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
@@ -39,16 +39,16 @@
39
39
  */
40
40
  import { z } from 'zod';
41
41
  import { type ToolContract } from './toolContract.ts';
42
- export declare const wikiMapContract: ToolContract<z.ZodObject<{}, z.core.$strip>>;
43
- export declare const wikiReadContract: ToolContract<z.ZodObject<{
42
+ export declare const wikiMapContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{}, z.core.$strip>, string>;
43
+ export declare const wikiReadContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
44
44
  path: z.ZodString;
45
45
  section: z.ZodOptional<z.ZodString>;
46
- }, z.core.$strip>>;
47
- export declare const wikiSearchContract: ToolContract<z.ZodObject<{
46
+ }, z.core.$strip>, string>;
47
+ export declare const wikiSearchContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
48
48
  query: z.ZodString;
49
49
  limit: z.ZodDefault<z.ZodNumber>;
50
- }, z.core.$strip>>;
51
- export declare const wikiLinksContract: ToolContract<z.ZodObject<{
50
+ }, z.core.$strip>, string>;
51
+ export declare const wikiLinksContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
52
52
  path: z.ZodString;
53
53
  depth: z.ZodDefault<z.ZodNumber>;
54
54
  direction: z.ZodDefault<z.ZodEnum<{
@@ -56,12 +56,12 @@ export declare const wikiLinksContract: ToolContract<z.ZodObject<{
56
56
  in: "in";
57
57
  out: "out";
58
58
  }>>;
59
- }, z.core.$strip>>;
60
- export declare const wikiDiveContract: ToolContract<z.ZodObject<{
59
+ }, z.core.$strip>, string>;
60
+ export declare const wikiDiveContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
61
61
  task: z.ZodString;
62
62
  budget_words: z.ZodDefault<z.ZodNumber>;
63
- }, z.core.$strip>>;
64
- export declare const wikiGraphContract: ToolContract<z.ZodObject<{
63
+ }, z.core.$strip>, string>;
64
+ export declare const wikiGraphContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
65
65
  node: z.ZodOptional<z.ZodString>;
66
66
  find: z.ZodOptional<z.ZodString>;
67
67
  kind: z.ZodOptional<z.ZodString>;
@@ -74,29 +74,29 @@ export declare const wikiGraphContract: ToolContract<z.ZodObject<{
74
74
  out: "out";
75
75
  }>>;
76
76
  limit: z.ZodDefault<z.ZodNumber>;
77
- }, z.core.$strip>>;
78
- export declare const wikiRelateContract: ToolContract<z.ZodObject<{
77
+ }, z.core.$strip>, string>;
78
+ export declare const wikiRelateContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
79
79
  from: z.ZodString;
80
80
  to: z.ZodString;
81
81
  relation: z.ZodString;
82
82
  evidence: z.ZodString;
83
83
  actor: z.ZodString;
84
84
  note: z.ZodOptional<z.ZodString>;
85
- }, z.core.$strip>>;
86
- export declare const wikiSaveContract: ToolContract<z.ZodObject<{
85
+ }, z.core.$strip>, string>;
86
+ export declare const wikiSaveContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
87
87
  path: z.ZodString;
88
88
  content: z.ZodString;
89
89
  actor: z.ZodString;
90
90
  summary: z.ZodString;
91
- }, z.core.$strip>>;
92
- export declare const wikiQueryContract: ToolContract<z.ZodObject<{
91
+ }, z.core.$strip>, string>;
92
+ export declare const wikiQueryContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
93
93
  question: z.ZodString;
94
94
  model: z.ZodOptional<z.ZodString>;
95
- }, z.core.$strip>>;
96
- export declare const wikiGardenContract: ToolContract<z.ZodObject<{
95
+ }, z.core.$strip>, string>;
96
+ export declare const wikiGardenContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
97
97
  instruction: z.ZodString;
98
98
  model: z.ZodOptional<z.ZodString>;
99
- }, z.core.$strip>>;
99
+ }, z.core.$strip>, string>;
100
100
  /** Everything an MCP client may be offered (see the wiki MCP server script). */
101
101
  export declare const WIKI_TOOL_CONTRACTS: readonly ToolContract<any>[];
102
102
  /**
@@ -43,12 +43,13 @@ import { runWikiAgent } from '../wiki/agentRun.js';
43
43
  import { appendLog, indexSpec, upsertDoc } from '../wiki/builder.js';
44
44
  import { repoDive, scoreDocs } from '../wiki/dive.js';
45
45
  import { actorSchema, BUILD_ACTOR, CONCEPT_TYPES, isPrivatePath, isReservedFilename, trustTier, } from '../wiki/format.js';
46
- import { edgeKey, entityStats, findNodes, isPrivateNode, loadEntityGraph, loadRelations, neighbors, nodesOfKind, NODE_KINDS, RELATIONS, relationsByTier, saveRelations, shortestPath, snapshotDrift, } from '../wiki/entities.js';
46
+ import { appendRelation, edgeKey, entityStats, findNodes, isPrivateNode, loadEntityGraph, loadRelations, neighbors, nodesOfKind, NODE_KINDS, RELATIONS, relationsByTier, shortestPath, snapshotDrift, } from '../wiki/entities.js';
47
47
  import { buildGraph, graphStats, neighborhood } from '../wiki/graph.js';
48
48
  import { formatLintReport, lintDoc, lintVault } from '../wiki/lint.js';
49
49
  import { sectionSlice } from '../wiki/markdown.js';
50
50
  import { docsInDirectory, jailedAbsPath, loadVault, lookupTarget, makeWikiDoc, resolveLinkTarget, resolveWikiRoot, writeDocFile, } from '../wiki/vault.js';
51
- import { defineTool, toFunctionTool } from './toolContract.js';
51
+ import { toFunctionTool } from './adkTool.js';
52
+ import { defineTool } from './toolContract.js';
52
53
  // ── Shared helpers ───────────────────────────────────────────────────────────
53
54
  function todayIso() {
54
55
  return new Date().toISOString().slice(0, 10);
@@ -474,11 +475,6 @@ export const wikiRelateContract = defineTool({
474
475
  if (fromNode.kind === 'doc' && !isPrivateNode(fromNode) && isPrivateNode(toNode)) {
475
476
  return `REJECTED — ${fromNode.id} is a public document and ${toNode.id} is private knowledge. Public documents never point into the private annex; move the claim to a /private/ document instead.`;
476
477
  }
477
- const { records } = loadRelations(root);
478
- const key = edgeKey({ from: fromNode.id, rel: relation, to: toNode.id });
479
- if (records.some((r) => edgeKey(r) === key)) {
480
- return `UNCHANGED — ${key} is already asserted. wiki_graph on either node shows it.`;
481
- }
482
478
  const record = {
483
479
  from: fromNode.id,
484
480
  to: toNode.id,
@@ -488,9 +484,17 @@ export const wikiRelateContract = defineTool({
488
484
  at: todayIso(),
489
485
  ...(note ? { note } : {}),
490
486
  };
491
- saveRelations(root, [...records, record]);
487
+ // Appended at the end, never re-sorted: relations.json merges by keeping both sides.
488
+ try {
489
+ if (!appendRelation(root, record)) {
490
+ return `UNCHANGED — ${edgeKey(record)} is already asserted. wiki_graph on either node shows it.`;
491
+ }
492
+ }
493
+ catch (err) {
494
+ return `REJECTED — the relation store could not be appended to, so nothing was written: ${err instanceof Error ? err.message : String(err)}. Fix .graph/relations.json first.`;
495
+ }
492
496
  appendLog(root, todayIso(), 'relate', `${fromNode.id} —${relation}→ ${toNode.id}`, `by ${actor}`, logTargetFor(isPrivateNode(fromNode) || isPrivateNode(toNode)));
493
- const reverse = records.find((r) => r.from === toNode.id && r.to === fromNode.id && r.rel === relation);
497
+ const reverse = loadRelations(root).records.find((r) => r.from === toNode.id && r.to === fromNode.id && r.rel === relation);
494
498
  return [
495
499
  `ASSERTED ${fromNode.id} —${relation}→ ${toNode.id} · logged to /log.md`,
496
500
  `reads: ${fromNode.label} ${RELATIONS[relation].phrase} ${toNode.label}`,
@@ -179,7 +179,7 @@ export interface XApiSearchInput {
179
179
  }
180
180
  /** One page of X, rendered for an agent. Never throws — see the header. */
181
181
  export declare function runXApiSearch(input: XApiSearchInput, deps?: XApiDeps): Promise<string>;
182
- export declare const xApiSearchContract: import("./toolContract.ts").ToolContract<z.ZodObject<{
182
+ export declare const xApiSearchContract: import("./toolContract.ts").DefinedTool<z.ZodObject<{
183
183
  query: z.ZodOptional<z.ZodString>;
184
184
  post: z.ZodOptional<z.ZodString>;
185
185
  days: z.ZodOptional<z.ZodNumber>;
@@ -189,6 +189,6 @@ export declare const xApiSearchContract: import("./toolContract.ts").ToolContrac
189
189
  }>>;
190
190
  max_results: z.ZodOptional<z.ZodNumber>;
191
191
  read_images: z.ZodOptional<z.ZodBoolean>;
192
- }, z.core.$strip>>;
192
+ }, z.core.$strip>, string>;
193
193
  /** ADK surface, registered under its contract name in lib/toolRegistry.ts. */
194
194
  export declare const xApiSearchTool: import("@google/adk").FunctionTool<undefined>;
@@ -57,7 +57,8 @@
57
57
  */
58
58
  import { GoogleGenAI } from '@google/genai';
59
59
  import { z } from 'zod';
60
- import { defineTool, toFunctionTool } from './toolContract.js';
60
+ import { toFunctionTool } from './adkTool.js';
61
+ import { defineTool } from './toolContract.js';
61
62
  export const X_API_SEARCH_TOOL_NAME = 'x_api_search';
62
63
  const API = 'https://api.x.com/2';
63
64
  /** Unit cost of a post read, USD — one place, dated in the header. */
@@ -35,8 +35,11 @@
35
35
  */
36
36
  import { BaseTool } from '@google/adk';
37
37
  import type { LlmRequest } from '@google/adk';
38
+ import { NATIVE_TOOL } from './tool.ts';
38
39
  export declare const X_SEARCH_TOOL_NAME = "x_search";
40
+ /** The ADK runtime's form of X_SEARCH_MARKER (lib/tools/nativeTools.ts), carrying its marker. */
39
41
  export declare class XSearchTool extends BaseTool {
42
+ readonly [NATIVE_TOOL]: import("../model.ts").NativeTool;
40
43
  constructor();
41
44
  /** Never a client-side function tool — xAI runs the search server-side. */
42
45
  _getDeclaration(): undefined;
@@ -48,14 +51,9 @@ export declare class XSearchTool extends BaseTool {
48
51
  }
49
52
  /** Shared instance, mirroring WEB_SEARCH. */
50
53
  export declare const X_SEARCH: XSearchTool;
51
- /** True when the agent requested X search (xAI sentinel path). */
54
+ /** True when the agent requested X search (xAI sentinel path), by marker. */
52
55
  export declare function wantsXSearch(llmRequest: LlmRequest): boolean;
53
- /** Sentinel test used by the request builder to skip function-tool emission. */
56
+ /** Sentinel test used by the request builder to skip function-tool emission: the x_search marker, on either form. */
54
57
  export declare function isXSearchSentinel(tool: unknown): boolean;
55
- /**
56
- * Optional server-side constraints for the x_search tool, read from the
57
- * environment at request-build time (see WHICH CONSTRAINTS above). With
58
- * nothing configured this returns {} and the tool ships bare, exactly as
59
- * it always has.
60
- */
61
- export declare function xSearchParamsFromEnv(): Record<string, unknown>;
58
+ /** The XAI_X_SEARCH_* reader lives in lib/tools/xaiSearchParams.ts (no @google/adk); re-exported here under its old name. */
59
+ export { xSearchParamsFromEnv } from './xaiSearchParams.ts';
@@ -35,14 +35,14 @@
35
35
  */
36
36
  import { BaseTool } from '@google/adk';
37
37
  import { providerForModel } from '../models/providerMap.js';
38
+ import { X_SEARCH_MARKER } from './nativeTools.js';
39
+ import { NATIVE_TOOL, nativeToolMarkerOf } from './tool.js';
38
40
  export const X_SEARCH_TOOL_NAME = 'x_search';
41
+ /** The ADK runtime's form of X_SEARCH_MARKER (lib/tools/nativeTools.ts), carrying its marker. */
39
42
  export class XSearchTool extends BaseTool {
43
+ [NATIVE_TOOL] = X_SEARCH_MARKER[NATIVE_TOOL];
40
44
  constructor() {
41
- super({
42
- name: X_SEARCH_TOOL_NAME,
43
- description: 'Live search over X (Twitter) posts via xAI Agent Tools — ' +
44
- 'grok-* models only; a no-op sentinel on every other provider.',
45
- });
45
+ super({ name: X_SEARCH_TOOL_NAME, description: X_SEARCH_MARKER.description });
46
46
  }
47
47
  /** Never a client-side function tool — xAI runs the search server-side. */
48
48
  _getDeclaration() {
@@ -62,64 +62,13 @@ export class XSearchTool extends BaseTool {
62
62
  }
63
63
  /** Shared instance, mirroring WEB_SEARCH. */
64
64
  export const X_SEARCH = new XSearchTool();
65
- /** True when the agent requested X search (xAI sentinel path). */
65
+ /** True when the agent requested X search (xAI sentinel path), by marker. */
66
66
  export function wantsXSearch(llmRequest) {
67
- return llmRequest.toolsDict?.[X_SEARCH_TOOL_NAME] instanceof XSearchTool;
67
+ return isXSearchSentinel(llmRequest.toolsDict?.[X_SEARCH_TOOL_NAME]);
68
68
  }
69
- /** Sentinel test used by the request builder to skip function-tool emission. */
69
+ /** Sentinel test used by the request builder to skip function-tool emission: the x_search marker, on either form. */
70
70
  export function isXSearchSentinel(tool) {
71
- return tool instanceof XSearchTool;
72
- }
73
- /** xAI's documented ceiling on allowed_x_handles / excluded_x_handles. */
74
- const X_SEARCH_MAX_HANDLES = 20;
75
- /** ISO date (YYYY-MM-DD) from an env var; malformed values warn and drop. */
76
- function isoDateFromEnv(name) {
77
- const raw = process.env[name]?.trim();
78
- if (!raw)
79
- return undefined;
80
- if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
81
- console.warn(`[x_search] ${name}="${raw}" is not YYYY-MM-DD — ignored.`);
82
- return undefined;
83
- }
84
- return raw;
85
- }
86
- /** Comma-separated handles from an env var; trimmed, @-stripped, capped. */
87
- function handlesFromEnv(name) {
88
- const handles = (process.env[name] ?? '')
89
- .split(',')
90
- .map((h) => h.trim().replace(/^@/, ''))
91
- .filter(Boolean);
92
- if (handles.length > X_SEARCH_MAX_HANDLES) {
93
- console.warn(`[x_search] ${name} lists ${handles.length} handles — xAI caps the ` +
94
- `list at ${X_SEARCH_MAX_HANDLES}; keeping the first ${X_SEARCH_MAX_HANDLES}.`);
95
- return handles.slice(0, X_SEARCH_MAX_HANDLES);
96
- }
97
- return handles;
98
- }
99
- /**
100
- * Optional server-side constraints for the x_search tool, read from the
101
- * environment at request-build time (see WHICH CONSTRAINTS above). With
102
- * nothing configured this returns {} and the tool ships bare, exactly as
103
- * it always has.
104
- */
105
- export function xSearchParamsFromEnv() {
106
- const params = {};
107
- const from = isoDateFromEnv('XAI_X_SEARCH_FROM_DATE');
108
- const to = isoDateFromEnv('XAI_X_SEARCH_TO_DATE');
109
- if (from)
110
- params.from_date = from;
111
- if (to)
112
- params.to_date = to;
113
- const allowed = handlesFromEnv('XAI_X_SEARCH_ALLOWED_HANDLES');
114
- const excluded = handlesFromEnv('XAI_X_SEARCH_EXCLUDED_HANDLES');
115
- if (allowed.length > 0 && excluded.length > 0) {
116
- console.warn('[x_search] XAI_X_SEARCH_ALLOWED_HANDLES and _EXCLUDED_HANDLES are ' +
117
- 'mutually exclusive (xAI rejects both together) — keeping the ' +
118
- 'allowlist, dropping the exclusions.');
119
- }
120
- if (allowed.length > 0)
121
- params.allowed_x_handles = allowed;
122
- else if (excluded.length > 0)
123
- params.excluded_x_handles = excluded;
124
- return params;
71
+ return nativeToolMarkerOf(tool) === 'x_search';
125
72
  }
73
+ /** The XAI_X_SEARCH_* reader lives in lib/tools/xaiSearchParams.ts (no @google/adk); re-exported here under its old name. */
74
+ export { xSearchParamsFromEnv } from './xaiSearchParams.js';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * lib/tools/xaiSearchParams.ts — the deployment settings for xAI's
3
+ * server-side search tools, read from the environment at request-build time.
4
+ *
5
+ * WHY its own module: GrokAdapter (lib/models/grokAdapter.ts) reads these
6
+ * on the engine's own contract, and the tool modules that also export them
7
+ * (webSearchTool.ts, xSearchTool.ts, collectionsSearchTool.ts) extend ADK's
8
+ * BaseTool. Here they import nothing, so the `melchizedek-agents/model`
9
+ * entry reaches no @google/adk. The tool modules re-export each reader under
10
+ * its old name.
11
+ *
12
+ * THE DOCTRINE (unchanged): constraints are deployment configuration, never
13
+ * YAML, so the YAML stays shareable. Misconfiguration degrades with a
14
+ * warning, never fatally.
15
+ * - web_search (docs.x.ai/developers/tools/web-search, 2026-08-08):
16
+ * allowed_domains / excluded_domains, at most 5 each and mutually
17
+ * exclusive, nested under `filters`. No date bounds. xAI only: OpenAI's
18
+ * web_search takes no such params.
19
+ * - x_search (docs.x.ai/developers/tools/x-search, 2026-08-02):
20
+ * from_date / to_date (YYYY-MM-DD) and allowed_x_handles /
21
+ * excluded_x_handles, at most 20 each and mutually exclusive.
22
+ * - collections_search: XAI_COLLECTION_IDS (comma-separated) and an
23
+ * optional XAI_COLLECTIONS_MAX_RESULTS cap.
24
+ * When both lists of a pair are set, the allowlist wins. Oversize lists
25
+ * truncate. Malformed dates are dropped.
26
+ */
27
+ /**
28
+ * Optional server-side domain filters for xAI's web_search tool. With
29
+ * nothing configured this returns {} and the tool ships bare. xAI only:
30
+ * apply on the xAI path, never on OpenAI's web_search.
31
+ */
32
+ export declare function xaiWebSearchParamsFromEnv(): Record<string, unknown>;
33
+ /**
34
+ * Optional server-side constraints for the x_search tool. With nothing
35
+ * configured this returns {} and the tool ships bare.
36
+ */
37
+ export declare function xSearchParamsFromEnv(): Record<string, unknown>;
38
+ /** Collection ids from XAI_COLLECTION_IDS (comma-separated, trimmed). */
39
+ export declare function collectionIdsFromEnv(): string[];
40
+ /** Optional retrieval cap from XAI_COLLECTIONS_MAX_RESULTS (positive int). */
41
+ export declare function collectionsMaxResultsFromEnv(): number | undefined;
@@ -0,0 +1,126 @@
1
+ /**
2
+ * lib/tools/xaiSearchParams.ts — the deployment settings for xAI's
3
+ * server-side search tools, read from the environment at request-build time.
4
+ *
5
+ * WHY its own module: GrokAdapter (lib/models/grokAdapter.ts) reads these
6
+ * on the engine's own contract, and the tool modules that also export them
7
+ * (webSearchTool.ts, xSearchTool.ts, collectionsSearchTool.ts) extend ADK's
8
+ * BaseTool. Here they import nothing, so the `melchizedek-agents/model`
9
+ * entry reaches no @google/adk. The tool modules re-export each reader under
10
+ * its old name.
11
+ *
12
+ * THE DOCTRINE (unchanged): constraints are deployment configuration, never
13
+ * YAML, so the YAML stays shareable. Misconfiguration degrades with a
14
+ * warning, never fatally.
15
+ * - web_search (docs.x.ai/developers/tools/web-search, 2026-08-08):
16
+ * allowed_domains / excluded_domains, at most 5 each and mutually
17
+ * exclusive, nested under `filters`. No date bounds. xAI only: OpenAI's
18
+ * web_search takes no such params.
19
+ * - x_search (docs.x.ai/developers/tools/x-search, 2026-08-02):
20
+ * from_date / to_date (YYYY-MM-DD) and allowed_x_handles /
21
+ * excluded_x_handles, at most 20 each and mutually exclusive.
22
+ * - collections_search: XAI_COLLECTION_IDS (comma-separated) and an
23
+ * optional XAI_COLLECTIONS_MAX_RESULTS cap.
24
+ * When both lists of a pair are set, the allowlist wins. Oversize lists
25
+ * truncate. Malformed dates are dropped.
26
+ */
27
+ /** xAI's documented ceiling on allowed_domains / excluded_domains. */
28
+ const XAI_WEB_SEARCH_MAX_DOMAINS = 5;
29
+ /** xAI's documented ceiling on allowed_x_handles / excluded_x_handles. */
30
+ const X_SEARCH_MAX_HANDLES = 20;
31
+ /** Comma-separated domains from an env var; trimmed, capped at xAI's limit. */
32
+ function domainsFromEnv(name) {
33
+ const domains = (process.env[name] ?? '')
34
+ .split(',')
35
+ .map((d) => d.trim())
36
+ .filter(Boolean);
37
+ if (domains.length > XAI_WEB_SEARCH_MAX_DOMAINS) {
38
+ console.warn(`[web_search] ${name} lists ${domains.length} domains — xAI caps the ` +
39
+ `list at ${XAI_WEB_SEARCH_MAX_DOMAINS}; keeping the first ${XAI_WEB_SEARCH_MAX_DOMAINS}.`);
40
+ return domains.slice(0, XAI_WEB_SEARCH_MAX_DOMAINS);
41
+ }
42
+ return domains;
43
+ }
44
+ /**
45
+ * Optional server-side domain filters for xAI's web_search tool. With
46
+ * nothing configured this returns {} and the tool ships bare. xAI only:
47
+ * apply on the xAI path, never on OpenAI's web_search.
48
+ */
49
+ export function xaiWebSearchParamsFromEnv() {
50
+ const allowed = domainsFromEnv('XAI_WEB_SEARCH_ALLOWED_DOMAINS');
51
+ const excluded = domainsFromEnv('XAI_WEB_SEARCH_EXCLUDED_DOMAINS');
52
+ if (allowed.length > 0 && excluded.length > 0) {
53
+ console.warn('[web_search] XAI_WEB_SEARCH_ALLOWED_DOMAINS and _EXCLUDED_DOMAINS are ' +
54
+ 'mutually exclusive (xAI rejects both together) — keeping the ' +
55
+ 'allowlist, dropping the exclusions.');
56
+ }
57
+ if (allowed.length > 0)
58
+ return { filters: { allowed_domains: allowed } };
59
+ if (excluded.length > 0)
60
+ return { filters: { excluded_domains: excluded } };
61
+ return {};
62
+ }
63
+ /** ISO date (YYYY-MM-DD) from an env var; malformed values warn and drop. */
64
+ function isoDateFromEnv(name) {
65
+ const raw = process.env[name]?.trim();
66
+ if (!raw)
67
+ return undefined;
68
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
69
+ console.warn(`[x_search] ${name}="${raw}" is not YYYY-MM-DD — ignored.`);
70
+ return undefined;
71
+ }
72
+ return raw;
73
+ }
74
+ /** Comma-separated handles from an env var; trimmed, @-stripped, capped. */
75
+ function handlesFromEnv(name) {
76
+ const handles = (process.env[name] ?? '')
77
+ .split(',')
78
+ .map((h) => h.trim().replace(/^@/, ''))
79
+ .filter(Boolean);
80
+ if (handles.length > X_SEARCH_MAX_HANDLES) {
81
+ console.warn(`[x_search] ${name} lists ${handles.length} handles — xAI caps the ` +
82
+ `list at ${X_SEARCH_MAX_HANDLES}; keeping the first ${X_SEARCH_MAX_HANDLES}.`);
83
+ return handles.slice(0, X_SEARCH_MAX_HANDLES);
84
+ }
85
+ return handles;
86
+ }
87
+ /**
88
+ * Optional server-side constraints for the x_search tool. With nothing
89
+ * configured this returns {} and the tool ships bare.
90
+ */
91
+ export function xSearchParamsFromEnv() {
92
+ const params = {};
93
+ const from = isoDateFromEnv('XAI_X_SEARCH_FROM_DATE');
94
+ const to = isoDateFromEnv('XAI_X_SEARCH_TO_DATE');
95
+ if (from)
96
+ params.from_date = from;
97
+ if (to)
98
+ params.to_date = to;
99
+ const allowed = handlesFromEnv('XAI_X_SEARCH_ALLOWED_HANDLES');
100
+ const excluded = handlesFromEnv('XAI_X_SEARCH_EXCLUDED_HANDLES');
101
+ if (allowed.length > 0 && excluded.length > 0) {
102
+ console.warn('[x_search] XAI_X_SEARCH_ALLOWED_HANDLES and _EXCLUDED_HANDLES are ' +
103
+ 'mutually exclusive (xAI rejects both together) — keeping the ' +
104
+ 'allowlist, dropping the exclusions.');
105
+ }
106
+ if (allowed.length > 0)
107
+ params.allowed_x_handles = allowed;
108
+ else if (excluded.length > 0)
109
+ params.excluded_x_handles = excluded;
110
+ return params;
111
+ }
112
+ /** Collection ids from XAI_COLLECTION_IDS (comma-separated, trimmed). */
113
+ export function collectionIdsFromEnv() {
114
+ return (process.env.XAI_COLLECTION_IDS ?? '')
115
+ .split(',')
116
+ .map((id) => id.trim())
117
+ .filter(Boolean);
118
+ }
119
+ /** Optional retrieval cap from XAI_COLLECTIONS_MAX_RESULTS (positive int). */
120
+ export function collectionsMaxResultsFromEnv() {
121
+ const raw = process.env.XAI_COLLECTIONS_MAX_RESULTS?.trim();
122
+ if (!raw)
123
+ return undefined;
124
+ const n = Number(raw);
125
+ return Number.isInteger(n) && n > 0 ? n : undefined;
126
+ }
@@ -15,8 +15,16 @@
15
15
  * provider — wiki operations inherit the framework's full model
16
16
  * optionality. A missing provider key degrades to a clear error string;
17
17
  * nothing here throws for want of credentials.
18
+ *
19
+ * The runtime follows the turn runner's flag (lib/runtime/runtimeFlag.ts):
20
+ * MELCHIZEDEK_RUNTIME, or the run's `runtime` option. On `native` the
21
+ * same agent runs on the engine's own loop (lib/runtime/nativeTurn.ts),
22
+ * each wiki FunctionTool as the own Tool behind it, and its events are
23
+ * read the same way.
18
24
  */
19
25
  import type { FunctionTool } from '@google/adk';
26
+ import type { ModelAdapter } from '../models/contract.ts';
27
+ import type { RuntimeName } from '../runtime/runtimeFlag.ts';
20
28
  export interface WikiAgentRun {
21
29
  name: string;
22
30
  description: string;
@@ -26,6 +34,10 @@ export interface WikiAgentRun {
26
34
  tools?: FunctionTool[];
27
35
  temperature?: number;
28
36
  maxOutputTokens?: number;
37
+ /** The runtime that runs the agent. Default: MELCHIZEDEK_RUNTIME, else adk. */
38
+ runtime?: RuntimeName;
39
+ /** Native runtime only: the leaf adapter for a model id. Default resolveAdapter (lib/models/registry.ts). */
40
+ adapterFor?: (model: string) => ModelAdapter;
29
41
  }
30
42
  export interface WikiAgentResult {
31
43
  text: string;
@@ -15,10 +15,21 @@
15
15
  * provider — wiki operations inherit the framework's full model
16
16
  * optionality. A missing provider key degrades to a clear error string;
17
17
  * nothing here throws for want of credentials.
18
+ *
19
+ * The runtime follows the turn runner's flag (lib/runtime/runtimeFlag.ts):
20
+ * MELCHIZEDEK_RUNTIME, or the run's `runtime` option. On `native` the
21
+ * same agent runs on the engine's own loop (lib/runtime/nativeTurn.ts),
22
+ * each wiki FunctionTool as the own Tool behind it, and its events are
23
+ * read the same way.
18
24
  */
19
25
  import { randomUUID } from 'node:crypto';
20
26
  import { InMemorySessionService, LlmAgent, Runner } from '@google/adk';
21
- import { providerForModel, providerKeyPresent, registerAvailableProviders, } from '../models/registry.js';
27
+ import { providerForModel, providerKeyPresent, registerAvailableProviders, resolveAdapter, } from '../models/registry.js';
28
+ import { SelfCorrection } from '../runtime/native/selfCorrection.js';
29
+ import { runNativeAgent } from '../runtime/nativeTurn.js';
30
+ import { chooseRuntime } from '../runtime/runtimeFlag.js';
31
+ import { InProcessSessionService } from '../runtime/sessions.js';
32
+ import { toolOf } from '../tools/tool.js';
22
33
  /** True when the model's provider has credentials (Ollama needs none). */
23
34
  export function modelAvailable(model) {
24
35
  const provider = providerForModel(model);
@@ -26,43 +37,26 @@ export function modelAvailable(model) {
26
37
  return { ok: true };
27
38
  return { ok: false, reason: `provider "${provider}" has no API key configured` };
28
39
  }
29
- export async function runWikiAgent(run) {
30
- const availability = modelAvailable(run.model);
31
- if (!availability.ok) {
32
- return { text: '', error: availability.reason };
33
- }
34
- registerAvailableProviders();
35
- const agent = new LlmAgent({
36
- name: run.name,
37
- description: run.description,
38
- model: run.model,
39
- instruction: run.instruction,
40
- generateContentConfig: {
41
- temperature: run.temperature ?? 0.3,
42
- maxOutputTokens: run.maxOutputTokens ?? 4096,
43
- },
44
- ...(run.tools && run.tools.length > 0 ? { tools: run.tools } : {}),
45
- });
46
- const appName = 'melchizedek-wiki';
47
- const userId = 'wiki';
48
- const sessionId = randomUUID();
49
- const sessionService = new InMemorySessionService();
50
- const runner = new Runner({ agent, appName, sessionService });
51
- await sessionService.createSession({ appName, userId, sessionId, state: {} });
40
+ const APP_NAME = 'melchizedek-wiki';
41
+ const USER_ID = 'wiki';
42
+ /** The generateContentConfig every wiki run sends. */
43
+ function configOf(run) {
44
+ return {
45
+ temperature: run.temperature ?? 0.3,
46
+ maxOutputTokens: run.maxOutputTokens ?? 4096,
47
+ };
48
+ }
49
+ /** Reads a run's events, either runtime: every non-thinking text part, and the last error. */
50
+ async function readRun(stream) {
52
51
  let outputText = '';
53
52
  let errorText = '';
54
53
  try {
55
- const stream = runner.runAsync({
56
- userId,
57
- sessionId,
58
- newMessage: { role: 'user', parts: [{ text: run.userText }] },
59
- });
60
- for await (const event of stream) {
61
- const evAny = event;
62
- if ((evAny.errorCode || evAny.errorMessage) && evAny.errorCode !== 'STOP') {
63
- errorText = `[${evAny.errorCode ?? 'ERROR'}] ${evAny.errorMessage ?? ''}`;
54
+ for await (const event of stream()) {
55
+ const e = event;
56
+ if ((e.errorCode || e.errorMessage) && e.errorCode !== 'STOP') {
57
+ errorText = `[${e.errorCode ?? 'ERROR'}] ${e.errorMessage ?? ''}`;
64
58
  }
65
- for (const part of event.content?.parts ?? []) {
59
+ for (const part of e.content?.parts ?? []) {
66
60
  const p = part;
67
61
  if (!p.thought && p.text)
68
62
  outputText += p.text;
@@ -77,3 +71,47 @@ export async function runWikiAgent(run) {
77
71
  ...(errorText ? { error: errorText } : {}),
78
72
  };
79
73
  }
74
+ export async function runWikiAgent(run) {
75
+ const availability = modelAvailable(run.model);
76
+ if (!availability.ok) {
77
+ return { text: '', error: availability.reason };
78
+ }
79
+ const sessionId = randomUUID();
80
+ const newMessage = { role: 'user', parts: [{ text: run.userText }] };
81
+ if (chooseRuntime(run.runtime) === 'native') {
82
+ const agent = {
83
+ name: run.name,
84
+ description: run.description,
85
+ model: run.model,
86
+ instruction: run.instruction,
87
+ generateContentConfig: configOf(run),
88
+ tools: (run.tools ?? []).map((t) => toolOf(t) ?? t),
89
+ };
90
+ const sessions = new InProcessSessionService();
91
+ await sessions.create({ appName: APP_NAME, userId: USER_ID, sessionId });
92
+ return readRun(() => runNativeAgent({
93
+ agent,
94
+ adapterFor: run.adapterFor ?? ((model) => resolveAdapter(model)),
95
+ sessions,
96
+ appName: APP_NAME,
97
+ userId: USER_ID,
98
+ sessionId,
99
+ userParts: newMessage.parts,
100
+ // As on ADK, where this Runner installs no reflect-and-retry plugins.
101
+ selfCorrection: new SelfCorrection({ model_errors: 0, tool_errors: 0 }),
102
+ }));
103
+ }
104
+ registerAvailableProviders();
105
+ const agent = new LlmAgent({
106
+ name: run.name,
107
+ description: run.description,
108
+ model: run.model,
109
+ instruction: run.instruction,
110
+ generateContentConfig: configOf(run),
111
+ ...(run.tools && run.tools.length > 0 ? { tools: run.tools } : {}),
112
+ });
113
+ const sessionService = new InMemorySessionService();
114
+ const runner = new Runner({ agent, appName: APP_NAME, sessionService });
115
+ await sessionService.createSession({ appName: APP_NAME, userId: USER_ID, sessionId, state: {} });
116
+ return readRun(() => runner.runAsync({ userId: USER_ID, sessionId, newMessage }));
117
+ }
@@ -182,7 +182,19 @@ export interface LoadedRelations {
182
182
  }
183
183
  export declare function loadRelations(wikiRoot: string): LoadedRelations;
184
184
  export declare function relationEdges(records: RelationRecord[]): EntityEdge[];
185
+ /**
186
+ * Replace the whole store with `records`, in the order given. The store's
187
+ * order is the order of assertion; nothing sorts it.
188
+ */
185
189
  export declare function saveRelations(wikiRoot: string, records: RelationRecord[]): void;
190
+ /**
191
+ * Add one assertion at the end of the store. Every record already there
192
+ * keeps its place and its bytes, so two branches that each assert something
193
+ * merge by keeping both sides. Returns false, writing nothing, when the edge
194
+ * is already asserted. Throws when the store does not parse rather than
195
+ * write over it.
196
+ */
197
+ export declare function appendRelation(wikiRoot: string, record: RelationRecord): boolean;
186
198
  export interface GraphSnapshot {
187
199
  version: number;
188
200
  generated: {