melchizedek-agents 0.18.0 → 0.19.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 (281) hide show
  1. package/.env.example +12 -0
  2. package/CHANGELOG.md +825 -0
  3. package/DOCUMENTATION.md +217 -59
  4. package/README.md +42 -1
  5. package/config/agents/examples/harness.yaml +3 -1
  6. package/config/agents/examples/model_zoo.yaml +10 -9
  7. package/config/agents/syndicateSchema.yaml +50 -16
  8. package/config/agents/templates/account_memory.yaml +2 -6
  9. package/config/agents/templates/case_desk.yaml +3 -9
  10. package/config/agents/templates/draft_review.yaml +3 -9
  11. package/config/agents/templates/intake_extractor.yaml +1 -3
  12. package/config/agents/templates/research_brief.yaml +3 -9
  13. package/config/agents/templates/research_desk.yaml +3 -9
  14. package/config/agents/templates/review_panel.yaml +4 -12
  15. package/config/agents/templates/support_triage.yaml +4 -12
  16. package/config/agents/templates/systems_operator.yaml +2 -6
  17. package/db/hardening.sql +7 -1
  18. package/db/migrations/0013_tool_credentials.sql +260 -0
  19. package/dist/lib/a2a/app.d.ts +70 -6
  20. package/dist/lib/a2a/app.js +107 -2
  21. package/dist/lib/a2a/executor.d.ts +20 -3
  22. package/dist/lib/a2a/executor.js +66 -7
  23. package/dist/lib/a2a/remoteAgent.d.ts +24 -9
  24. package/dist/lib/a2a/remoteAgent.js +31 -14
  25. package/dist/lib/compile.d.ts +121 -30
  26. package/dist/lib/compile.js +137 -124
  27. package/dist/lib/compileAdk.d.ts +29 -0
  28. package/dist/lib/compileAdk.js +132 -0
  29. package/dist/lib/compileNative.d.ts +85 -0
  30. package/dist/lib/compileNative.js +222 -0
  31. package/dist/lib/config.d.ts +6 -5
  32. package/dist/lib/config.js +6 -5
  33. package/dist/lib/doctor.js +1 -0
  34. package/dist/lib/index.d.ts +2 -1
  35. package/dist/lib/index.js +2 -1
  36. package/dist/lib/loadSyndicate.d.ts +18 -0
  37. package/dist/lib/memory/erase.d.ts +5 -3
  38. package/dist/lib/memory/erase.js +5 -2
  39. package/dist/lib/memory/namespace.d.ts +8 -1
  40. package/dist/lib/memory/namespace.js +12 -6
  41. package/dist/lib/memory/providers.js +2 -1
  42. package/dist/lib/memory/supabaseMemoryService.d.ts +37 -3
  43. package/dist/lib/memory/supabaseMemoryService.js +42 -2
  44. package/dist/lib/model.d.ts +47 -0
  45. package/dist/lib/model.js +37 -0
  46. package/dist/lib/models/adapterResolver.d.ts +113 -0
  47. package/dist/lib/models/adapterResolver.js +136 -0
  48. package/dist/lib/models/adkGeminiAdapter.d.ts +90 -0
  49. package/dist/lib/models/adkGeminiAdapter.js +367 -0
  50. package/dist/lib/models/adkShim.d.ts +111 -0
  51. package/dist/lib/models/adkShim.js +136 -0
  52. package/dist/lib/models/capabilities.d.ts +3 -0
  53. package/dist/lib/models/capabilities.js +20 -13
  54. package/dist/lib/models/chatCompletionsAdapter.d.ts +279 -0
  55. package/dist/lib/models/chatCompletionsAdapter.js +854 -0
  56. package/dist/lib/models/circuitBreaker.d.ts +42 -0
  57. package/dist/lib/models/circuitBreaker.js +70 -0
  58. package/dist/lib/models/claudeAdapter.d.ts +103 -0
  59. package/dist/lib/models/claudeAdapter.js +669 -0
  60. package/dist/lib/models/claudeLlm.d.ts +39 -62
  61. package/dist/lib/models/claudeLlm.js +44 -349
  62. package/dist/lib/models/claudeModels.d.ts +127 -0
  63. package/dist/lib/models/claudeModels.js +237 -0
  64. package/dist/lib/models/contract.d.ts +395 -0
  65. package/dist/lib/models/contract.js +39 -0
  66. package/dist/lib/models/endpoints.js +2 -1
  67. package/dist/lib/models/errorResponse.d.ts +50 -0
  68. package/dist/lib/models/errorResponse.js +48 -0
  69. package/dist/lib/models/fallback.d.ts +17 -10
  70. package/dist/lib/models/fallback.js +53 -42
  71. package/dist/lib/models/fallbackAdapter.d.ts +55 -0
  72. package/dist/lib/models/fallbackAdapter.js +62 -0
  73. package/dist/lib/models/gateway.js +2 -1
  74. package/dist/lib/models/gatewayAdapter.d.ts +51 -0
  75. package/dist/lib/models/gatewayAdapter.js +81 -0
  76. package/dist/lib/models/gatewayLlm.d.ts +12 -33
  77. package/dist/lib/models/gatewayLlm.js +14 -75
  78. package/dist/lib/models/geminiAdapter.d.ts +123 -0
  79. package/dist/lib/models/geminiAdapter.js +831 -0
  80. package/dist/lib/models/geminiState.d.ts +25 -0
  81. package/dist/lib/models/geminiState.js +25 -0
  82. package/dist/lib/models/genaiMapping.d.ts +263 -0
  83. package/dist/lib/models/genaiMapping.js +862 -0
  84. package/dist/lib/models/gptAdapter.d.ts +240 -0
  85. package/dist/lib/models/gptAdapter.js +804 -0
  86. package/dist/lib/models/gptLlm.d.ts +63 -123
  87. package/dist/lib/models/gptLlm.js +88 -602
  88. package/dist/lib/models/grokAdapter.d.ts +86 -0
  89. package/dist/lib/models/grokAdapter.js +142 -0
  90. package/dist/lib/models/grokLlm.d.ts +22 -45
  91. package/dist/lib/models/grokLlm.js +22 -67
  92. package/dist/lib/models/kimiAdapter.d.ts +157 -0
  93. package/dist/lib/models/kimiAdapter.js +203 -0
  94. package/dist/lib/models/kimiLlm.d.ts +15 -107
  95. package/dist/lib/models/kimiLlm.js +17 -153
  96. package/dist/lib/models/ollamaAdapter.d.ts +125 -0
  97. package/dist/lib/models/ollamaAdapter.js +155 -0
  98. package/dist/lib/models/ollamaLlm.d.ts +11 -107
  99. package/dist/lib/models/ollamaLlm.js +13 -151
  100. package/dist/lib/models/openAiCompatibleLlm.d.ts +73 -216
  101. package/dist/lib/models/openAiCompatibleLlm.js +109 -671
  102. package/dist/lib/models/providerState.d.ts +63 -0
  103. package/dist/lib/models/providerState.js +61 -0
  104. package/dist/lib/models/reasoning.d.ts +26 -0
  105. package/dist/lib/models/reasoning.js +59 -0
  106. package/dist/lib/models/registry.d.ts +58 -35
  107. package/dist/lib/models/registry.js +89 -118
  108. package/dist/lib/models/retry.d.ts +2 -1
  109. package/dist/lib/models/retry.js +3 -2
  110. package/dist/lib/models/schemaNormalize.d.ts +98 -0
  111. package/dist/lib/models/schemaNormalize.js +321 -1
  112. package/dist/lib/models/tracedGemini.d.ts +41 -0
  113. package/dist/lib/models/tracedGemini.js +98 -0
  114. package/dist/lib/models/urls.d.ts +11 -0
  115. package/dist/lib/models/urls.js +16 -0
  116. package/dist/lib/net/redirects.d.ts +21 -2
  117. package/dist/lib/net/redirects.js +11 -34
  118. package/dist/lib/observability/audit.d.ts +5 -1
  119. package/dist/lib/observability/lineage.d.ts +14 -0
  120. package/dist/lib/observability/lineage.js +33 -0
  121. package/dist/lib/observability/supabaseSpanExporter.d.ts +10 -4
  122. package/dist/lib/observability/supabaseSpanExporter.js +17 -9
  123. package/dist/lib/observability/tracer.d.ts +26 -8
  124. package/dist/lib/observability/tracer.js +43 -18
  125. package/dist/lib/runtime/adkMemoryBridge.d.ts +46 -0
  126. package/dist/lib/runtime/adkMemoryBridge.js +68 -0
  127. package/dist/lib/runtime/adkSessionBridge.d.ts +78 -0
  128. package/dist/lib/runtime/adkSessionBridge.js +176 -0
  129. package/dist/lib/runtime/credentials.d.ts +59 -0
  130. package/dist/lib/runtime/credentials.js +62 -0
  131. package/dist/lib/runtime/events.d.ts +229 -0
  132. package/dist/lib/runtime/events.js +274 -0
  133. package/dist/lib/runtime/logging.d.ts +32 -0
  134. package/dist/lib/runtime/logging.js +55 -0
  135. package/dist/lib/runtime/memoryService.d.ts +72 -0
  136. package/dist/lib/runtime/memoryService.js +25 -0
  137. package/dist/lib/runtime/native/agentLoop.d.ts +203 -0
  138. package/dist/lib/runtime/native/agentLoop.js +687 -0
  139. package/dist/lib/runtime/native/compaction.d.ts +103 -0
  140. package/dist/lib/runtime/native/compaction.js +191 -0
  141. package/dist/lib/runtime/native/delegate.d.ts +98 -0
  142. package/dist/lib/runtime/native/delegate.js +173 -0
  143. package/dist/lib/runtime/native/history.d.ts +83 -0
  144. package/dist/lib/runtime/native/history.js +312 -0
  145. package/dist/lib/runtime/native/interrupts.d.ts +126 -0
  146. package/dist/lib/runtime/native/interrupts.js +291 -0
  147. package/dist/lib/runtime/native/request.d.ts +215 -0
  148. package/dist/lib/runtime/native/request.js +585 -0
  149. package/dist/lib/runtime/native/selfCorrection.d.ts +106 -0
  150. package/dist/lib/runtime/native/selfCorrection.js +253 -0
  151. package/dist/lib/runtime/native/step.d.ts +148 -0
  152. package/dist/lib/runtime/native/step.js +239 -0
  153. package/dist/lib/runtime/native/taskMode.d.ts +64 -0
  154. package/dist/lib/runtime/native/taskMode.js +126 -0
  155. package/dist/lib/runtime/native/telemetry.d.ts +75 -0
  156. package/dist/lib/runtime/native/telemetry.js +299 -0
  157. package/dist/lib/runtime/native/tempState.d.ts +31 -0
  158. package/dist/lib/runtime/native/tempState.js +56 -0
  159. package/dist/lib/runtime/nativeTurn.d.ts +86 -0
  160. package/dist/lib/runtime/nativeTurn.js +107 -0
  161. package/dist/lib/runtime/questions.d.ts +29 -7
  162. package/dist/lib/runtime/questions.js +47 -32
  163. package/dist/lib/runtime/runtimeFlag.d.ts +30 -0
  164. package/dist/lib/runtime/runtimeFlag.js +50 -0
  165. package/dist/lib/runtime/sessions.d.ts +166 -0
  166. package/dist/lib/runtime/sessions.js +201 -0
  167. package/dist/lib/runtime/syndicateTurn.d.ts +41 -5
  168. package/dist/lib/runtime/syndicateTurn.js +202 -32
  169. package/dist/lib/session/supabaseSessionService.d.ts +64 -17
  170. package/dist/lib/session/supabaseSessionService.js +148 -105
  171. package/dist/lib/session/transcript.d.ts +68 -22
  172. package/dist/lib/session/transcript.js +102 -28
  173. package/dist/lib/skills.js +33 -7
  174. package/dist/lib/storage/postgres/credentialStore.d.ts +20 -0
  175. package/dist/lib/storage/postgres/credentialStore.js +82 -0
  176. package/dist/lib/storage/postgres/index.d.ts +12 -0
  177. package/dist/lib/storage/postgres/index.js +6 -1
  178. package/dist/lib/storage/postgres/sessionService.d.ts +43 -15
  179. package/dist/lib/storage/postgres/sessionService.js +128 -66
  180. package/dist/lib/syndicateSchema.d.ts +47 -0
  181. package/dist/lib/syndicateSchema.js +72 -3
  182. package/dist/lib/toolRegistry.d.ts +15 -2
  183. package/dist/lib/toolRegistry.js +33 -17
  184. package/dist/lib/tools/adkTool.d.ts +81 -0
  185. package/dist/lib/tools/adkTool.js +268 -0
  186. package/dist/lib/tools/auth.d.ts +118 -0
  187. package/dist/lib/tools/auth.js +89 -0
  188. package/dist/lib/tools/collectionsSearchTool.d.ts +7 -6
  189. package/dist/lib/tools/collectionsSearchTool.js +11 -26
  190. package/dist/lib/tools/credentialCipher.d.ts +58 -0
  191. package/dist/lib/tools/credentialCipher.js +116 -0
  192. package/dist/lib/tools/credentialStore.d.ts +77 -0
  193. package/dist/lib/tools/credentialStore.js +246 -0
  194. package/dist/lib/tools/examples.d.ts +43 -0
  195. package/dist/lib/tools/examples.js +62 -0
  196. package/dist/lib/tools/generateImageTool.d.ts +15 -6
  197. package/dist/lib/tools/generateImageTool.js +19 -29
  198. package/dist/lib/tools/inspectImageTool.d.ts +9 -6
  199. package/dist/lib/tools/inspectImageTool.js +13 -17
  200. package/dist/lib/tools/mcpToolFactory.d.ts +42 -1
  201. package/dist/lib/tools/mcpToolFactory.js +46 -47
  202. package/dist/lib/tools/memoryTools.d.ts +61 -0
  203. package/dist/lib/tools/memoryTools.js +119 -0
  204. package/dist/lib/tools/nativeTools.d.ts +38 -0
  205. package/dist/lib/tools/nativeTools.js +43 -0
  206. package/dist/lib/tools/oauthConsent.d.ts +181 -0
  207. package/dist/lib/tools/oauthConsent.js +330 -0
  208. package/dist/lib/tools/openapi/call.d.ts +108 -0
  209. package/dist/lib/tools/openapi/call.js +295 -0
  210. package/dist/lib/tools/openapi/parse.d.ts +147 -0
  211. package/dist/lib/tools/openapi/parse.js +570 -0
  212. package/dist/lib/tools/openapiTools.d.ts +25 -17
  213. package/dist/lib/tools/openapiTools.js +124 -121
  214. package/dist/lib/tools/scienceTools.d.ts +14 -14
  215. package/dist/lib/tools/skillToolset.d.ts +58 -87
  216. package/dist/lib/tools/skillToolset.js +61 -142
  217. package/dist/lib/tools/skills/env.d.ts +58 -0
  218. package/dist/lib/tools/skills/env.js +165 -0
  219. package/dist/lib/tools/skills/executor.d.ts +114 -0
  220. package/dist/lib/tools/skills/executor.js +331 -0
  221. package/dist/lib/tools/skills/frontmatter.d.ts +79 -0
  222. package/dist/lib/tools/skills/frontmatter.js +215 -0
  223. package/dist/lib/tools/skills/loader.d.ts +91 -0
  224. package/dist/lib/tools/skills/loader.js +257 -0
  225. package/dist/lib/tools/skills/tools.d.ts +187 -0
  226. package/dist/lib/tools/skills/tools.js +386 -0
  227. package/dist/lib/tools/taskTools.d.ts +15 -15
  228. package/dist/lib/tools/tool.d.ts +354 -0
  229. package/dist/lib/tools/tool.js +304 -0
  230. package/dist/lib/tools/toolContract.d.ts +89 -33
  231. package/dist/lib/tools/toolContract.js +104 -82
  232. package/dist/lib/tools/urlContextTool.d.ts +3 -0
  233. package/dist/lib/tools/urlContextTool.js +5 -1
  234. package/dist/lib/tools/webExtractTool.d.ts +2 -2
  235. package/dist/lib/tools/webExtractTool.js +2 -1
  236. package/dist/lib/tools/webSearchTool.d.ts +6 -9
  237. package/dist/lib/tools/webSearchTool.js +14 -59
  238. package/dist/lib/tools/wikiTools.d.ts +19 -19
  239. package/dist/lib/tools/wikiTools.js +13 -9
  240. package/dist/lib/tools/xApiSearchTool.d.ts +2 -2
  241. package/dist/lib/tools/xApiSearchTool.js +2 -1
  242. package/dist/lib/tools/xSearchTool.d.ts +7 -9
  243. package/dist/lib/tools/xSearchTool.js +11 -62
  244. package/dist/lib/tools/xaiSearchParams.d.ts +41 -0
  245. package/dist/lib/tools/xaiSearchParams.js +126 -0
  246. package/dist/lib/wiki/agentRun.d.ts +12 -0
  247. package/dist/lib/wiki/agentRun.js +72 -34
  248. package/dist/lib/wiki/entities.d.ts +12 -0
  249. package/dist/lib/wiki/entities.js +45 -3
  250. package/dist/lib/workflow/agentNode.d.ts +136 -0
  251. package/dist/lib/workflow/agentNode.js +274 -0
  252. package/dist/lib/workflow/graph.d.ts +177 -0
  253. package/dist/lib/workflow/graph.js +458 -0
  254. package/dist/lib/workflow/nodeEvents.d.ts +50 -0
  255. package/dist/lib/workflow/nodeEvents.js +101 -0
  256. package/dist/lib/workflow/pause.d.ts +122 -0
  257. package/dist/lib/workflow/pause.js +180 -0
  258. package/dist/lib/workflow/resume.d.ts +165 -0
  259. package/dist/lib/workflow/resume.js +440 -0
  260. package/dist/lib/workflow/route.d.ts +58 -0
  261. package/dist/lib/workflow/route.js +69 -0
  262. package/dist/lib/workflow/scheduler.d.ts +415 -0
  263. package/dist/lib/workflow/scheduler.js +743 -0
  264. package/dist/lib/workflow/toolNode.d.ts +127 -0
  265. package/dist/lib/workflow/toolNode.js +236 -0
  266. package/dist/lib/workflow/turn.d.ts +118 -0
  267. package/dist/lib/workflow/turn.js +216 -0
  268. package/dist/lib/workflowConfig.d.ts +3 -2
  269. package/dist/lib/workflowConfig.js +3 -12
  270. package/dist/scripts/a2a_server.js +4 -3
  271. package/dist/scripts/assistant_worker.d.ts +2 -1
  272. package/dist/scripts/assistant_worker.js +9 -4
  273. package/dist/scripts/syndicate_chat.js +19 -10
  274. package/package.json +4 -1
  275. package/skills/briefs/melchizedek-author.md +3 -2
  276. package/skills/briefs/melchizedek-models.md +13 -9
  277. package/skills/briefs/melchizedek.md +3 -3
  278. package/skills/melchizedek/SKILL.md +2 -1
  279. package/skills/melchizedek-author/SKILL.md +2 -1
  280. package/skills/melchizedek-author/assets/minimal.yaml +2 -0
  281. package/skills/melchizedek-models/SKILL.md +23 -6
@@ -0,0 +1,176 @@
1
+ /**
2
+ * lib/runtime/adkSessionBridge.ts — one session store, either runtime
3
+ * (ADR 0045, ADR 0052, ADR 0058).
4
+ *
5
+ * WHY this file exists:
6
+ * Until ADK leaves at 1.0, the ADK runtime asks for ADK's
7
+ * BaseSessionService and the native runtime for the engine's
8
+ * SessionService (lib/runtime/sessions.ts). The durable stores and the
9
+ * transcript projection implement both, so they need no bridge. A store
10
+ * that implements only one of them gets the other here:
11
+ * - SessionServiceForAdk: the ADK runtime on an engine store, such as
12
+ * InProcessSessionService.
13
+ * - AdkSessionServiceForEngine: the engine's interface on an ADK store,
14
+ * such as ADK's InMemorySessionService, with the interface's meaning
15
+ * where ADK's store has another (sessions.ts, "ONE MEANING ACROSS
16
+ * STORES").
17
+ * asAdkSessionService and asSessionService hand a store back as it is
18
+ * when it already implements the face asked for, and a bridge back as the
19
+ * store it wraps, so a store bridged one way and then back is itself.
20
+ * A surface that takes a store from its caller (the A2A executor and app,
21
+ * the REPL) types it as EitherSessionService and asks for the face it
22
+ * needs here (ADR 0080).
23
+ *
24
+ * APPEND: each face keeps its own runtime's rules for the caller's session.
25
+ * The ADK face applies an event to the runner's session through ADK's
26
+ * base service, write-order check and all, exactly as the durable stores
27
+ * do, and the store records it on a copy. The engine face applies it
28
+ * through applyEvent, which never changes the caller's event, and hands
29
+ * ADK's store a copy.
30
+ *
31
+ * This module loads ADK at run time, so it is not one of the engine's leaf
32
+ * modules (tests/events.test.ts names those).
33
+ */
34
+ import { BaseSessionService } from '@google/adk';
35
+ import { applyEvent, listPage, listWindow, selectEvents, withoutTempKeys } from './sessions.js';
36
+ /** Every method the engine's interface names. */
37
+ export function isSessionService(value) {
38
+ const v = value;
39
+ return (typeof v === 'object' && v !== null &&
40
+ typeof v.create === 'function' && typeof v.get === 'function' && typeof v.list === 'function' &&
41
+ typeof v.delete === 'function' && typeof v.append === 'function');
42
+ }
43
+ /**
44
+ * Every method ADK's runner and services call. A duck check rather than
45
+ * instanceof, so a store built against another copy of ADK still counts.
46
+ */
47
+ export function isAdkSessionService(value) {
48
+ const v = value;
49
+ return (typeof v === 'object' && v !== null &&
50
+ typeof v.createSession === 'function' && typeof v.getSession === 'function' &&
51
+ typeof v.listSessions === 'function' && typeof v.deleteSession === 'function' &&
52
+ typeof v.appendEvent === 'function');
53
+ }
54
+ /**
55
+ * A copy a store may apply an event to without touching the caller's
56
+ * session: applyEvent and ADK's base service change only `state`'s keys,
57
+ * the `events` array and `lastUpdateTime`.
58
+ */
59
+ function shadowOf(session) {
60
+ return { ...session, state: { ...session.state }, events: [...session.events] };
61
+ }
62
+ /** The key fields only: a request object can carry more. */
63
+ function keyOf(request) {
64
+ return { appName: request.appName, userId: request.userId, sessionId: request.sessionId };
65
+ }
66
+ // ── The ADK runtime on an engine store ───────────────────────────────────────
67
+ /** ADK's BaseSessionService over an engine SessionService. */
68
+ export class SessionServiceForAdk extends BaseSessionService {
69
+ service;
70
+ constructor(service) {
71
+ super();
72
+ this.service = service;
73
+ }
74
+ async createSession(request) {
75
+ return (await this.service.create(request));
76
+ }
77
+ async getSession(request) {
78
+ return (await this.service.get(keyOf(request), request.config));
79
+ }
80
+ async listSessions(request) {
81
+ return (await this.service.list(request));
82
+ }
83
+ async deleteSession(request) {
84
+ await this.service.delete(keyOf(request));
85
+ }
86
+ async appendEvent({ session, event }) {
87
+ if (event.partial)
88
+ return event;
89
+ // The store applies the event once, to the session as it stood.
90
+ const before = shadowOf(session);
91
+ await super.appendEvent({ session, event });
92
+ session.lastUpdateTime = event.timestamp;
93
+ await this.service.append(before, event);
94
+ return event;
95
+ }
96
+ }
97
+ // ── The engine's interface on an ADK store ───────────────────────────────────
98
+ /** The engine's SessionService over an ADK BaseSessionService. */
99
+ export class AdkSessionServiceForEngine {
100
+ service;
101
+ constructor(service) {
102
+ this.service = service;
103
+ }
104
+ /** A session that exists comes back unchanged: ADK's own store would reset it. */
105
+ async create(request) {
106
+ if (request.sessionId) {
107
+ const existing = await this.get({ appName: request.appName, userId: request.userId, sessionId: request.sessionId });
108
+ if (existing)
109
+ return existing;
110
+ }
111
+ const created = await this.service.createSession({
112
+ appName: request.appName,
113
+ userId: request.userId,
114
+ sessionId: request.sessionId,
115
+ state: withoutTempKeys(request.state ?? {}),
116
+ });
117
+ return created;
118
+ }
119
+ /** Reads the whole session and filters it here, so `options` mean what the interface says. */
120
+ async get(key, options) {
121
+ const held = (await this.service.getSession(keyOf(key)));
122
+ if (!held)
123
+ return undefined;
124
+ return { ...held, events: selectEvents(held.events, options) };
125
+ }
126
+ /** The window goes to ADK's store as an offset; the paging figures are the interface's. */
127
+ async list(request) {
128
+ const { offset, limit } = listWindow(request);
129
+ const listed = await this.service.listSessions({
130
+ appName: request.appName,
131
+ userId: request.userId,
132
+ order: request.order,
133
+ offset,
134
+ limit,
135
+ });
136
+ return {
137
+ sessions: listed.sessions.map((s) => ({ ...s, events: [] })),
138
+ ...listPage(listed.totalItems, request),
139
+ };
140
+ }
141
+ async delete(key) {
142
+ await this.service.deleteSession(keyOf(key));
143
+ }
144
+ async append(session, event) {
145
+ if (event.partial)
146
+ return event;
147
+ // ADK's base service applies an event to the session it is given and
148
+ // rewrites the event's delta in place, so ADK's store gets copies of
149
+ // both, and the session as it stood.
150
+ const before = shadowOf(session);
151
+ const stored = applyEvent(session, event);
152
+ await this.service.appendEvent({ session: before, event: structuredClone(stored) });
153
+ return stored;
154
+ }
155
+ }
156
+ // ── Either face of a store ───────────────────────────────────────────────────
157
+ /** The store as the ADK runtime takes it: itself when it already is one. */
158
+ export function asAdkSessionService(service) {
159
+ if (service instanceof AdkSessionServiceForEngine)
160
+ return service.service;
161
+ if (isAdkSessionService(service))
162
+ return service;
163
+ if (isSessionService(service))
164
+ return new SessionServiceForAdk(service);
165
+ throw new TypeError('Not a session service: it implements neither SessionService nor ADK\'s BaseSessionService.');
166
+ }
167
+ /** The store as the engine's interface: itself when it already is one. */
168
+ export function asSessionService(service) {
169
+ if (service instanceof SessionServiceForAdk)
170
+ return service.service;
171
+ if (isSessionService(service))
172
+ return service;
173
+ if (isAdkSessionService(service))
174
+ return new AdkSessionServiceForEngine(service);
175
+ throw new TypeError('Not a session service: it implements neither SessionService nor ADK\'s BaseSessionService.');
176
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * lib/runtime/credentials.ts — reading and answering a tool's OAuth consent
3
+ * request in a session (WS6-3b, ADR 0085).
4
+ *
5
+ * A tool that needs a grant the person has not given asks for it
6
+ * (`ctx.requestCredential(provider)`). The run stores ADK's own
7
+ * `adk_request_credential` call, as ADK's generateAuthEvent writes it: args
8
+ * `{ function_call_id, auth_config }`, an `adk-` id listed in
9
+ * longRunningToolIds. The auth_config carries the authorization URL and the
10
+ * state nonce, never a client secret or a code verifier
11
+ * (lib/tools/oauthConsent.ts). The turn ends input-required with the
12
+ * request (`result.consent`).
13
+ *
14
+ * The person completes the flow in their browser; the server's callback
15
+ * stores the grant. Their next message, once the grant is stored, becomes a
16
+ * function response to the request (`credentialResponsePart`), and the
17
+ * agent's loop runs the paused call again before its next step
18
+ * (lib/runtime/native/interrupts.ts grantedCalls). Until the grant is
19
+ * stored, a message repeats the request and runs nothing.
20
+ */
21
+ import type { Event } from '@google/adk';
22
+ /** ADK's name for the credential request (REQUEST_CREDENTIAL_FUNCTION_CALL_NAME). */
23
+ export declare const CREDENTIAL_REQUEST = "adk_request_credential";
24
+ /** A paused call waiting for the person to grant a provider. */
25
+ export interface PendingConsent {
26
+ /** The `adk_request_credential` call's id: what the answer names. */
27
+ id: string;
28
+ /** The agent whose call is paused. */
29
+ agent: string;
30
+ /** The paused call's id. */
31
+ functionCallId: string;
32
+ /** The provider, as the credential store names it (the AuthConfig's credentialKey). */
33
+ provider: string;
34
+ /** The authorization URL the person opens. */
35
+ authUri: string;
36
+ /** The state nonce the URL carries. */
37
+ state: string;
38
+ scopes: string[];
39
+ }
40
+ /** The request an `adk_request_credential` call carries, or undefined when it is not one this engine reads. */
41
+ export declare function consentFrom(author: string | undefined, call: {
42
+ name?: string;
43
+ id?: string;
44
+ args?: Record<string, unknown>;
45
+ }): PendingConsent | undefined;
46
+ /**
47
+ * The consent request still waiting in a session, or undefined. One that is
48
+ * answered (a function response with its id), or that the person moved past
49
+ * with a text message, is not pending.
50
+ */
51
+ export declare function pendingConsent(events: readonly Event[]): PendingConsent | undefined;
52
+ /**
53
+ * The message part that answers request `id` once the grant is stored. It
54
+ * names the provider and carries no credential: the grant is in the
55
+ * credential store, and the resumed call reads it from there.
56
+ */
57
+ export declare function credentialResponsePart(id: string, provider: string): Record<string, unknown>;
58
+ /** One line a person can read: what they are asked to connect. */
59
+ export declare function describeConsent(c: PendingConsent): string;
@@ -0,0 +1,62 @@
1
+ /** ADK's name for the credential request (REQUEST_CREDENTIAL_FUNCTION_CALL_NAME). */
2
+ export const CREDENTIAL_REQUEST = 'adk_request_credential';
3
+ const partsOf = (e) => (e.content?.parts ?? []);
4
+ const hasUserText = (e) => e.author === 'user' && partsOf(e).some((p) => typeof p.text === 'string' && p.text.trim() && !p.thought);
5
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
6
+ /** The request an `adk_request_credential` call carries, or undefined when it is not one this engine reads. */
7
+ export function consentFrom(author, call) {
8
+ if (call.name !== CREDENTIAL_REQUEST || !call.id || !isRecord(call.args))
9
+ return undefined;
10
+ const functionCallId = call.args.function_call_id ?? call.args.functionCallId;
11
+ const config = call.args.auth_config ?? call.args.authConfig;
12
+ if (typeof functionCallId !== 'string' || !isRecord(config))
13
+ return undefined;
14
+ const oauth2 = isRecord(config.exchangedAuthCredential) && isRecord(config.exchangedAuthCredential.oauth2) ? config.exchangedAuthCredential.oauth2 : {};
15
+ const flows = isRecord(config.authScheme) && isRecord(config.authScheme.flows) ? config.authScheme.flows : {};
16
+ const scopes = isRecord(flows.authorizationCode) && isRecord(flows.authorizationCode.scopes) ? Object.keys(flows.authorizationCode.scopes) : [];
17
+ return {
18
+ id: call.id,
19
+ agent: author ?? '',
20
+ functionCallId,
21
+ provider: typeof config.credentialKey === 'string' ? config.credentialKey : '',
22
+ authUri: typeof oauth2.authUri === 'string' ? oauth2.authUri : '',
23
+ state: typeof oauth2.state === 'string' ? oauth2.state : '',
24
+ scopes,
25
+ };
26
+ }
27
+ /**
28
+ * The consent request still waiting in a session, or undefined. One that is
29
+ * answered (a function response with its id), or that the person moved past
30
+ * with a text message, is not pending.
31
+ */
32
+ export function pendingConsent(events) {
33
+ const answered = new Set();
34
+ for (let i = events.length - 1; i >= 0; i--) {
35
+ const e = events[i];
36
+ if (hasUserText(e))
37
+ return undefined;
38
+ for (const p of partsOf(e)) {
39
+ if (p.functionResponse?.name === CREDENTIAL_REQUEST && p.functionResponse.id)
40
+ answered.add(p.functionResponse.id);
41
+ }
42
+ for (const p of partsOf(e)) {
43
+ const call = p.functionCall;
44
+ if (call?.name !== CREDENTIAL_REQUEST || !call.id || answered.has(call.id))
45
+ continue;
46
+ return consentFrom(e.author, call);
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+ /**
52
+ * The message part that answers request `id` once the grant is stored. It
53
+ * names the provider and carries no credential: the grant is in the
54
+ * credential store, and the resumed call reads it from there.
55
+ */
56
+ export function credentialResponsePart(id, provider) {
57
+ return { functionResponse: { id, name: CREDENTIAL_REQUEST, response: { credentialKey: provider, granted: true } } };
58
+ }
59
+ /** One line a person can read: what they are asked to connect. */
60
+ export function describeConsent(c) {
61
+ return `${c.agent} needs access to your ${c.provider} account`;
62
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * lib/runtime/events.ts — the engine's own event type: one step of a
3
+ * conversation as a session stores it (ADR 0045, ADR 0052).
4
+ *
5
+ * WHY this file exists:
6
+ * The native runtime reads and writes the sessions ADK wrote, and the
7
+ * stored Event JSON in adk_sessions.events and adk_session_events is one of
8
+ * the four shapes ADR 0045 fixes. So the engine's event is not a new
9
+ * format: TurnEvent IS that JSON, typed. Every field the engine reads has
10
+ * ADK's name, position in the object and meaning, and a TurnEvent
11
+ * serializes to the bytes ADK would have stored (tests/events.test.ts
12
+ * proves it on every session fixture, in both stored forms). The content
13
+ * stays @google/genai `Content` in shape, described here structurally;
14
+ * the model contract (lib/models/contract.ts) is what a model call speaks,
15
+ * reached through lib/models/genaiMapping.ts (ADR 0048 item 8).
16
+ *
17
+ * THE PARSE CARRIES EVERYTHING:
18
+ * parseTurnEvent checks the type of every field this file declares and
19
+ * returns the same object, never a projection. A field ADK writes that the
20
+ * engine does not know (a live-streaming field, a part's videoMetadata, the
21
+ * camelCase toolCall some providers emit) is kept as it is, in place. That
22
+ * matters because the Supabase service rewrites a conversation's whole
23
+ * events array on every append: a parse that dropped an unknown field would
24
+ * erase it from every stored row the native runtime touched. It rejects
25
+ * only what the engine cannot read, with the path of the field and the
26
+ * type it found, never the value, since events hold what people said.
27
+ *
28
+ * NO RUNTIME IMPORTS: every import here is a type. Nothing in this module's
29
+ * import graph names @google/* (tests/events.test.ts asserts it), so the
30
+ * native runtime can read sessions with ADK uninstalled.
31
+ */
32
+ import type { ProviderState } from '../models/contract.ts';
33
+ /** A tool call the model made: `part.functionCall`. */
34
+ export interface TurnFunctionCall {
35
+ /** ADK's `adk-<uuid>`, or the provider's id. Absent in a request ADK built: it strips its own ids. */
36
+ id?: string;
37
+ name?: string;
38
+ args?: Record<string, unknown>;
39
+ }
40
+ /** A tool's answer: `part.functionResponse`. */
41
+ export interface TurnFunctionResponse {
42
+ /** The id of the call it answers. */
43
+ id?: string;
44
+ name?: string;
45
+ /**
46
+ * ADK wraps a result that is not an object as `{ result }`. In a trimmed
47
+ * row a result over 2,000 characters is `{ elided: '<size> chars dropped
48
+ * before storage — …' }` (trimEventForStorage, lib/session/transcript.ts).
49
+ */
50
+ response?: Record<string, unknown>;
51
+ }
52
+ /** One part of a content: genai's `Part`, with the fields the engine reads or writes. */
53
+ export interface TurnPart {
54
+ text?: string;
55
+ /** The text is the model's reasoning, shown but never replayed as speech. */
56
+ thought?: boolean;
57
+ /** Gemini's opaque signature. A trimmed row keeps only a call's, as `skip_thought_signature_validator`. */
58
+ thoughtSignature?: string;
59
+ functionCall?: TurnFunctionCall;
60
+ functionResponse?: TurnFunctionResponse;
61
+ inlineData?: {
62
+ mimeType?: string;
63
+ data?: string;
64
+ displayName?: string;
65
+ };
66
+ fileData?: {
67
+ mimeType?: string;
68
+ fileUri?: string;
69
+ displayName?: string;
70
+ };
71
+ executableCode?: {
72
+ code?: string;
73
+ language?: string;
74
+ };
75
+ codeExecutionResult?: {
76
+ outcome?: string;
77
+ output?: string;
78
+ };
79
+ /** Another provider's reasoning state (ADR 0046), stored whole on the part it belongs before. */
80
+ providerState?: ProviderState;
81
+ }
82
+ export interface TurnContent {
83
+ /** `user` or `model`. A tool's answer is a `user` content; ADK's confirmation request is too. */
84
+ role?: string;
85
+ parts?: TurnPart[];
86
+ }
87
+ /** A pending approval, keyed in `requestedToolConfirmations` by the gated call's id. */
88
+ export interface TurnToolConfirmation {
89
+ hint?: string;
90
+ confirmed?: boolean;
91
+ payload?: unknown;
92
+ }
93
+ /**
94
+ * What the event does besides speak: ADK's `EventActions`. ADK writes the
95
+ * four dictionaries on every event (createTurnEvent does too); they are
96
+ * optional here because a reader must not fail on a row that lacks one.
97
+ */
98
+ export interface TurnEventActions {
99
+ /** State writes. `temp:` keys never reach a store (applyEvent, lib/runtime/sessions.ts). */
100
+ stateDelta?: Record<string, unknown>;
101
+ /** Artifact name to version. */
102
+ artifactDelta?: Record<string, number>;
103
+ /** Auth configurations a tool asked for, by call id. */
104
+ requestedAuthConfigs?: Record<string, unknown>;
105
+ /** Approvals asked for, by the gated call's id (ADR 0028). */
106
+ requestedToolConfirmations?: Record<string, TurnToolConfirmation>;
107
+ /** The run ends on this tool response, without a model call to summarize it. */
108
+ skipSummarization?: boolean;
109
+ transferToAgent?: string;
110
+ escalate?: boolean;
111
+ /** A workflow node's checkpointed input, read back when a paused workflow resumes (ADR 0030). */
112
+ agentState?: Record<string, unknown>;
113
+ endOfAgent?: boolean;
114
+ }
115
+ /**
116
+ * `usageMetadata`, in Gemini's meanings: `candidatesTokenCount` excludes the
117
+ * thinking counted in `thoughtsTokenCount`. The turn runner sums it per
118
+ * turn: the largest prompt, every completion, every thought.
119
+ */
120
+ export interface TurnUsage {
121
+ promptTokenCount?: number;
122
+ candidatesTokenCount?: number;
123
+ thoughtsTokenCount?: number;
124
+ totalTokenCount?: number;
125
+ cachedContentTokenCount?: number;
126
+ toolUsePromptTokenCount?: number;
127
+ }
128
+ /** Where a workflow event came from (ADR 0030). */
129
+ export interface TurnNodeInfo {
130
+ /** The node path, e.g. `Pipeline.Triage`; the root's has no dot. */
131
+ path?: string;
132
+ outputFor?: string[];
133
+ messageAsOutput?: boolean;
134
+ }
135
+ export type TurnRouteKey = string | number | boolean;
136
+ /**
137
+ * One event of a session: the stored ADK Event JSON, typed. The first group
138
+ * is what the engine reads to run and resume a turn; the second is what ADK
139
+ * writes beside it, which the engine stores and reads back unchanged.
140
+ */
141
+ export interface TurnEvent {
142
+ /** Eight letters and digits (newEventId). An append with an id already in the session replaces that event. */
143
+ id: string;
144
+ /** Every event of one run shares it. ADK writes `e-<uuid>`. */
145
+ invocationId: string;
146
+ /** `user`, or the name of the agent or workflow node that wrote it. */
147
+ author?: string;
148
+ /** Absent on an event that only carries actions (a workflow's pause marker). */
149
+ content?: TurnContent;
150
+ actions: TurnEventActions;
151
+ /** A streaming fragment: shown, never stored. */
152
+ partial?: boolean;
153
+ /** The model finished this response. */
154
+ turnComplete?: boolean;
155
+ /** Milliseconds since the epoch. */
156
+ timestamp: number;
157
+ /** Labels an adapter attaches, e.g. `responses.server_tool_calls`; JSON only. */
158
+ customMetadata?: Record<string, unknown>;
159
+ /** Ids of this event's calls that wait for a person (`ask_user`, a workflow's input request). */
160
+ longRunningToolIds?: string[];
161
+ /** `parent.child` path that keeps a subagent's events from its peers. */
162
+ branch?: string;
163
+ /**
164
+ * A failure. Gemini reports its finish or block reason here, and `STOP` is
165
+ * not a failure: the turn runner ignores an error whose code is `STOP`.
166
+ */
167
+ errorCode?: string;
168
+ errorMessage?: string;
169
+ usageMetadata?: TurnUsage;
170
+ /** Gemini's finish reason, e.g. `STOP`. */
171
+ finishReason?: string;
172
+ /** Gemini search grounding: queries and sources (lib/grounding.ts reads it). */
173
+ groundingMetadata?: object;
174
+ citationMetadata?: object;
175
+ /** A live session was interrupted mid-answer. */
176
+ interrupted?: boolean;
177
+ modelVersion?: string;
178
+ /** A workflow node's result (ADR 0030). */
179
+ output?: unknown;
180
+ /** The route a workflow routing node chose. */
181
+ route?: TurnRouteKey | TurnRouteKey[];
182
+ nodeInfo?: TurnNodeInfo;
183
+ isolationScope?: string;
184
+ }
185
+ /** The event's tool calls, in order: the parts' `functionCall` objects themselves, not copies. */
186
+ export declare function getFunctionCalls(event: TurnEvent): TurnFunctionCall[];
187
+ /** The event's tool responses, in order: the parts' `functionResponse` objects themselves. */
188
+ export declare function getFunctionResponses(event: TurnEvent): TurnFunctionResponse[];
189
+ /** The last part is a code execution result: the model has more to say about it. */
190
+ export declare function hasTrailingCodeExecutionResult(event: TurnEvent): boolean;
191
+ /**
192
+ * The event ends its agent's run: ADK's `isFinalResponse`, case for case.
193
+ *
194
+ * Final at once when the run is meant to stop on it: a tool response that
195
+ * skips summarization (an approval request), a call that waits for a person
196
+ * (long-running ids), or a tool asking for auth. Otherwise final when it
197
+ * carries no tool call, no tool response, is not a streaming fragment, and
198
+ * does not end on a code execution result.
199
+ */
200
+ export declare function isFinal(event: TurnEvent): boolean;
201
+ /** A new event id: eight letters and digits, as ADK makes them. */
202
+ export declare function newEventId(): string;
203
+ /** Actions with ADK's four dictionaries present, then `actions` over them. */
204
+ export declare function createEventActions(actions?: TurnEventActions): TurnEventActions;
205
+ /** What createTurnEvent takes: any field, every one optional. */
206
+ export type TurnEventInit = Partial<Omit<TurnEvent, 'actions'>> & {
207
+ actions?: TurnEventActions;
208
+ };
209
+ /**
210
+ * A new event, built as ADK's `createEvent` builds one, so it serializes to
211
+ * the same JSON, key order included: the given fields first, then the
212
+ * defaults in ADK's order (an id, an empty invocation id, the four action
213
+ * dictionaries, no long-running ids, the time now).
214
+ */
215
+ export declare function createTurnEvent(init?: TurnEventInit): TurnEvent;
216
+ /** A stored event the engine cannot read, and where in it. */
217
+ export declare class TurnEventError extends Error {
218
+ /** e.g. `events[3].content.parts[0].functionCall.name` */
219
+ readonly path: string;
220
+ constructor(path: string, problem: string);
221
+ }
222
+ /**
223
+ * A stored event, checked: the same object, typed. Throws TurnEventError
224
+ * naming the first field the engine cannot read. Nothing is copied, added,
225
+ * dropped or reordered, so `JSON.stringify` of the result is the stored JSON.
226
+ */
227
+ export declare function parseTurnEvent(value: unknown, path?: string): TurnEvent;
228
+ /** A stored events array (a session's `events`, or a row's), checked the same way. */
229
+ export declare function parseTurnEvents(value: unknown, path?: string): TurnEvent[];