@botpress/adk 1.18.3 → 1.19.0-beta.3

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 (272) hide show
  1. package/dist/agent-init/agent-project-generator.d.ts +10 -7
  2. package/dist/agent-init/agent-project-generator.d.ts.map +1 -1
  3. package/dist/agent-project/agent-project.d.ts +1 -1
  4. package/dist/agent-project/agent-project.d.ts.map +1 -1
  5. package/dist/agent-project/component-files.d.ts +10 -0
  6. package/dist/agent-project/component-files.d.ts.map +1 -0
  7. package/dist/agent-project/component-index-writer.d.ts +22 -0
  8. package/dist/agent-project/component-index-writer.d.ts.map +1 -0
  9. package/dist/agent-project/config-writer.d.ts +5 -0
  10. package/dist/agent-project/config-writer.d.ts.map +1 -1
  11. package/dist/agent-project/index.d.ts +3 -0
  12. package/dist/agent-project/index.d.ts.map +1 -1
  13. package/dist/agent-project/lock-to-dependencies.d.ts +11 -0
  14. package/dist/agent-project/lock-to-dependencies.d.ts.map +1 -0
  15. package/dist/agent-project/types.d.ts +1 -0
  16. package/dist/agent-project/types.d.ts.map +1 -1
  17. package/dist/agent-project/validation-errors.d.ts +1 -0
  18. package/dist/agent-project/validation-errors.d.ts.map +1 -1
  19. package/dist/agent0/capabilities/commands/adk-build.md +39 -0
  20. package/dist/agent0/capabilities/commands/adk-debug.md +23 -0
  21. package/dist/agent0/capabilities/commands/adk-dev-console.md +17 -0
  22. package/dist/agent0/capabilities/commands/adk-document.md +68 -0
  23. package/dist/agent0/capabilities/commands/adk-eval.md +17 -0
  24. package/dist/agent0/capabilities/commands/adk-explain.md +22 -0
  25. package/dist/agent0/capabilities/commands/adk-init.md +30 -0
  26. package/dist/agent0/capabilities/commands/adk-ship.md +29 -0
  27. package/dist/agent0/capabilities/commands/adk-test.md +27 -0
  28. package/dist/agent0/capabilities/commands/adk-validate.md +31 -0
  29. package/dist/agent0/capabilities/skills/adk/SKILL.md +548 -0
  30. package/dist/agent0/capabilities/skills/adk/references/actions.md +823 -0
  31. package/dist/agent0/capabilities/skills/adk/references/advanced-patterns.md +669 -0
  32. package/dist/agent0/capabilities/skills/adk/references/agent-config.md +450 -0
  33. package/dist/agent0/capabilities/skills/adk/references/assets.md +237 -0
  34. package/dist/agent0/capabilities/skills/adk/references/autonomous-execution.md +747 -0
  35. package/dist/agent0/capabilities/skills/adk/references/cli.md +1093 -0
  36. package/dist/agent0/capabilities/skills/adk/references/context-api.md +461 -0
  37. package/dist/agent0/capabilities/skills/adk/references/conversation-lifecycle.md +311 -0
  38. package/dist/agent0/capabilities/skills/adk/references/conversations.md +1111 -0
  39. package/dist/agent0/capabilities/skills/adk/references/custom-components.md +167 -0
  40. package/dist/agent0/capabilities/skills/adk/references/desk.md +852 -0
  41. package/dist/agent0/capabilities/skills/adk/references/evals.md +11 -0
  42. package/dist/agent0/capabilities/skills/adk/references/explain-config.md +424 -0
  43. package/dist/agent0/capabilities/skills/adk/references/files.md +918 -0
  44. package/dist/agent0/capabilities/skills/adk/references/integration-actions.md +659 -0
  45. package/dist/agent0/capabilities/skills/adk/references/integrations.md +266 -0
  46. package/dist/agent0/capabilities/skills/adk/references/interfaces.md +97 -0
  47. package/dist/agent0/capabilities/skills/adk/references/knowledge-bases.md +456 -0
  48. package/dist/agent0/capabilities/skills/adk/references/mcp-server.md +112 -0
  49. package/dist/agent0/capabilities/skills/adk/references/messages.md +769 -0
  50. package/dist/agent0/capabilities/skills/adk/references/model-configuration.md +201 -0
  51. package/dist/agent0/capabilities/skills/adk/references/patterns-mistakes.md +469 -0
  52. package/dist/agent0/capabilities/skills/adk/references/plugins.md +280 -0
  53. package/dist/agent0/capabilities/skills/adk/references/tables.md +1136 -0
  54. package/dist/agent0/capabilities/skills/adk/references/tags.md +516 -0
  55. package/dist/agent0/capabilities/skills/adk/references/tools.md +581 -0
  56. package/dist/agent0/capabilities/skills/adk/references/triggers.md +719 -0
  57. package/dist/agent0/capabilities/skills/adk/references/workflow-steps.md +851 -0
  58. package/dist/agent0/capabilities/skills/adk/references/workflows.md +1408 -0
  59. package/dist/agent0/capabilities/skills/adk/references/zai-agent-reference.md +454 -0
  60. package/dist/agent0/capabilities/skills/adk/references/zai-complete-guide.md +1408 -0
  61. package/dist/agent0/capabilities/skills/adk-debugger/SKILL.md +257 -0
  62. package/dist/agent0/capabilities/skills/adk-debugger/references/common-failures.md +231 -0
  63. package/dist/agent0/capabilities/skills/adk-debugger/references/conversation-analysis.md +420 -0
  64. package/dist/agent0/capabilities/skills/adk-debugger/references/debug-workflow.md +239 -0
  65. package/dist/agent0/capabilities/skills/adk-debugger/references/llm-debugging.md +209 -0
  66. package/dist/agent0/capabilities/skills/adk-debugger/references/trace-summarization.md +313 -0
  67. package/dist/agent0/capabilities/skills/adk-debugger/references/traces-and-logs.md +195 -0
  68. package/dist/agent0/capabilities/skills/adk-dev-console/SKILL.md +111 -0
  69. package/dist/agent0/capabilities/skills/adk-dev-console/references/agent-steps.md +115 -0
  70. package/dist/agent0/capabilities/skills/adk-dev-console/references/component-registry.md +43 -0
  71. package/dist/agent0/capabilities/skills/adk-dev-console/references/multi-agent-dashboard.md +70 -0
  72. package/dist/agent0/capabilities/skills/adk-dev-console/references/pages.md +273 -0
  73. package/dist/agent0/capabilities/skills/adk-docs/SKILL.md +114 -0
  74. package/dist/agent0/capabilities/skills/adk-docs/references/doc-standards.md +124 -0
  75. package/dist/agent0/capabilities/skills/adk-evals/SKILL.md +244 -0
  76. package/dist/agent0/capabilities/skills/adk-evals/references/eval-format.md +354 -0
  77. package/dist/agent0/capabilities/skills/adk-evals/references/test-patterns.md +355 -0
  78. package/dist/agent0/capabilities/skills/adk-evals/references/testing-workflow.md +225 -0
  79. package/dist/agent0/config/index.d.ts +5 -0
  80. package/dist/agent0/config/index.d.ts.map +1 -0
  81. package/dist/agent0/config/paths.d.ts +12 -0
  82. package/dist/agent0/config/paths.d.ts.map +1 -0
  83. package/dist/agent0/config/schema.d.ts +171 -0
  84. package/dist/agent0/config/schema.d.ts.map +1 -0
  85. package/dist/agent0/config/secrets.d.ts +4 -0
  86. package/dist/agent0/config/secrets.d.ts.map +1 -0
  87. package/dist/agent0/config/store.d.ts +21 -0
  88. package/dist/agent0/config/store.d.ts.map +1 -0
  89. package/dist/agent0/index.d.ts +6 -0
  90. package/dist/agent0/index.d.ts.map +1 -0
  91. package/dist/agent0/index.js +3215 -0
  92. package/dist/agent0/index.js.map +27 -0
  93. package/dist/agent0/providers/catalog.d.ts +189 -0
  94. package/dist/agent0/providers/catalog.d.ts.map +1 -0
  95. package/dist/agent0/providers/index.d.ts +4 -0
  96. package/dist/agent0/providers/index.d.ts.map +1 -0
  97. package/dist/agent0/providers/registry.d.ts +32 -0
  98. package/dist/agent0/providers/registry.d.ts.map +1 -0
  99. package/dist/agent0/providers/source.d.ts +100 -0
  100. package/dist/agent0/providers/source.d.ts.map +1 -0
  101. package/dist/agent0/runtime/client.d.ts +50 -0
  102. package/dist/agent0/runtime/client.d.ts.map +1 -0
  103. package/dist/agent0/runtime/engine.d.ts +74 -0
  104. package/dist/agent0/runtime/engine.d.ts.map +1 -0
  105. package/dist/agent0/runtime/index.d.ts +7 -0
  106. package/dist/agent0/runtime/index.d.ts.map +1 -0
  107. package/dist/agent0/runtime/manager.d.ts +82 -0
  108. package/dist/agent0/runtime/manager.d.ts.map +1 -0
  109. package/dist/agent0/runtime/permissions.d.ts +6 -0
  110. package/dist/agent0/runtime/permissions.d.ts.map +1 -0
  111. package/dist/agent0/runtime/process.d.ts +43 -0
  112. package/dist/agent0/runtime/process.d.ts.map +1 -0
  113. package/dist/agent0/runtime/project-discovery.d.ts +5 -0
  114. package/dist/agent0/runtime/project-discovery.d.ts.map +1 -0
  115. package/dist/agent0/types.d.ts +447 -0
  116. package/dist/agent0/types.d.ts.map +1 -0
  117. package/dist/assets/manager.d.ts +0 -2
  118. package/dist/assets/manager.d.ts.map +1 -1
  119. package/dist/assets/types.d.ts +3 -1
  120. package/dist/assets/types.d.ts.map +1 -1
  121. package/dist/auth/credentials.d.ts.map +1 -1
  122. package/dist/auth/index.d.ts +30 -0
  123. package/dist/auth/index.d.ts.map +1 -1
  124. package/dist/bot-generator/dev-id-manager.d.ts.map +1 -1
  125. package/dist/bot-generator/generator.d.ts +5 -1
  126. package/dist/bot-generator/generator.d.ts.map +1 -1
  127. package/dist/bot-generator/integration-sync.d.ts.map +1 -1
  128. package/dist/bot-generator/interface-sync.d.ts.map +1 -1
  129. package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
  130. package/dist/bot-generator/table-validation.d.ts +17 -0
  131. package/dist/bot-generator/table-validation.d.ts.map +1 -0
  132. package/dist/chat-bundle.cjs +31 -0
  133. package/dist/cognitive/models.d.ts +32 -0
  134. package/dist/cognitive/models.d.ts.map +1 -0
  135. package/dist/commands/base-command.d.ts.map +1 -1
  136. package/dist/commands/bp-add-command.d.ts.map +1 -1
  137. package/dist/commands/bp-build-command.d.ts.map +1 -1
  138. package/dist/commands/bp-chat-command.d.ts.map +1 -1
  139. package/dist/commands/bp-cli.d.ts +1 -0
  140. package/dist/commands/bp-cli.d.ts.map +1 -1
  141. package/dist/commands/bp-deploy-command.d.ts.map +1 -1
  142. package/dist/commands/bp-dev-command.d.ts +5 -0
  143. package/dist/commands/bp-dev-command.d.ts.map +1 -1
  144. package/dist/commands/bp-dev-stderr.d.ts +21 -0
  145. package/dist/commands/bp-dev-stderr.d.ts.map +1 -0
  146. package/dist/commands/index.d.ts +0 -5
  147. package/dist/commands/index.d.ts.map +1 -1
  148. package/dist/config/manager.d.ts +9 -1
  149. package/dist/config/manager.d.ts.map +1 -1
  150. package/dist/constants.d.ts +1 -0
  151. package/dist/constants.d.ts.map +1 -1
  152. package/dist/dependencies/alias-utils.d.ts +13 -0
  153. package/dist/dependencies/alias-utils.d.ts.map +1 -0
  154. package/dist/dependencies/dependency-manager.d.ts +89 -0
  155. package/dist/dependencies/dependency-manager.d.ts.map +1 -0
  156. package/dist/dependencies/errors.d.ts +16 -0
  157. package/dist/dependencies/errors.d.ts.map +1 -0
  158. package/dist/dependencies/index.d.ts +17 -0
  159. package/dist/dependencies/index.d.ts.map +1 -0
  160. package/dist/dependencies/index.js +6032 -0
  161. package/dist/dependencies/index.js.map +59 -0
  162. package/dist/dependencies/json-utils.d.ts +3 -0
  163. package/dist/dependencies/json-utils.d.ts.map +1 -0
  164. package/dist/dependencies/lock-file.d.ts +15 -0
  165. package/dist/dependencies/lock-file.d.ts.map +1 -0
  166. package/dist/dependencies/migration.d.ts +8 -0
  167. package/dist/dependencies/migration.d.ts.map +1 -0
  168. package/dist/dependencies/registry/integration-registry.d.ts +17 -0
  169. package/dist/dependencies/registry/integration-registry.d.ts.map +1 -0
  170. package/dist/dependencies/registry/interface-registry.d.ts +11 -0
  171. package/dist/dependencies/registry/interface-registry.d.ts.map +1 -0
  172. package/dist/dependencies/registry/plugin-registry.d.ts +16 -0
  173. package/dist/dependencies/registry/plugin-registry.d.ts.map +1 -0
  174. package/dist/dependencies/resolvers/integration-resolver.d.ts +30 -0
  175. package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -0
  176. package/dist/dependencies/resolvers/plugin-resolver.d.ts +38 -0
  177. package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -0
  178. package/dist/dependencies/types.d.ts +253 -0
  179. package/dist/dependencies/types.d.ts.map +1 -0
  180. package/dist/deploy-manifest/index.d.ts +608 -0
  181. package/dist/deploy-manifest/index.d.ts.map +1 -0
  182. package/dist/generators/assets.d.ts +2 -2
  183. package/dist/generators/assets.d.ts.map +1 -1
  184. package/dist/generators/tests.d.ts +6 -6
  185. package/dist/generators/tests.d.ts.map +1 -1
  186. package/dist/generators/utils.d.ts.map +1 -1
  187. package/dist/index.d.ts +13 -10
  188. package/dist/index.d.ts.map +1 -1
  189. package/dist/index.js +16445 -4824
  190. package/dist/index.js.map +70 -56
  191. package/dist/integrations/config-utils.d.ts.map +1 -1
  192. package/dist/integrations/index.d.ts +0 -6
  193. package/dist/integrations/index.d.ts.map +1 -1
  194. package/dist/integrations/manager.d.ts +17 -1
  195. package/dist/integrations/manager.d.ts.map +1 -1
  196. package/dist/interfaces/index.d.ts +0 -2
  197. package/dist/interfaces/index.d.ts.map +1 -1
  198. package/dist/interfaces/manager.d.ts +3 -1
  199. package/dist/interfaces/manager.d.ts.map +1 -1
  200. package/dist/knowledge/manager.d.ts +3 -1
  201. package/dist/knowledge/manager.d.ts.map +1 -1
  202. package/dist/knowledge/types.d.ts +2 -2
  203. package/dist/knowledge/types.d.ts.map +1 -1
  204. package/dist/plugins/manager.d.ts +29 -1
  205. package/dist/plugins/manager.d.ts.map +1 -1
  206. package/dist/preflight/checker.d.ts +5 -6
  207. package/dist/preflight/checker.d.ts.map +1 -1
  208. package/dist/preflight/index.d.ts +2 -2
  209. package/dist/preflight/index.d.ts.map +1 -1
  210. package/dist/preflight/types.d.ts +30 -32
  211. package/dist/preflight/types.d.ts.map +1 -1
  212. package/dist/runner/script-runner.d.ts +2 -0
  213. package/dist/runner/script-runner.d.ts.map +1 -1
  214. package/dist/runner/supervise-child.d.ts +24 -0
  215. package/dist/runner/supervise-child.d.ts.map +1 -0
  216. package/dist/tables/table-manager.d.ts.map +1 -1
  217. package/dist/tables/types.d.ts +3 -2
  218. package/dist/tables/types.d.ts.map +1 -1
  219. package/dist/templates/README.md +13 -12
  220. package/dist/templates/blank/agent.config.ts +0 -3
  221. package/dist/templates/blank/evals/index.eval.ts +30 -0
  222. package/dist/templates/blank/src/conversations/index.ts +16 -16
  223. package/dist/templates/botpress-desk/README.md +87 -0
  224. package/dist/templates/botpress-desk/agent.config.ts +19 -0
  225. package/dist/templates/botpress-desk/evals/index.eval.ts +30 -0
  226. package/dist/templates/botpress-desk/package.json +17 -0
  227. package/dist/templates/botpress-desk/src/actions/index.ts +19 -0
  228. package/dist/templates/botpress-desk/src/conversations/index.ts +16 -0
  229. package/dist/templates/botpress-desk/src/knowledge/index.ts +20 -0
  230. package/dist/templates/botpress-desk/src/tables/index.ts +16 -0
  231. package/dist/templates/botpress-desk/src/tools/handToSupport.ts +23 -0
  232. package/dist/templates/botpress-desk/src/triggers/index.ts +17 -0
  233. package/dist/templates/botpress-desk/src/workflows/index.ts +21 -0
  234. package/dist/templates/crm-enrichment/agent.config.ts +0 -3
  235. package/dist/templates/crm-enrichment/evals/example.eval.ts +29 -0
  236. package/dist/templates/crm-enrichment/package.json +1 -0
  237. package/dist/templates/hello-world/agent.config.ts +0 -3
  238. package/dist/templates/hello-world/evals/context-retention.eval.ts +37 -0
  239. package/dist/templates/hello-world/evals/greeting.eval.ts +43 -0
  240. package/dist/templates/hello-world/package.json +1 -0
  241. package/dist/templates/knowledge-assistant/agent.config.ts +0 -3
  242. package/dist/templates/knowledge-assistant/evals/engineering-practices.eval.ts +45 -0
  243. package/dist/templates/knowledge-assistant/evals/out-of-scope.eval.ts +33 -0
  244. package/dist/templates/knowledge-assistant/evals/pto-policy.eval.ts +44 -0
  245. package/dist/templates/knowledge-assistant/package.json +1 -0
  246. package/dist/templates/slack-triage/agent.config.ts +0 -8
  247. package/dist/templates/slack-triage/evals/triage-basic.eval.ts +9 -39
  248. package/dist/templates/slack-triage/package.json +1 -0
  249. package/dist/templates/slack-triage/src/conversations/slack-dm.ts +4 -1
  250. package/dist/templates/template.config.json +16 -16
  251. package/dist/utils/require-chat.d.ts +3 -24
  252. package/dist/utils/require-chat.d.ts.map +1 -1
  253. package/dist/utils/search-ranking.d.ts +15 -0
  254. package/dist/utils/search-ranking.d.ts.map +1 -0
  255. package/dist/workspace/workspace-cache.d.ts.map +1 -1
  256. package/package.json +19 -11
  257. package/dist/commands/copilot-config-reader.d.ts +0 -12
  258. package/dist/commands/copilot-config-reader.d.ts.map +0 -1
  259. package/dist/commands/copilot-server.d.ts +0 -26
  260. package/dist/commands/copilot-server.d.ts.map +0 -1
  261. package/dist/commands/opencode-config.d.ts +0 -29
  262. package/dist/commands/opencode-config.d.ts.map +0 -1
  263. package/dist/integrations/checker.d.ts +0 -41
  264. package/dist/integrations/checker.d.ts.map +0 -1
  265. package/dist/integrations/operations.d.ts +0 -140
  266. package/dist/integrations/operations.d.ts.map +0 -1
  267. package/dist/integrations/sync-manager.d.ts +0 -19
  268. package/dist/integrations/sync-manager.d.ts.map +0 -1
  269. package/dist/interfaces/operations.d.ts +0 -48
  270. package/dist/interfaces/operations.d.ts.map +0 -1
  271. package/dist/preflight/formatter.d.ts +0 -12
  272. package/dist/preflight/formatter.d.ts.map +0 -1
@@ -0,0 +1,3215 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
47
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
48
+
49
+ // src/agent0/types.ts
50
+ var AGENT0_CONFIG_SCHEMA_VERSION = 1;
51
+ var AGENT0_SESSION_MODES = ["default", "guided"];
52
+ // src/agent0/capabilities/builtins.ts
53
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
54
+ import { basename, dirname, extname, join } from "node:path";
55
+ import { fileURLToPath } from "node:url";
56
+
57
+ // src/agent0/capabilities/prompts/default.ts
58
+ var AGENT0_DEFAULT_PROMPT = `You are agent(0) — an expert assistant embedded in the Botpress Agent Development Kit control panel.
59
+
60
+ ## Who you help
61
+ A developer building an AI agent with the ADK. They're running \`adk dev\` and have the control panel open alongside you. They can see traces, logs, integrations, workflows, and tables in the UI.
62
+
63
+ ## What you know
64
+ The ADK is a high-level framework built on Botpress. An agent project has:
65
+ - /actions — strongly-typed callable functions (Action from @botpress/runtime)
66
+ - /tools — LLM-callable interfaces with natural language descriptions (Tool from @botpress/runtime)
67
+ - /workflows — step-based, resumable long-running processes (Workflow from @botpress/runtime)
68
+ - /conversations — channel-specific interaction handlers (Conversation from @botpress/runtime)
69
+ - /tables — schema-validated data storage with semantic search (Table from @botpress/runtime)
70
+ - /triggers — event subscription system (Trigger from @botpress/runtime)
71
+ - /knowledge — RAG knowledge base documents
72
+ - agent.config.ts — agent metadata, integrations, model configuration, variables
73
+
74
+ The ADK compiles these high-level primitives down to Botpress SDK primitives. Default to ADK terms. Only drop to Botpress SDK concepts when the problem requires it (SDK-level errors, compilation issues, or when the developer explicitly asks).
75
+
76
+ Schemas use \`z\` from @botpress/sdk (a Zod fork) — never import Zod directly.
77
+
78
+ ## How you work
79
+
80
+ **Working directory.** Your shell is already set to the agent project root. Run all commands directly — never prepend \`cd\` to change into the project directory.
81
+
82
+ **CLI-first.** Use the \`adk\` CLI with \`--format json\` for everything you can — status, logs, traces, integrations, workflows, chat, evals. The only MCP tool you have is \`adk_take_screenshot\` (see below), because it requires direct browser access the CLI can't provide.
83
+
84
+ **Do not run dev subcommands.** Never run commands that start, restart, or watch a development server from this embedded assistant, including \`adk dev\`, \`bun dev\`, \`bun run dev\`, \`npm run dev\`, \`pnpm dev\`, \`yarn dev\`, \`vite dev\`, or framework-specific \`dev\` subcommands. The ADK dev server hosts you; starting or restarting it from inside agent(0) can terminate your own session. If the dev server is missing or unhealthy, ask the developer to start or restart it in their own terminal, then continue with non-dev CLI commands.
85
+
86
+ **Skills.** The \`adk\` skill is preloaded for every conversation — treat it as your authoritative reference for ADK primitives, conventions, and CLI usage. Don't try to re-load it. Other packaged skills you can load on demand for deeper topics: \`adk-debugger\` (systematic debugging, traces, common failures), \`adk-evals\` (writing and running evals), \`adk-dev-console\` (Dev Console UI context), and \`adk-docs\` (creating and maintaining ADK docs).
87
+
88
+ **Page context is auto-attached.** Every developer message begins with a hidden \`<dev_console_context>\` block describing what they're currently viewing in the dev console — page, URL, selected entity (trace ID, workflow name, action name, etc.), and any active filters. Use it to skip "what page are you on?" questions and answer in terms of what the developer can already see. The block is internal: never echo it back, never quote it verbatim. If it's missing or stale, fall back to asking.
89
+
90
+ **Look at the screen when it matters.** Use \`adk_take_screenshot\` to capture what the developer currently sees (page + sidebar + your own panel) when they reference something visual — "I don't see X", "where is this?", "what's that button?", "this looks wrong", "show you what I'm looking at". Don't guess from the URL or invent UI elements that may have moved or been renamed; look first, then answer. Skip the screenshot for non-visual questions (debugging traces, writing code, conceptual questions).
91
+
92
+ **Orient on first interaction.** If you haven't yet, run \`adk status --format json\` to learn the project's structure, primitives, and integrations before answering.
93
+
94
+ **Conceptual vs. project questions.** Conceptual questions about ADK, Botpress, or TypeScript — answer from knowledge immediately. Questions about their project (why something fails, what a file does, how to change behavior) — inspect first. If in doubt, answer what you can immediately and inspect in parallel.
95
+
96
+ **Read freely, write carefully.** Inspecting files, querying traces and logs via CLI, and reading documentation are always safe — do them without asking. But actions that modify the project (adding integrations, editing files, executing workflows, sending messages) should be confirmed first unless the developer explicitly asked you to do it.
97
+
98
+ **Debug by matching the approach to the problem:**
99
+ - Developer gives you an error message → start from the error, don't begin at "step 1"
100
+ - Build or type error → run \`adk check --format json\` for offline validation, then check the file and generated types. Traces won't help.
101
+ - Runtime behavior is wrong ("it responds wrong") → reproduce with \`adk chat --single "<relevant message>" --format json\`, then inspect traces with \`adk traces --format json\`
102
+ - Nothing happens → check \`adk logs error --format json\` for silent failures, then check if the handler is registered
103
+ - When in doubt → start with \`adk check --format json\`, then \`adk logs error --format json\`, then traces
104
+
105
+ **Integrations.** First check if the integration already exists with \`adk list\`. Only search the hub (\`adk search <query>\`) when adding a new integration. Get details with \`adk info <name>\` to understand actions, events, channels, and config requirements. Add it with \`adk add <name>\` after the developer confirms.
106
+
107
+ **Test iteratively.** To send messages, use \`adk chat --single "<message>" --format json\`. Pass the \`conversationId\` (--conversation-id "<id>") from the previous response to continue. Only test against the local dev bot.
108
+
109
+ **Workflows.** Use \`adk workflows list --format json\` to discover available workflows. Use \`adk workflows inspect <name> --format json\` to get the input schema. Use \`adk workflows run <name> '{"key": "value"}' --format json\` to execute. For workflows with no required input, pass \`'{}'\` as the payload.
110
+
111
+ **Handle failures.** If a command or tool returns an error, tell the developer what happened and suggest a concrete next step (e.g., "Dev server isn't running — start it in your terminal with \`adk dev\`, then ask me to continue"). Don't silently retry or ignore errors.
112
+
113
+ **Edit with precision.** When modifying code, change only what's needed to solve the problem. Don't refactor surrounding code, add features, or "improve" things that weren't asked about. When writing ADK primitives, match ADK conventions. For utility code, match the patterns already in the project.
114
+
115
+ ## How you communicate
116
+
117
+ **Lead with the answer.** First sentence is the diagnosis, the solution, or the action you took. Context and explanation come after, if needed.
118
+
119
+ **Show, don't describe.** Instead of "you should add error handling," show the code change. Instead of "the trace shows a failure," show the relevant span data and what it means.
120
+
121
+ **Match the developer's energy.** Short question → short answer. Detailed question → detailed response. "Why is this broken?" → diagnosis + fix. "How do workflows work?" → teach.
122
+
123
+ **Hypothesize while verifying.** If you have a likely diagnosis, say so while you check. "This usually means X — checking your trace now" is better than silence followed by an answer.
124
+
125
+ **When you fix something, explain what you changed and why.** Don't apply changes silently — the developer needs to understand the fix to trust it and learn from it.
126
+
127
+ **When you don't know, say so plainly.** "I don't have enough context — can you share the error message?" is fine.
128
+
129
+ **Skip the filler.** No "Great question!", no "Let me help you with that." Just do it.
130
+
131
+ **Never read or display the contents of .env files or credentials.** If you need to verify a configuration value, ask the developer to confirm it.`;
132
+
133
+ // src/agent0/capabilities/prompts/guided-setup.ts
134
+ var GUIDED_SETUP_PROMPT = `You are agent(0) — a friendly setup guide for the Botpress Agent Development Kit (ADK).
135
+
136
+ ## Mission
137
+
138
+ A developer chose "Guided Setup with Agent(0)" from the ADK launcher. A blank ADK project was scaffolded for them and they are in a dedicated guided setup view alongside you. Your job is to understand what they want, infer the right ADK shape, build it with sensible defaults, and validate the agent end-to-end. The whole point is that they don't have to spell everything out — they should watch you build.
139
+
140
+ This is an onboarding experience. The developer should feel guided, not interrogated. Ask about outcomes and product behavior; you decide the ADK primitives.
141
+
142
+ ## Conversation Loop
143
+
144
+ The default mode is **infer and build**, not **ask and wait**. Every question is a tax on the developer; every assumption you make and state clearly is a free invitation for them to correct you. Bias hard toward the latter.
145
+
146
+ 1. **Open with one plain-language question.** Ask what they want to build, in their own words. Do not start with a checklist.
147
+ 2. **Build an internal intent brief — silently, with defaults filled in.** For each slot below, fill in the most reasonable assumption given what the developer said. These are working assumptions to state in your plan, not unknowns to interrogate the developer about.
148
+ - goal: what useful outcome the agent provides
149
+ - trigger: what starts it, and from where
150
+ - audience: who talks to it or benefits from it
151
+ - behavior: what it reads, decides, writes, or sends
152
+ - autonomy: conversational, event-driven, scheduled, callable, or mixed
153
+ - data: tables/state, knowledge/RAG, files, seed/demo data
154
+ - integrations: Slack, Linear, CRM, calendar, internal API, etc.
155
+ - success test: one realistic message, event, or workflow run that should prove it works
156
+ - constraints: permissions, human approval, config values, unknown credentials
157
+ 3. **Default to inferring, not asking.** Use the question tool only when a wrong assumption would force real rework — the product shape would have to change, or an integration would have to be reconfigured. For everything else (data contents, names, shapes), use clearly-labeled placeholders. See "Defaults Over Questions" below.
158
+ 4. **State the plan and start building.** Once intent is clear, summarize in 2-3 sentences what you're about to build and name the assumptions you're making, then start. Do not wait for a green-light reply to start writing code. The exception is credential-consuming or irreversible actions: confirm before adding an integration that will prompt for secrets, before deploying, or before destroying existing files.
159
+ 5. **Build, validate, and hand off.** Build the agent end-to-end — primitives, config, placeholder data, the works. Run validation, fix failures, then summarize what's now working and how to try it. If the developer's reply at any point is ambiguous but clearly meant to advance ("yep", "sure", "go ahead", typos that read as affirmative), take the charitable interpretation and keep moving rather than re-asking.
160
+
161
+ ## Defaults Over Questions
162
+
163
+ Use clearly-labeled placeholders rather than ask the developer to author content. Specifically, infer and placeholder these without asking:
164
+ - routing rosters, lookup tables, assignment maps
165
+ - table rows, seed/demo data
166
+ - schema fields, return shapes, retry policies
167
+ - channel, workflow, action, and table names
168
+ - confidence thresholds, fallback values
169
+ - column names
170
+
171
+ Reserve the question tool for product forks where the default would noticeably reshape the agent or require rework:
172
+ - destination shape (post in-channel vs DM vs create ticket vs human-in-the-loop approval) when not implied
173
+ - conversational vs event-driven trigger when both are plausible from the description
174
+ - which integration to use when several would fit (Slack vs Teams, Linear vs Jira)
175
+ - whether the agent should write back or stay read-only when both are plausible
176
+
177
+ Avoid asking the developer to choose ADK internals at any point: schemas, return types, table columns, workflow names, retry policies, or which primitive to use. Infer those and state your assumption in the plan.
178
+
179
+ ## ADK Architecture Map
180
+
181
+ Map intent onto the smallest useful set of ADK building blocks:
182
+ - \`agent.config.ts\` — agent metadata, integrations, model/config/state schemas
183
+ - \`src/conversations/\` — channel-specific message handlers for chat-style interaction
184
+ - \`src/triggers/\` — event subscriptions like "when a Slack message/event arrives"
185
+ - \`src/workflows/\` — multi-step, resumable, stateful, scheduled, or human-in-the-loop processes
186
+ - \`src/actions/\` — strongly typed reusable business logic, callable by workflows/conversations/other code
187
+ - \`src/tools/\` — LLM-callable capabilities selected during autonomous reasoning
188
+ - \`src/tables/\` — durable schema-validated records, routing rules, memory, queues, assignments
189
+ - \`src/knowledge/\` — RAG over documents, websites, directories, or table-backed sources
190
+ - \`evals/\` — behavior checks for important user journeys
191
+
192
+ Default to the simplest design that works. A Slack triage agent may need a Slack conversation or trigger, one workflow, one classification action, and a routing table. It does not need every primitive.
193
+
194
+ ## Prefer AI Over Deterministic Code
195
+
196
+ The ADK is built for LLM-native patterns. Default to AI for anything resembling reasoning, classification, summarization, or generation. Reserve deterministic code for mechanical work (data transforms, API calls, plain control flow).
197
+
198
+ - For conversations and workflows, use **\`execute()\`** to let the LLM drive — provide instructions, hook up tools and knowledge bases, let the model decide. This is the default for chat-style interaction and autonomous workflows. See \`conversations.md\` and \`workflows.md\`.
199
+ - For one-shot LLM operations inside actions, workflows, or scripts, use **\`adk.zai.*\`** (imported from \`@botpress/runtime\`):
200
+ - \`zai.extract(input, schema)\` — pull structured data out of free text
201
+ - \`zai.check(input, condition)\` — yes/no classification with reasoning
202
+ - \`zai.summarize(input, options)\` — distill long content
203
+ - \`zai.label(input, labels)\` — multi-class classification against a fixed set
204
+ - \`zai.filter(items, condition)\` — keep items matching a natural-language predicate
205
+ - See \`zai-agent-reference.md\` and \`zai-complete-guide.md\`.
206
+ - Use hand-rolled logic only when the developer asks for deterministic behavior, the task is mechanical (string formatting, arithmetic, shape transforms), or the operation is genuinely trivial.
207
+
208
+ When building a triage, routing, classification, extraction, or Q&A agent, the right primitive is almost always \`execute()\` or zai — not a hand-rolled regex or rule table.
209
+
210
+ ## ADK Knowledge Sources
211
+
212
+ The \`adk\` skill is preloaded as \`.agents/skills/adk/SKILL.md\`. Treat it as the index, not the whole manual. Before authoring a primitive, read the relevant reference file under \`.agents/skills/adk/references/\`:
213
+ - \`agent-config.md\` before changing \`agent.config.ts\`
214
+ - \`conversations.md\` before writing or modifying conversations
215
+ - \`triggers.md\` before event-driven behavior
216
+ - \`workflows.md\` before multi-step or resumable flows
217
+ - \`actions.md\` before reusable typed logic
218
+ - \`tools.md\` before autonomous LLM tools
219
+ - \`zai-agent-reference.md\` and \`zai-complete-guide.md\` before using \`adk.zai.*\` (extract / check / summarize / label / filter)
220
+ - \`tables.md\` before durable data
221
+ - \`knowledge-bases.md\` before RAG
222
+ - \`integration-actions.md\` and \`integrations.md\` before using integration actions
223
+ - \`patterns-mistakes.md\` when writing code, especially for imports, workflow steps, and table schemas
224
+ - \`cli.md\` when choosing an ADK command
225
+
226
+ If a signature is still unclear, inspect existing project files, generated types in \`.adk/*.d.ts\`, or \`node_modules/@botpress/runtime\`. Do not guess primitive APIs.
227
+
228
+ Use ADK imports from \`@botpress/runtime\` for generated agent code. Use Botpress's \`z\` export from the ADK runtime import when following project/template style; never import from \`zod\` directly.
229
+
230
+ ## Command Playbooks
231
+
232
+ Generated projects include OpenCode command playbooks in \`.opencode/commands/\`. Use them as workflow guidance:
233
+ - \`adk-build.md\` for decomposing a feature into primitives and building it
234
+ - \`adk-validate.md\` for static validation of a primitive or feature
235
+ - \`adk-test.md\` for invoking the built behavior
236
+ - \`adk-eval.md\` for adding regression coverage
237
+
238
+ You do not need to tell the developer to run these slash commands during guided setup. Follow the playbooks yourself when they apply.
239
+
240
+ ## Visual Context
241
+
242
+ The guided setup view provides page context automatically. Screenshot capture is not available in guided setup, so rely on that context, project files, and CLI/status output when orienting yourself.
243
+
244
+ ## Working Directory
245
+
246
+ Your shell is already set to the agent project root. Run all commands directly — never prepend \`cd\` to change into the project directory.
247
+
248
+ ## Project Inspection
249
+
250
+ Before planning or writing, inspect enough local context:
251
+ - Run \`adk status --format json\` if available to learn project state.
252
+ - Read \`agent.config.ts\`.
253
+ - Run \`adk list --format json\` before deciding integrations.
254
+ - Glob \`src/\` and skim existing primitives if the project is not empty.
255
+ - For conversation changes, read every \`src/conversations/*.ts\` file and check channel overlap. Extend an existing overlapping handler; only create a new conversation file when channels are disjoint or the developer explicitly asks.
256
+
257
+ Never read or display \`.env\` files or credentials. If a secret/config value is needed, ask the developer to confirm or configure it.
258
+
259
+ ## Building Rules
260
+
261
+ - Use \`adk info <integration> --format json\` before adding an integration when possible. Pin the version when you know it.
262
+ - Write files in dependency order: tables/knowledge first, actions/tools next, workflows next, conversations/triggers last.
263
+ - Add seed/demo data only when useful and clearly placeholder.
264
+ - Use static imports. Avoid dynamic imports except for documented ADK-safe cases.
265
+ - Keep names clear and project-local. Do not invent unrelated abstractions.
266
+ - Add comments only where they teach a real ADK concept or clarify non-obvious behavior.
267
+
268
+ ## Validation Rules
269
+
270
+ Validate as you go:
271
+ - Run \`adk check --format json\` after meaningful additions.
272
+ - Use \`adk build\` when generated types or production bundle behavior need confirmation.
273
+ - For conversational agents, use \`adk chat --single "<message>" --format json\` when the chat/webchat integration is present and the dev server can handle it.
274
+ - For workflow-first agents, use \`adk workflows inspect <name> --format json\` and \`adk workflows run <name> '<payload>' --format json\` when available.
275
+ - If validation fails, fix it before moving on. If a command needs the dev server and it is unavailable, ask the developer to start/restart \`adk dev\`; do not start or restart dev/watch servers from inside agent(0).
276
+
277
+ Do not run commands that start, restart, or watch a development server from inside guided setup, including \`adk dev\`, \`bun dev\`, \`bun run dev\`, \`npm run dev\`, \`pnpm dev\`, \`yarn dev\`, \`vite dev\`, or framework-specific dev commands.
278
+
279
+ ## Communication Style
280
+
281
+ Warm, direct, and efficient. No filler. Bias to action over questions; when you must ask, one short batch at a time.`;
282
+
283
+ // src/agent0/capabilities/builtins.ts
284
+ var AGENT0_DEFAULT_AGENT = "default";
285
+ var AGENT0_PRIMARY_AGENT_STEPS = 64;
286
+ var AGENT0_SCREENSHOT_MCP_TOOL_PERMISSION = "adk_adk_take_screenshot";
287
+ var AGENT0_SCREENSHOT_RAW_TOOL_PERMISSION = "adk_take_screenshot";
288
+ function buildAgent0BuiltInCapabilities(options) {
289
+ const skillsRoot = resolveAgent0BuiltInSkillsRoot();
290
+ return {
291
+ mcp: {
292
+ adk: {
293
+ type: "remote",
294
+ url: `http://localhost:${options.adkDevConsolePort}/mcp?agent=${encodeURIComponent(options.agentPath)}`,
295
+ oauth: false
296
+ }
297
+ },
298
+ skills: {
299
+ paths: resolveAgent0BuiltInSkillPaths(skillsRoot),
300
+ urls: []
301
+ },
302
+ instructions: resolveAgent0BuiltInInstructionFiles(skillsRoot),
303
+ command: loadAgent0BuiltInCommandConfig(),
304
+ agent: {
305
+ default: {
306
+ description: "Agent(0) - helps build and debug Botpress ADK agents",
307
+ prompt: AGENT0_DEFAULT_PROMPT,
308
+ mode: "primary",
309
+ steps: AGENT0_PRIMARY_AGENT_STEPS
310
+ },
311
+ guided: {
312
+ description: "ADK guided setup - interviews the developer and scaffolds a new agent",
313
+ prompt: GUIDED_SETUP_PROMPT,
314
+ mode: "primary",
315
+ steps: AGENT0_PRIMARY_AGENT_STEPS,
316
+ permission: {
317
+ [AGENT0_SCREENSHOT_MCP_TOOL_PERMISSION]: "deny",
318
+ [AGENT0_SCREENSHOT_RAW_TOOL_PERMISSION]: "deny"
319
+ }
320
+ },
321
+ build: {
322
+ mode: "primary",
323
+ steps: AGENT0_PRIMARY_AGENT_STEPS
324
+ },
325
+ plan: {
326
+ mode: "primary",
327
+ steps: AGENT0_PRIMARY_AGENT_STEPS
328
+ }
329
+ },
330
+ defaultAgent: AGENT0_DEFAULT_AGENT
331
+ };
332
+ }
333
+ function resolveAgent0BuiltInSkillsRoot() {
334
+ return firstExistingDirectory(resolveAgent0BuiltInSkillsRootCandidates(moduleDir()));
335
+ }
336
+ function resolveAgent0BuiltInCommandsRoot() {
337
+ return firstExistingDirectory(resolveAgent0BuiltInCommandsRootCandidates(moduleDir()));
338
+ }
339
+ function resolveAgent0BuiltInSkillPaths(skillsRoot = resolveAgent0BuiltInSkillsRoot()) {
340
+ if (!skillsRoot)
341
+ return [];
342
+ return readdirSync(skillsRoot).toSorted().flatMap((entry) => {
343
+ const dir = join(skillsRoot, entry);
344
+ if (!statSync(dir).isDirectory())
345
+ return [];
346
+ if (!existsSync(join(dir, "SKILL.md")))
347
+ return [];
348
+ return [dir];
349
+ });
350
+ }
351
+ function resolveAgent0BuiltInInstructionFiles(skillsRoot = resolveAgent0BuiltInSkillsRoot()) {
352
+ const files = skillsRoot ? [join(skillsRoot, "adk", "SKILL.md")] : [];
353
+ return files.filter((file) => existsSync(file) && statSync(file).isFile());
354
+ }
355
+ function loadAgent0BuiltInCommandConfig(commandsRoot = resolveAgent0BuiltInCommandsRoot()) {
356
+ if (!commandsRoot)
357
+ return {};
358
+ const commands = {};
359
+ for (const file of readdirSync(commandsRoot).toSorted()) {
360
+ if (extname(file) !== ".md")
361
+ continue;
362
+ const filepath = join(commandsRoot, file);
363
+ if (!statSync(filepath).isFile())
364
+ continue;
365
+ const parsed = parseFrontmatterMarkdown(readFileSync(filepath, "utf8"));
366
+ const name = parsed.frontmatter.name || basename(file, ".md");
367
+ if (!name)
368
+ continue;
369
+ commands[name] = {
370
+ template: parsed.body.trim(),
371
+ ...parsed.frontmatter.description ? { description: parsed.frontmatter.description } : {},
372
+ ...parsed.frontmatter.agent ? { agent: parsed.frontmatter.agent } : {},
373
+ ...parsed.frontmatter.model ? { model: parsed.frontmatter.model } : {},
374
+ ...parsed.frontmatter.subtask === "true" ? { subtask: true } : parsed.frontmatter.subtask === "false" ? { subtask: false } : {}
375
+ };
376
+ }
377
+ return commands;
378
+ }
379
+ function parseFrontmatterMarkdown(text) {
380
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
381
+ if (!match)
382
+ return { frontmatter: {}, body: text };
383
+ const frontmatter = {};
384
+ for (const line of match[1].split(/\r?\n/)) {
385
+ const index = line.indexOf(":");
386
+ if (index === -1)
387
+ continue;
388
+ const key = line.slice(0, index).trim();
389
+ const value = line.slice(index + 1).trim();
390
+ if (!key || !value)
391
+ continue;
392
+ frontmatter[key] = unquote(value);
393
+ }
394
+ return { frontmatter, body: match[2] ?? "" };
395
+ }
396
+ function unquote(value) {
397
+ const quote = value[0];
398
+ return quote && quote === value[value.length - 1] && (quote === '"' || quote === "'") ? value.slice(1, -1) : value;
399
+ }
400
+ function firstExistingDirectory(paths) {
401
+ return paths.find((dir) => existsSync(dir) && statSync(dir).isDirectory());
402
+ }
403
+ function resolveAgent0BuiltInSkillsRootCandidates(baseDir) {
404
+ return [join(baseDir, "capabilities", "skills"), join(baseDir, "agent0-assets", "skills"), join(baseDir, "skills")];
405
+ }
406
+ function resolveAgent0BuiltInCommandsRootCandidates(baseDir) {
407
+ return [
408
+ join(baseDir, "capabilities", "commands"),
409
+ join(baseDir, "agent0-assets", "playbooks"),
410
+ join(baseDir, "commands")
411
+ ];
412
+ }
413
+ function moduleDir() {
414
+ return dirname(fileURLToPath(import.meta.url));
415
+ }
416
+ // src/agent0/config/paths.ts
417
+ import { createHash } from "node:crypto";
418
+ import { existsSync as existsSync2, realpathSync } from "node:fs";
419
+ import { chmod, mkdir } from "node:fs/promises";
420
+ import { homedir } from "node:os";
421
+ import { join as join2, resolve } from "node:path";
422
+ var PROJECT_HASH_LENGTH = 32;
423
+ var OWNER_ONLY_DIR_MODE = 448;
424
+ function getAgent0HomeDir(options = {}) {
425
+ return join2(options.homeDir ?? process.env.HOME ?? homedir(), ".adk", "agent0");
426
+ }
427
+ function getAgent0ConfigPath(options = {}) {
428
+ return join2(getAgent0HomeDir(options), "config.json");
429
+ }
430
+ async function ensureAgent0Directory(dirPath) {
431
+ await mkdir(dirPath, { recursive: true, mode: OWNER_ONLY_DIR_MODE });
432
+ await chmod(dirPath, OWNER_ONLY_DIR_MODE);
433
+ }
434
+ function canonicalizeAgent0ProjectPath(projectPath) {
435
+ const resolved = resolve(projectPath);
436
+ return existsSync2(resolved) ? realpathSync(resolved) : resolved;
437
+ }
438
+ function getAgent0ProjectHash(projectPath) {
439
+ return createHash("sha256").update(canonicalizeAgent0ProjectPath(projectPath)).digest("hex").slice(0, PROJECT_HASH_LENGTH);
440
+ }
441
+ function getAgent0ProjectPaths(projectPath, options = {}) {
442
+ const canonicalProjectPath = canonicalizeAgent0ProjectPath(projectPath);
443
+ const projectHash = getAgent0ProjectHash(canonicalProjectPath);
444
+ const rootDir = join2(getAgent0HomeDir(options), "projects", projectHash);
445
+ const xdgConfigHome = join2(rootDir, "xdg", "config");
446
+ const xdgDataHome = join2(rootDir, "xdg", "data");
447
+ const xdgCacheHome = join2(rootDir, "xdg", "cache");
448
+ const xdgStateHome = join2(rootDir, "xdg", "state");
449
+ const fakeHomeDir = join2(rootDir, "home");
450
+ return {
451
+ projectHash,
452
+ canonicalProjectPath,
453
+ rootDir,
454
+ xdgConfigHome,
455
+ xdgDataHome,
456
+ xdgCacheHome,
457
+ xdgStateHome,
458
+ fakeHomeDir,
459
+ engineBinDir: join2(rootDir, "bin"),
460
+ engineConfigDir: join2(xdgConfigHome, "opencode"),
461
+ engineDataDir: join2(xdgDataHome, "opencode"),
462
+ sessionsDir: join2(xdgStateHome, "sessions")
463
+ };
464
+ }
465
+ async function ensureAgent0ProjectDirs(projectPath, options = {}) {
466
+ const paths = getAgent0ProjectPaths(projectPath, options);
467
+ await Promise.all([
468
+ ensureAgent0Directory(paths.rootDir),
469
+ ensureAgent0Directory(join2(paths.rootDir, "xdg")),
470
+ ensureAgent0Directory(paths.xdgConfigHome),
471
+ ensureAgent0Directory(paths.xdgDataHome),
472
+ ensureAgent0Directory(paths.xdgCacheHome),
473
+ ensureAgent0Directory(paths.xdgStateHome),
474
+ ensureAgent0Directory(paths.fakeHomeDir),
475
+ ensureAgent0Directory(paths.engineBinDir),
476
+ ensureAgent0Directory(paths.engineConfigDir),
477
+ ensureAgent0Directory(paths.engineDataDir),
478
+ ensureAgent0Directory(paths.sessionsDir)
479
+ ]);
480
+ return paths;
481
+ }
482
+ // src/agent0/config/schema.ts
483
+ import { z } from "@botpress/sdk";
484
+ var agent0ProviderAuthSchema = z.object({
485
+ type: z.literal("api_key"),
486
+ apiKey: z.string().trim().min(1),
487
+ baseURL: z.string().trim().url().optional()
488
+ }).strict();
489
+ var agent0ProviderConnectionSchema = z.object({
490
+ providerId: z.string().min(1),
491
+ enabled: z.boolean(),
492
+ auth: agent0ProviderAuthSchema.optional(),
493
+ createdAt: z.string().datetime(),
494
+ updatedAt: z.string().datetime()
495
+ }).strict();
496
+ var agent0ConfigPreferencesSchema = z.object({
497
+ defaultModel: z.string().min(1).optional(),
498
+ showThinking: z.boolean(),
499
+ showUsage: z.boolean()
500
+ }).strict();
501
+ var agent0ConfigSchema = z.object({
502
+ schemaVersion: z.literal(AGENT0_CONFIG_SCHEMA_VERSION),
503
+ enabled: z.boolean(),
504
+ providers: z.record(agent0ProviderConnectionSchema),
505
+ preferences: agent0ConfigPreferencesSchema,
506
+ createdAt: z.string().datetime(),
507
+ updatedAt: z.string().datetime()
508
+ }).strict();
509
+ var DEFAULT_AGENT0_PREFERENCES = {
510
+ showThinking: true,
511
+ showUsage: false
512
+ };
513
+ function createDefaultAgent0Config(now = new Date) {
514
+ const timestamp = now.toISOString();
515
+ return {
516
+ schemaVersion: AGENT0_CONFIG_SCHEMA_VERSION,
517
+ enabled: true,
518
+ providers: {},
519
+ preferences: { ...DEFAULT_AGENT0_PREFERENCES },
520
+ createdAt: timestamp,
521
+ updatedAt: timestamp
522
+ };
523
+ }
524
+ function parseAgent0Config(value) {
525
+ const config = agent0ConfigSchema.parse(value);
526
+ for (const [key, connection] of Object.entries(config.providers)) {
527
+ if (key !== connection.providerId) {
528
+ throw new Error(`Provider connection key "${key}" does not match providerId "${connection.providerId}"`);
529
+ }
530
+ }
531
+ return config;
532
+ }
533
+ // src/agent0/config/secrets.ts
534
+ function redactProviderAuth(auth) {
535
+ if (!auth)
536
+ return;
537
+ return {
538
+ type: auth.type,
539
+ configured: Boolean(auth.apiKey),
540
+ ...auth.baseURL ? { baseURL: auth.baseURL } : {}
541
+ };
542
+ }
543
+ function redactProviderConnection(connection) {
544
+ return {
545
+ ...connection,
546
+ auth: redactProviderAuth(connection.auth)
547
+ };
548
+ }
549
+ function redactAgent0Config(config) {
550
+ return {
551
+ ...config,
552
+ providers: Object.fromEntries(Object.entries(config.providers).map(([providerId, connection]) => [
553
+ providerId,
554
+ redactProviderConnection(connection)
555
+ ]))
556
+ };
557
+ }
558
+ function hasAgent0ProviderAuth(connection) {
559
+ return Boolean(connection?.auth?.apiKey);
560
+ }
561
+ // src/agent0/config/store.ts
562
+ import { readFile, rename, writeFile, chmod as chmod2 } from "node:fs/promises";
563
+ import { dirname as dirname2 } from "node:path";
564
+ class Agent0ConfigError extends Error {
565
+ cause;
566
+ constructor(message, cause) {
567
+ super(message);
568
+ this.cause = cause;
569
+ this.name = "Agent0ConfigError";
570
+ }
571
+ }
572
+
573
+ class Agent0ConfigStore {
574
+ configPath;
575
+ now;
576
+ writeLock = Promise.resolve();
577
+ constructor(options = {}) {
578
+ this.configPath = options.configPath ?? getAgent0ConfigPath(options);
579
+ this.now = options.now ?? (() => new Date);
580
+ }
581
+ async read() {
582
+ let content;
583
+ try {
584
+ content = await readFile(this.configPath, "utf-8");
585
+ } catch (error) {
586
+ if (isFileNotFoundError(error))
587
+ return createDefaultAgent0Config(this.now());
588
+ throw new Agent0ConfigError(`Failed to read Agent(0) config at ${this.configPath}`, error);
589
+ }
590
+ try {
591
+ return parseAgent0Config(JSON.parse(content));
592
+ } catch (error) {
593
+ throw new Agent0ConfigError(`Invalid Agent(0) config at ${this.configPath}`, error);
594
+ }
595
+ }
596
+ async write(config) {
597
+ const parsed = parseAgent0Config(config);
598
+ await writeOwnerOnlyJson(this.configPath, parsed);
599
+ }
600
+ async reset() {
601
+ const config = createDefaultAgent0Config(this.now());
602
+ await this.write(config);
603
+ return config;
604
+ }
605
+ async update(updater) {
606
+ const result = this.writeLock.then(async () => {
607
+ const current = await this.read();
608
+ const draft = structuredClone(current);
609
+ const updated = updater(draft) ?? draft;
610
+ const next = parseAgent0Config({
611
+ ...updated,
612
+ updatedAt: this.now().toISOString()
613
+ });
614
+ await this.write(next);
615
+ return next;
616
+ });
617
+ this.writeLock = result.then(() => {}, () => {});
618
+ return result;
619
+ }
620
+ }
621
+ async function writeOwnerOnlyJson(filePath, value) {
622
+ await ensureAgent0Directory(dirname2(filePath));
623
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
624
+ await writeFile(tmpPath, JSON.stringify(value, null, 2) + `
625
+ `, { encoding: "utf-8", mode: 384 });
626
+ await chmod2(tmpPath, 384);
627
+ await rename(tmpPath, filePath);
628
+ await chmod2(filePath, 384);
629
+ }
630
+ function isFileNotFoundError(error) {
631
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
632
+ }
633
+ // src/agent0/providers/catalog.ts
634
+ var apiKey = (apiKeyLabel = "API key", baseURL) => ({
635
+ type: "api_key",
636
+ apiKeyLabel,
637
+ ...baseURL ? {
638
+ baseURL: {
639
+ label: baseURL.label ?? "Base URL",
640
+ placeholder: baseURL.placeholder,
641
+ defaultValue: baseURL.defaultValue,
642
+ required: baseURL.required ?? false
643
+ }
644
+ } : {}
645
+ });
646
+ var planned = (reason) => ({ type: "planned", reason });
647
+ var modelsDev = (providerId) => ({
648
+ type: "models.dev",
649
+ ...providerId === undefined ? {} : { providerId }
650
+ });
651
+ var botpressCognitive = () => ({
652
+ type: "cognitive"
653
+ });
654
+ var AGENT0_PROVIDER_CATALOG = [
655
+ {
656
+ id: "cognitive",
657
+ name: "Botpress Cognitive",
658
+ description: "First-party Botpress model access through the active ADK dev bot.",
659
+ firstParty: true,
660
+ status: "available",
661
+ enabledByDefault: true,
662
+ auth: { type: "none" },
663
+ modelSource: botpressCognitive()
664
+ },
665
+ {
666
+ id: "openai",
667
+ name: "OpenAI",
668
+ description: "Direct OpenAI API access.",
669
+ firstParty: false,
670
+ status: "available",
671
+ enabledByDefault: false,
672
+ auth: apiKey("OpenAI API key"),
673
+ modelSource: modelsDev()
674
+ },
675
+ {
676
+ id: "anthropic",
677
+ name: "Anthropic",
678
+ description: "Direct Anthropic API access.",
679
+ firstParty: false,
680
+ status: "available",
681
+ enabledByDefault: false,
682
+ auth: apiKey("Anthropic API key"),
683
+ modelSource: modelsDev()
684
+ },
685
+ {
686
+ id: "google",
687
+ name: "Google Gemini",
688
+ description: "Google Gemini API access.",
689
+ firstParty: false,
690
+ status: "available",
691
+ enabledByDefault: false,
692
+ auth: apiKey("Gemini API key"),
693
+ modelSource: modelsDev()
694
+ },
695
+ {
696
+ id: "github-copilot",
697
+ name: "GitHub Copilot",
698
+ description: "GitHub Copilot model access.",
699
+ firstParty: false,
700
+ status: "planned",
701
+ enabledByDefault: false,
702
+ auth: planned("GitHub Copilot requires an OAuth/device-code flow, which is outside the first simple API-key pass."),
703
+ modelSource: modelsDev()
704
+ },
705
+ {
706
+ id: "openrouter",
707
+ name: "OpenRouter",
708
+ description: "Aggregator access to many hosted models.",
709
+ firstParty: false,
710
+ status: "available",
711
+ enabledByDefault: false,
712
+ auth: apiKey("OpenRouter API key"),
713
+ modelSource: modelsDev()
714
+ },
715
+ {
716
+ id: "moonshotai",
717
+ name: "Moonshot AI / Kimi",
718
+ description: "Direct Moonshot AI access to Kimi models.",
719
+ firstParty: false,
720
+ status: "available",
721
+ enabledByDefault: false,
722
+ auth: apiKey("Moonshot API key"),
723
+ modelSource: modelsDev()
724
+ },
725
+ {
726
+ id: "mistral",
727
+ name: "Mistral",
728
+ description: "Direct Mistral API access.",
729
+ firstParty: false,
730
+ status: "available",
731
+ enabledByDefault: false,
732
+ auth: apiKey("Mistral API key"),
733
+ modelSource: modelsDev()
734
+ },
735
+ {
736
+ id: "groq",
737
+ name: "Groq",
738
+ description: "Groq-hosted low-latency model access.",
739
+ firstParty: false,
740
+ status: "available",
741
+ enabledByDefault: false,
742
+ auth: apiKey("Groq API key"),
743
+ modelSource: modelsDev()
744
+ },
745
+ {
746
+ id: "xai",
747
+ name: "xAI",
748
+ description: "Direct xAI API access.",
749
+ firstParty: false,
750
+ status: "available",
751
+ enabledByDefault: false,
752
+ auth: apiKey("xAI API key"),
753
+ modelSource: modelsDev()
754
+ },
755
+ {
756
+ id: "deepseek",
757
+ name: "DeepSeek",
758
+ description: "Direct DeepSeek API access.",
759
+ firstParty: false,
760
+ status: "available",
761
+ enabledByDefault: false,
762
+ auth: apiKey("DeepSeek API key"),
763
+ modelSource: modelsDev()
764
+ },
765
+ {
766
+ id: "cerebras",
767
+ name: "Cerebras",
768
+ description: "Cerebras-hosted model access.",
769
+ firstParty: false,
770
+ status: "available",
771
+ enabledByDefault: false,
772
+ auth: apiKey("Cerebras API key"),
773
+ modelSource: modelsDev()
774
+ },
775
+ {
776
+ id: "fireworks-ai",
777
+ name: "Fireworks",
778
+ description: "Fireworks-hosted model access.",
779
+ firstParty: false,
780
+ status: "available",
781
+ enabledByDefault: false,
782
+ auth: apiKey("Fireworks API key"),
783
+ modelSource: modelsDev()
784
+ },
785
+ {
786
+ id: "togetherai",
787
+ name: "Together AI",
788
+ description: "Together AI hosted model access.",
789
+ firstParty: false,
790
+ status: "available",
791
+ enabledByDefault: false,
792
+ auth: apiKey("Together API key"),
793
+ modelSource: modelsDev()
794
+ },
795
+ {
796
+ id: "cohere",
797
+ name: "Cohere",
798
+ description: "Direct Cohere API access.",
799
+ firstParty: false,
800
+ status: "available",
801
+ enabledByDefault: false,
802
+ auth: apiKey("Cohere API key"),
803
+ modelSource: modelsDev()
804
+ },
805
+ {
806
+ id: "perplexity",
807
+ name: "Perplexity",
808
+ description: "Perplexity API access for answer and research-oriented models.",
809
+ firstParty: false,
810
+ status: "available",
811
+ enabledByDefault: false,
812
+ auth: apiKey("Perplexity API key"),
813
+ modelSource: modelsDev()
814
+ },
815
+ {
816
+ id: "azure",
817
+ name: "Azure OpenAI",
818
+ description: "Azure-hosted OpenAI-compatible deployments.",
819
+ firstParty: false,
820
+ status: "available",
821
+ enabledByDefault: false,
822
+ auth: apiKey("Azure OpenAI API key", {
823
+ label: "Azure OpenAI endpoint",
824
+ placeholder: "https://<resource>.openai.azure.com/openai/deployments/<deployment>",
825
+ required: true
826
+ }),
827
+ modelSource: modelsDev()
828
+ },
829
+ {
830
+ id: "amazon-bedrock",
831
+ name: "AWS Bedrock",
832
+ description: "AWS Bedrock model access.",
833
+ firstParty: false,
834
+ status: "planned",
835
+ enabledByDefault: false,
836
+ auth: planned("AWS Bedrock needs AWS credential and region configuration, not a single API key."),
837
+ modelSource: modelsDev()
838
+ },
839
+ {
840
+ id: "google-vertex",
841
+ name: "Vertex AI",
842
+ description: "Google Cloud Vertex AI model access.",
843
+ firstParty: false,
844
+ status: "planned",
845
+ enabledByDefault: false,
846
+ auth: planned("Vertex AI needs Google Cloud project, location, and service account credentials."),
847
+ modelSource: modelsDev()
848
+ },
849
+ {
850
+ id: "alibaba",
851
+ name: "Alibaba / Qwen / DashScope",
852
+ description: "Alibaba DashScope access to Qwen models.",
853
+ firstParty: false,
854
+ status: "available",
855
+ enabledByDefault: false,
856
+ auth: apiKey("DashScope API key"),
857
+ modelSource: modelsDev()
858
+ }
859
+ ];
860
+ var CATALOG_BY_ID = new Map(AGENT0_PROVIDER_CATALOG.map((entry) => [entry.id, entry]));
861
+ function listAgent0ProviderCatalog() {
862
+ return [...AGENT0_PROVIDER_CATALOG];
863
+ }
864
+ function getAgent0ProviderCatalogEntry(providerId) {
865
+ return CATALOG_BY_ID.get(providerId);
866
+ }
867
+ function requireAgent0ProviderCatalogEntry(providerId) {
868
+ const entry = getAgent0ProviderCatalogEntry(providerId);
869
+ if (!entry)
870
+ throw new Error(`Unknown Agent(0) provider: ${providerId}`);
871
+ return entry;
872
+ }
873
+ function toAgent0AvailableModel(entry, model) {
874
+ if (model.providerId !== entry.id) {
875
+ throw new Error(`Agent(0) model ${model.modelId} belongs to ${model.providerId}, not ${entry.id}`);
876
+ }
877
+ return {
878
+ id: `${entry.id}/${model.modelId}`,
879
+ providerId: entry.id,
880
+ providerName: entry.name,
881
+ modelId: model.modelId,
882
+ name: model.name,
883
+ contextWindow: model.contextWindow,
884
+ outputLimit: model.outputLimit,
885
+ inputCostPer1MTokens: model.inputCostPer1MTokens,
886
+ outputCostPer1MTokens: model.outputCostPer1MTokens,
887
+ tags: model.tags ? [...model.tags] : undefined
888
+ };
889
+ }
890
+ // src/cognitive/models.ts
891
+ import { z as z2 } from "@botpress/sdk";
892
+ var DEFAULT_BOTPRESS_API_URL = "https://api.botpress.cloud";
893
+ var DEFAULT_FETCH_TIMEOUT_MS = 5000;
894
+ var cognitiveModelsResponseSchema = z2.object({
895
+ models: z2.array(z2.object({
896
+ id: z2.string(),
897
+ name: z2.string(),
898
+ tags: z2.array(z2.string()).optional(),
899
+ input: z2.object({
900
+ maxTokens: z2.number(),
901
+ costPer1MTokens: z2.number()
902
+ }).optional(),
903
+ output: z2.object({
904
+ maxTokens: z2.number(),
905
+ costPer1MTokens: z2.number()
906
+ }).optional()
907
+ }))
908
+ });
909
+ async function fetchBotpressCognitiveModels(options) {
910
+ try {
911
+ const apiUrl = options.apiUrl || DEFAULT_BOTPRESS_API_URL;
912
+ const fetchImpl = options.fetch ?? fetch;
913
+ const res = await fetchImpl(`${apiUrl}/v2/cognitive/models`, {
914
+ headers: {
915
+ Authorization: `Bearer ${options.token}`,
916
+ "X-Bot-Id": options.botId
917
+ },
918
+ ...options.timeoutMs === 0 ? {} : { signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS) }
919
+ });
920
+ if (!res.ok)
921
+ return;
922
+ const { models } = cognitiveModelsResponseSchema.parse(await res.json());
923
+ const filtered = models.filter((model) => !model.tags?.includes("speech-to-text") && !model.tags?.includes("deprecated") && !model.tags?.includes("discontinued"));
924
+ const nameCounts = new Map;
925
+ for (const model of filtered)
926
+ nameCounts.set(model.name, (nameCounts.get(model.name) ?? 0) + 1);
927
+ return filtered.map((model) => {
928
+ if (nameCounts.get(model.name) > 1) {
929
+ const provider = model.id.split(":")[0] ?? "";
930
+ return { ...model, name: `${model.name} (${provider})` };
931
+ }
932
+ return model;
933
+ });
934
+ } catch {
935
+ return;
936
+ }
937
+ }
938
+ function toCognitiveModelKey(id) {
939
+ return id.replace(":", "--");
940
+ }
941
+
942
+ // src/agent0/providers/source.ts
943
+ var DEFAULT_MODELS_DEV_API_URL = "https://models.dev/api.json";
944
+ var DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
945
+ var DEFAULT_MODELS_DEV_FETCH_TIMEOUT_MS = 1e4;
946
+
947
+ class Agent0ProviderCatalogSourceError extends Error {
948
+ cause;
949
+ constructor(message, cause) {
950
+ super(message);
951
+ this.cause = cause;
952
+ this.name = "Agent0ProviderCatalogSourceError";
953
+ }
954
+ }
955
+
956
+ class Agent0CompositeProviderCatalogSource {
957
+ id = "agent0-composite";
958
+ sources;
959
+ constructor(options) {
960
+ this.sources = options.sources;
961
+ }
962
+ async listProviders() {
963
+ return listAgent0ProviderCatalog();
964
+ }
965
+ async listModels(options = {}) {
966
+ return (await this.listModelsWithStatus(options)).models;
967
+ }
968
+ async listModelsWithStatus(options = {}) {
969
+ const results = await Promise.all(this.sources.map((source) => listSourceModelsWithStatus(source, options)));
970
+ return {
971
+ models: results.flatMap((result) => result.models),
972
+ warnings: results.flatMap((result) => result.warnings)
973
+ };
974
+ }
975
+ async refresh() {
976
+ await this.listModels({ refresh: true });
977
+ }
978
+ }
979
+
980
+ class Agent0CognitiveCatalogSource {
981
+ id = "cognitive";
982
+ auth;
983
+ resolveAuth;
984
+ fetchImpl;
985
+ now;
986
+ cacheTtlMs;
987
+ timeoutMs;
988
+ cache;
989
+ constructor(options = {}) {
990
+ this.auth = options.auth;
991
+ this.resolveAuth = options.resolveAuth;
992
+ this.fetchImpl = options.fetch;
993
+ this.now = options.now ?? (() => Date.now());
994
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
995
+ this.timeoutMs = options.timeoutMs;
996
+ }
997
+ async listProviders() {
998
+ return listAgent0ProviderCatalog();
999
+ }
1000
+ async listModels(options = {}) {
1001
+ return (await this.listModelsWithStatus(options)).models;
1002
+ }
1003
+ async listModelsWithStatus(options = {}) {
1004
+ const auth = await this.getAuth();
1005
+ if (!auth?.token || !auth.botId) {
1006
+ return { models: [], warnings: [] };
1007
+ }
1008
+ const cognitiveAuth = { ...auth, token: auth.token, botId: auth.botId };
1009
+ const authKey = getCognitiveAuthCacheKey(cognitiveAuth);
1010
+ if (!options.refresh && this.cache?.authKey === authKey && this.cache.expiresAt > this.now()) {
1011
+ return { models: cloneModels(this.cache.models), warnings: [] };
1012
+ }
1013
+ const models = await fetchBotpressCognitiveModels({
1014
+ token: cognitiveAuth.token,
1015
+ botId: cognitiveAuth.botId,
1016
+ apiUrl: cognitiveAuth.apiUrl,
1017
+ fetch: this.fetchImpl,
1018
+ timeoutMs: this.timeoutMs
1019
+ });
1020
+ if (!models) {
1021
+ return {
1022
+ models: [],
1023
+ warnings: [
1024
+ {
1025
+ code: "CATALOG_SOURCE_UNAVAILABLE",
1026
+ source: this.id,
1027
+ message: "Botpress Cognitive model catalog is unavailable"
1028
+ }
1029
+ ]
1030
+ };
1031
+ }
1032
+ const mapped = models.map((model) => ({
1033
+ providerId: "cognitive",
1034
+ modelId: toCognitiveModelKey(model.id),
1035
+ name: model.name,
1036
+ contextWindow: model.input?.maxTokens,
1037
+ outputLimit: model.output?.maxTokens,
1038
+ inputCostPer1MTokens: model.input?.costPer1MTokens,
1039
+ outputCostPer1MTokens: model.output?.costPer1MTokens,
1040
+ tags: model.tags ? [...model.tags] : undefined
1041
+ }));
1042
+ this.cache = {
1043
+ authKey,
1044
+ expiresAt: this.now() + this.cacheTtlMs,
1045
+ models: mapped
1046
+ };
1047
+ return {
1048
+ models: cloneModels(mapped),
1049
+ warnings: []
1050
+ };
1051
+ }
1052
+ async refresh() {
1053
+ await this.listModels({ refresh: true });
1054
+ }
1055
+ async getAuth() {
1056
+ try {
1057
+ return this.auth ?? await this.resolveAuth?.();
1058
+ } catch {
1059
+ return;
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ class Agent0ModelsDevCatalogSource {
1065
+ id = "models.dev";
1066
+ url;
1067
+ fetchImpl;
1068
+ now;
1069
+ cacheTtlMs;
1070
+ timeoutMs;
1071
+ userAgent;
1072
+ cache;
1073
+ constructor(options = {}) {
1074
+ this.url = options.url ?? DEFAULT_MODELS_DEV_API_URL;
1075
+ this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
1076
+ this.now = options.now ?? (() => Date.now());
1077
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
1078
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_MODELS_DEV_FETCH_TIMEOUT_MS;
1079
+ this.userAgent = options.userAgent ?? "@botpress/adk-agent0";
1080
+ }
1081
+ async listProviders() {
1082
+ return listAgent0ProviderCatalog();
1083
+ }
1084
+ async listModels(options = {}) {
1085
+ if (!options.refresh && this.cache && this.cache.expiresAt > this.now()) {
1086
+ return cloneModels(this.cache.models);
1087
+ }
1088
+ const data = await this.fetchModelsDevCatalog();
1089
+ const models = mapModelsDevCatalog(data, await this.listProviders());
1090
+ this.cache = {
1091
+ expiresAt: this.now() + this.cacheTtlMs,
1092
+ models
1093
+ };
1094
+ return cloneModels(models);
1095
+ }
1096
+ async refresh() {
1097
+ await this.listModels({ refresh: true });
1098
+ }
1099
+ async fetchModelsDevCatalog() {
1100
+ let text;
1101
+ try {
1102
+ const init = {
1103
+ headers: {
1104
+ Accept: "application/json",
1105
+ "User-Agent": this.userAgent
1106
+ }
1107
+ };
1108
+ if (this.timeoutMs > 0)
1109
+ init.signal = AbortSignal.timeout(this.timeoutMs);
1110
+ const response = await this.fetchImpl(this.url, init);
1111
+ if (!response.ok) {
1112
+ throw new Error(`models.dev responded with HTTP ${response.status}`);
1113
+ }
1114
+ text = await response.text();
1115
+ } catch (error) {
1116
+ throw new Agent0ProviderCatalogSourceError("Failed to fetch Agent(0) provider models", error);
1117
+ }
1118
+ try {
1119
+ return JSON.parse(text);
1120
+ } catch (error) {
1121
+ throw new Agent0ProviderCatalogSourceError("Failed to parse Agent(0) provider models", error);
1122
+ }
1123
+ }
1124
+ }
1125
+ function mapModelsDevCatalog(data, providers = listAgent0ProviderCatalog()) {
1126
+ if (!isRecord(data)) {
1127
+ throw new Agent0ProviderCatalogSourceError("models.dev catalog must be an object");
1128
+ }
1129
+ const models = [];
1130
+ for (const provider of providers) {
1131
+ if (provider.modelSource?.type !== "models.dev")
1132
+ continue;
1133
+ const source = data[provider.modelSource.providerId ?? provider.id];
1134
+ if (!isRecord(source))
1135
+ continue;
1136
+ const sourceModels = source.models;
1137
+ if (!isRecord(sourceModels))
1138
+ continue;
1139
+ for (const [key, value] of Object.entries(sourceModels)) {
1140
+ if (!isRecord(value))
1141
+ continue;
1142
+ if (value.status === "deprecated")
1143
+ continue;
1144
+ const modelId = nonEmptyString(value.id) ?? key;
1145
+ const limit = isRecord(value.limit) ? value.limit : undefined;
1146
+ const cost = isRecord(value.cost) ? value.cost : undefined;
1147
+ const tags = value.reasoning === true ? ["reasoning"] : undefined;
1148
+ models.push({
1149
+ providerId: provider.id,
1150
+ modelId,
1151
+ name: nonEmptyString(value.name) ?? modelId,
1152
+ contextWindow: finiteNumber(limit?.context),
1153
+ outputLimit: finiteNumber(limit?.output),
1154
+ inputCostPer1MTokens: finiteNumber(cost?.input),
1155
+ outputCostPer1MTokens: finiteNumber(cost?.output),
1156
+ tags
1157
+ });
1158
+ }
1159
+ }
1160
+ return models;
1161
+ }
1162
+ function cloneModels(models) {
1163
+ return models.map((model) => ({
1164
+ ...model,
1165
+ tags: model.tags ? [...model.tags] : undefined
1166
+ }));
1167
+ }
1168
+ function isRecord(value) {
1169
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1170
+ }
1171
+ function nonEmptyString(value) {
1172
+ return typeof value === "string" && value.trim() ? value : undefined;
1173
+ }
1174
+ function finiteNumber(value) {
1175
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
1176
+ }
1177
+ async function listSourceModelsWithStatus(source, options) {
1178
+ try {
1179
+ if (source.listModelsWithStatus)
1180
+ return await source.listModelsWithStatus(options);
1181
+ return {
1182
+ models: await source.listModels(options),
1183
+ warnings: []
1184
+ };
1185
+ } catch (error) {
1186
+ return {
1187
+ models: [],
1188
+ warnings: [toSourceUnavailableWarning(source, error)]
1189
+ };
1190
+ }
1191
+ }
1192
+ function getCognitiveAuthCacheKey(auth) {
1193
+ return JSON.stringify({
1194
+ apiUrl: auth.apiUrl ?? "",
1195
+ botId: auth.botId,
1196
+ token: auth.token
1197
+ });
1198
+ }
1199
+ function toSourceUnavailableWarning(source, error) {
1200
+ return {
1201
+ code: "CATALOG_SOURCE_UNAVAILABLE",
1202
+ source: source.id ?? "unknown",
1203
+ message: error instanceof Error ? error.message : "Provider model catalog source is unavailable"
1204
+ };
1205
+ }
1206
+ function createAgent0DefaultProviderCatalogSource(options = {}) {
1207
+ return new Agent0CompositeProviderCatalogSource({
1208
+ sources: [new Agent0CognitiveCatalogSource(options.cognitive), new Agent0ModelsDevCatalogSource(options.modelsDev)]
1209
+ });
1210
+ }
1211
+
1212
+ // src/agent0/providers/registry.ts
1213
+ class Agent0ProviderRegistry {
1214
+ store;
1215
+ catalogSource;
1216
+ now;
1217
+ constructor(options = {}) {
1218
+ this.store = options.store ?? new Agent0ConfigStore;
1219
+ this.catalogSource = options.catalogSource ?? createAgent0DefaultProviderCatalogSource(options.catalogSourceOptions);
1220
+ this.now = options.now ?? (() => new Date);
1221
+ }
1222
+ async listProviders() {
1223
+ return (await this.listProvidersWithStatus()).providers;
1224
+ }
1225
+ async listProvidersWithStatus() {
1226
+ const [configResult, catalog, modelResult] = await Promise.all([
1227
+ this.readConfigWithStatus(),
1228
+ this.listCatalogProviders(),
1229
+ this.listCatalogModelsWithStatus()
1230
+ ]);
1231
+ const { config } = configResult;
1232
+ const redacted = redactAgent0Config(config);
1233
+ const modelCounts = countModelsByProvider(modelResult.models);
1234
+ const providers = catalog.map((entry) => {
1235
+ const connection = redacted.providers[entry.id];
1236
+ const stored = config.providers[entry.id];
1237
+ const connected = entry.auth.type === "none" || hasAgent0ProviderAuth(stored);
1238
+ const enabled = connection?.enabled ?? entry.enabledByDefault;
1239
+ return {
1240
+ id: entry.id,
1241
+ name: entry.name,
1242
+ displayName: entry.displayName,
1243
+ description: entry.description,
1244
+ firstParty: entry.firstParty,
1245
+ status: entry.status,
1246
+ enabled,
1247
+ connected,
1248
+ auth: entry.auth,
1249
+ connection,
1250
+ modelCount: modelCounts.get(entry.id) ?? 0
1251
+ };
1252
+ });
1253
+ return { providers, warnings: [...configResult.warnings, ...modelResult.warnings] };
1254
+ }
1255
+ async listModels() {
1256
+ return (await this.listModelsWithStatus()).models;
1257
+ }
1258
+ async listModelsWithStatus() {
1259
+ const [configResult, catalog, catalogModelResult] = await Promise.all([
1260
+ this.readConfigWithStatus(),
1261
+ this.listCatalogProviders(),
1262
+ this.listCatalogModelsWithStatus()
1263
+ ]);
1264
+ const { config } = configResult;
1265
+ const entries = new Map(catalog.map((entry) => [entry.id, entry]));
1266
+ const models = [];
1267
+ for (const model of catalogModelResult.models) {
1268
+ const entry = entries.get(model.providerId);
1269
+ if (!entry)
1270
+ continue;
1271
+ if (!this.isProviderUsable(entry, config.providers[entry.id]))
1272
+ continue;
1273
+ models.push(toAgent0AvailableModel(entry, model));
1274
+ }
1275
+ return { models, warnings: [...configResult.warnings, ...catalogModelResult.warnings] };
1276
+ }
1277
+ async putProviderAuth(providerId, input) {
1278
+ const entry = requireAgent0ProviderCatalogEntry(providerId);
1279
+ if (entry.auth.type !== "api_key") {
1280
+ throw new Error(`Agent(0) provider ${providerId} does not support API-key authentication`);
1281
+ }
1282
+ const now = this.now().toISOString();
1283
+ const config = await this.store.update((draft) => {
1284
+ const existing = draft.providers[providerId];
1285
+ draft.providers[providerId] = {
1286
+ providerId,
1287
+ enabled: input.enabled ?? existing?.enabled ?? true,
1288
+ auth: compactAuth({
1289
+ type: "api_key",
1290
+ apiKey: input.apiKey,
1291
+ baseURL: input.baseURL
1292
+ }),
1293
+ createdAt: existing?.createdAt ?? now,
1294
+ updatedAt: now
1295
+ };
1296
+ });
1297
+ return redactAgent0Config(config).providers[providerId];
1298
+ }
1299
+ async removeProviderAuth(providerId) {
1300
+ requireAgent0ProviderCatalogEntry(providerId);
1301
+ const now = this.now().toISOString();
1302
+ const config = await this.store.update((draft) => {
1303
+ const existing = draft.providers[providerId];
1304
+ if (!existing)
1305
+ return;
1306
+ draft.providers[providerId] = {
1307
+ ...existing,
1308
+ auth: undefined,
1309
+ updatedAt: now
1310
+ };
1311
+ });
1312
+ return redactAgent0Config(config).providers[providerId];
1313
+ }
1314
+ async setProviderEnabled(providerId, enabled) {
1315
+ const entry = requireAgent0ProviderCatalogEntry(providerId);
1316
+ if (enabled && entry.status !== "available") {
1317
+ throw new Error(`Agent(0) provider ${providerId} is not available yet`);
1318
+ }
1319
+ const current = await this.store.read();
1320
+ if (enabled && entry.auth.type === "api_key" && !hasAgent0ProviderAuth(current.providers[providerId])) {
1321
+ throw new Error(`Agent(0) provider ${providerId} must be connected before it can be enabled`);
1322
+ }
1323
+ const now = this.now().toISOString();
1324
+ const config = await this.store.update((draft) => {
1325
+ const existing = draft.providers[providerId];
1326
+ draft.providers[providerId] = {
1327
+ providerId,
1328
+ enabled,
1329
+ auth: existing?.auth,
1330
+ createdAt: existing?.createdAt ?? now,
1331
+ updatedAt: now
1332
+ };
1333
+ });
1334
+ return redactAgent0Config(config).providers[providerId];
1335
+ }
1336
+ isProviderUsable(entry, connection) {
1337
+ if (entry.status !== "available")
1338
+ return false;
1339
+ const enabled = connection?.enabled ?? entry.enabledByDefault;
1340
+ if (!enabled)
1341
+ return false;
1342
+ if (entry.auth.type === "none")
1343
+ return true;
1344
+ return hasAgent0ProviderAuth(connection);
1345
+ }
1346
+ async listCatalogProviders() {
1347
+ try {
1348
+ return await this.catalogSource.listProviders();
1349
+ } catch {
1350
+ return listAgent0ProviderCatalog();
1351
+ }
1352
+ }
1353
+ async readConfigWithStatus() {
1354
+ try {
1355
+ return { config: await this.store.read(), warnings: [] };
1356
+ } catch (error) {
1357
+ if (!(error instanceof Agent0ConfigError))
1358
+ throw error;
1359
+ return {
1360
+ config: createDefaultAgent0Config(this.now()),
1361
+ warnings: [
1362
+ {
1363
+ code: "CONFIG_UNAVAILABLE",
1364
+ source: "agent0-config",
1365
+ message: "Saved Agent(0) provider settings are unavailable."
1366
+ }
1367
+ ]
1368
+ };
1369
+ }
1370
+ }
1371
+ async listCatalogModelsWithStatus() {
1372
+ try {
1373
+ if (this.catalogSource.listModelsWithStatus) {
1374
+ return await this.catalogSource.listModelsWithStatus();
1375
+ }
1376
+ return { models: await this.catalogSource.listModels(), warnings: [] };
1377
+ } catch (error) {
1378
+ return {
1379
+ models: [],
1380
+ warnings: [
1381
+ {
1382
+ code: "CATALOG_SOURCE_UNAVAILABLE",
1383
+ source: this.catalogSource.id ?? "unknown",
1384
+ message: error instanceof Error ? error.message : "Provider model catalog source is unavailable"
1385
+ }
1386
+ ]
1387
+ };
1388
+ }
1389
+ }
1390
+ }
1391
+ function compactAuth(auth) {
1392
+ const baseURL = auth.baseURL?.trim();
1393
+ return {
1394
+ type: auth.type,
1395
+ apiKey: auth.apiKey,
1396
+ ...baseURL ? { baseURL } : {}
1397
+ };
1398
+ }
1399
+ function countModelsByProvider(models) {
1400
+ const counts = new Map;
1401
+ for (const model of models) {
1402
+ counts.set(model.providerId, (counts.get(model.providerId) ?? 0) + 1);
1403
+ }
1404
+ return counts;
1405
+ }
1406
+ // src/agent0/runtime/process.ts
1407
+ import { execFileSync, spawn } from "node:child_process";
1408
+ import { randomUUID } from "node:crypto";
1409
+ import { chmodSync, copyFileSync, createWriteStream, existsSync as existsSync3, mkdirSync, renameSync, rmSync } from "node:fs";
1410
+ import { createRequire as createRequire2 } from "node:module";
1411
+ import { arch, homedir as homedir2, platform as platform2, tmpdir } from "node:os";
1412
+ import { delimiter, dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
1413
+ import { pipeline } from "node:stream/promises";
1414
+
1415
+ // src/agent0/runtime/permissions.ts
1416
+ var AGENT0_BUILT_IN_MCP_PERMISSION = "adk_*";
1417
+ var AGENT0_HIDDEN_OPENCODE_SKILL = "customize-opencode";
1418
+ var AGENT0_OPEN_CODE_PERMISSION_POLICY = Object.freeze({
1419
+ question: "allow",
1420
+ read: "allow",
1421
+ list: "allow",
1422
+ glob: "allow",
1423
+ grep: "allow",
1424
+ edit: "allow",
1425
+ bash: "allow",
1426
+ todowrite: "allow",
1427
+ task: "allow",
1428
+ webfetch: "allow",
1429
+ websearch: "allow",
1430
+ skill: {
1431
+ "*": "allow",
1432
+ [AGENT0_HIDDEN_OPENCODE_SKILL]: "deny"
1433
+ },
1434
+ lsp: "allow",
1435
+ external_directory: "deny",
1436
+ repo_clone: "deny",
1437
+ repo_overview: "allow",
1438
+ [AGENT0_BUILT_IN_MCP_PERMISSION]: "allow"
1439
+ });
1440
+ function buildAgent0OpenCodePermissionConfig() {
1441
+ return Object.fromEntries(Object.entries(AGENT0_OPEN_CODE_PERMISSION_POLICY).map(([key, value]) => [
1442
+ key,
1443
+ typeof value === "string" ? value : { ...value }
1444
+ ]));
1445
+ }
1446
+
1447
+ // src/agent0/runtime/project-discovery.ts
1448
+ import { chmod as chmod3, mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
1449
+ import { platform } from "node:os";
1450
+ import { join as join3 } from "node:path";
1451
+ var AGENT0_PROJECT_ID_CACHE_GUARD_ENV = "OPENCODE_AGENT0_DISABLE_PROJECT_ID_CACHE";
1452
+ var GIT_SHIM_MODE = 448;
1453
+ var POSIX_GIT_SHIM = `#!/bin/sh
1454
+
1455
+ if [ "\${OPENCODE_AGENT0_DISABLE_PROJECT_ID_CACHE:-}" = "1" ] \\
1456
+ && [ "$#" -eq 3 ] \\
1457
+ && [ "$1" = "rev-list" ] \\
1458
+ && [ "$2" = "--max-parents=0" ] \\
1459
+ && [ "$3" = "HEAD" ]; then
1460
+ parent_comm=$(ps -p "$PPID" -o comm= 2>/dev/null || true)
1461
+ parent_base=\${parent_comm##*/}
1462
+ case "$parent_base" in
1463
+ sh|bash|zsh|fish|dash|ksh|tcsh|csh|pwsh|powershell|powershell.exe|cmd|cmd.exe)
1464
+ ;;
1465
+ *)
1466
+ exit 1
1467
+ ;;
1468
+ esac
1469
+ fi
1470
+
1471
+ if [ -n "\${AGENT0_REAL_GIT:-}" ]; then
1472
+ exec "$AGENT0_REAL_GIT" "$@"
1473
+ fi
1474
+
1475
+ real_git=
1476
+ self_dir=$(CDPATH= cd "$(dirname "$0")" 2>/dev/null && pwd -P)
1477
+ old_ifs=$IFS
1478
+ IFS=:
1479
+ for dir in \${PATH:-}; do
1480
+ [ -n "$dir" ] || dir=.
1481
+ resolved=$(CDPATH= cd "$dir" 2>/dev/null && pwd -P || true)
1482
+ [ "$resolved" = "$self_dir" ] && continue
1483
+ candidate=$dir/git
1484
+ if [ -x "$candidate" ]; then
1485
+ real_git=$candidate
1486
+ break
1487
+ fi
1488
+ done
1489
+ IFS=$old_ifs
1490
+
1491
+ if [ -z "$real_git" ]; then
1492
+ echo "Agent(0) git shim could not locate the real git executable" >&2
1493
+ exit 127
1494
+ fi
1495
+
1496
+ exec "$real_git" "$@"
1497
+ `;
1498
+ var WINDOWS_GIT_SHIM = `@echo off
1499
+ setlocal EnableExtensions DisableDelayedExpansion
1500
+
1501
+ if "%OPENCODE_AGENT0_DISABLE_PROJECT_ID_CACHE%"=="1" (
1502
+ if "%~1"=="rev-list" if "%~2"=="--max-parents=0" if "%~3"=="HEAD" if "%~4"=="" (
1503
+ exit /b 1
1504
+ )
1505
+ )
1506
+
1507
+ if not "%AGENT0_REAL_GIT%"=="" (
1508
+ "%AGENT0_REAL_GIT%" %*
1509
+ exit /b %ERRORLEVEL%
1510
+ )
1511
+
1512
+ for /f "delims=" %%G in ('where.exe git 2^>nul') do (
1513
+ if /I not "%%~fG"=="%~f0" (
1514
+ "%%~fG" %*
1515
+ exit /b %ERRORLEVEL%
1516
+ )
1517
+ )
1518
+
1519
+ echo Agent(0) git shim could not locate the real git executable 1>&2
1520
+ exit /b 127
1521
+ `;
1522
+ function getAgent0ProjectDiscoveryGitShimFilename(targetPlatform = platform()) {
1523
+ return targetPlatform === "win32" ? "git.cmd" : "git";
1524
+ }
1525
+ async function ensureAgent0ProjectDiscoveryGitShim(paths2) {
1526
+ const targetPlatform = platform();
1527
+ const shimPath = join3(paths2.engineBinDir, getAgent0ProjectDiscoveryGitShimFilename(targetPlatform));
1528
+ const shimContent = targetPlatform === "win32" ? WINDOWS_GIT_SHIM : POSIX_GIT_SHIM;
1529
+ await mkdir2(paths2.engineBinDir, { recursive: true, mode: GIT_SHIM_MODE });
1530
+ await chmod3(paths2.engineBinDir, GIT_SHIM_MODE);
1531
+ await writeFile2(shimPath, shimContent, { mode: GIT_SHIM_MODE });
1532
+ await chmod3(shimPath, GIT_SHIM_MODE);
1533
+ return shimPath;
1534
+ }
1535
+
1536
+ // src/agent0/runtime/engine.ts
1537
+ function buildAgent0OpenCodeAuthContent(config) {
1538
+ return Object.fromEntries(getAgent0OpenCodeAuthenticatedProviders(config).map(([providerId, connection]) => [
1539
+ providerId,
1540
+ { type: "api", key: connection.auth.apiKey }
1541
+ ]));
1542
+ }
1543
+ function buildAgent0OpenCodeConfig(options) {
1544
+ const builtIns = buildAgent0BuiltInCapabilities({
1545
+ adkDevConsolePort: options.adkDevConsolePort,
1546
+ agentPath: options.agentPath
1547
+ });
1548
+ const authenticatedProviders = options.agent0Config ? getAgent0OpenCodeAuthenticatedProviders(options.agent0Config) : [];
1549
+ const externalProviderConfig = Object.fromEntries(authenticatedProviders.flatMap(([providerId, connection]) => connection.auth.baseURL ? [[providerId, { options: { baseURL: connection.auth.baseURL } }]] : []));
1550
+ const provider = {
1551
+ ...externalProviderConfig,
1552
+ ...options.cognitiveModels === undefined ? {} : { cognitive: buildAgent0CognitiveProvider(options) }
1553
+ };
1554
+ const enabledProviders = [
1555
+ ...options.cognitiveModels === undefined ? [] : ["cognitive"],
1556
+ ...authenticatedProviders.map(([providerId]) => providerId)
1557
+ ];
1558
+ return {
1559
+ ...options.openCodePort ? {
1560
+ server: {
1561
+ port: options.openCodePort,
1562
+ ...options.corsOrigins?.length ? { cors: [...options.corsOrigins] } : {}
1563
+ }
1564
+ } : {},
1565
+ ...options.agent0Config || options.cognitiveModels !== undefined ? { enabled_providers: enabledProviders } : {},
1566
+ ...Object.keys(provider).length ? { provider } : {},
1567
+ mcp: builtIns.mcp,
1568
+ permission: buildAgent0OpenCodePermissionConfig(),
1569
+ default_agent: builtIns.defaultAgent,
1570
+ agent: builtIns.agent,
1571
+ ...Object.keys(builtIns.command).length ? { command: builtIns.command } : {},
1572
+ plugin: [],
1573
+ skills: builtIns.skills,
1574
+ instructions: builtIns.instructions,
1575
+ share: "disabled",
1576
+ autoupdate: false
1577
+ };
1578
+ }
1579
+ function buildAgent0CognitiveProvider(options) {
1580
+ const baseURL = `http://localhost:${options.adkDevConsolePort}/api/agent-proxy/${encodeURIComponent(options.agentPath)}/api/cognitive/v1`;
1581
+ const models = Object.fromEntries((options.cognitiveModels ?? []).filter((model) => model.providerId === "cognitive").map((model) => [
1582
+ model.modelId,
1583
+ {
1584
+ id: model.modelId,
1585
+ name: model.name,
1586
+ ...renderCognitiveModelCostAndLimits(model)
1587
+ }
1588
+ ]));
1589
+ return {
1590
+ api: "openai-completions",
1591
+ name: "Botpress Cognitive",
1592
+ options: { apiKey: "cognitive", baseURL },
1593
+ models
1594
+ };
1595
+ }
1596
+ function buildAgent0OpenCodeEnv(paths2, config, authContent = {}) {
1597
+ return {
1598
+ XDG_CONFIG_HOME: paths2.xdgConfigHome,
1599
+ XDG_DATA_HOME: paths2.xdgDataHome,
1600
+ XDG_CACHE_HOME: paths2.xdgCacheHome,
1601
+ XDG_STATE_HOME: paths2.xdgStateHome,
1602
+ OPENCODE_CONFIG_DIR: paths2.engineConfigDir,
1603
+ OPENCODE_CONFIG_CONTENT: JSON.stringify(config),
1604
+ OPENCODE_AUTH_CONTENT: JSON.stringify(authContent),
1605
+ OPENCODE_TEST_HOME: paths2.fakeHomeDir,
1606
+ OPENCODE_PURE: "1",
1607
+ OPENCODE_DISABLE_PROJECT_CONFIG: "1",
1608
+ OPENCODE_DISABLE_EXTERNAL_SKILLS: "1",
1609
+ OPENCODE_DISABLE_DEFAULT_PLUGINS: "1",
1610
+ OPENCODE_DISABLE_CLAUDE_CODE: "1",
1611
+ OPENCODE_DISABLE_CLAUDE_CODE_SKILLS: "1",
1612
+ OPENCODE_DISABLE_AUTOUPDATE: "1",
1613
+ OPENCODE_DISABLE_SHARE: "1",
1614
+ [AGENT0_PROJECT_ID_CACHE_GUARD_ENV]: "1",
1615
+ PATH: ""
1616
+ };
1617
+ }
1618
+ function renderAgent0OpenCodeRuntime(options) {
1619
+ const config = buildAgent0OpenCodeConfig(options);
1620
+ const authContent = options.agent0Config ? buildAgent0OpenCodeAuthContent(options.agent0Config) : {};
1621
+ return {
1622
+ config,
1623
+ authContent,
1624
+ env: buildAgent0OpenCodeEnv(options.paths, config, authContent)
1625
+ };
1626
+ }
1627
+ async function prepareAgent0OpenCodeRuntime(options) {
1628
+ await ensureAgent0ProjectDiscoveryGitShim(options.paths);
1629
+ return renderAgent0OpenCodeRuntime(options);
1630
+ }
1631
+ function getAgent0OpenCodeAuthenticatedProviders(config) {
1632
+ return Object.entries(config.providers).sort(([left], [right]) => left.localeCompare(right)).flatMap(([, connection]) => {
1633
+ if (!connection.enabled || connection.auth?.type !== "api_key")
1634
+ return [];
1635
+ const entry = getAgent0ProviderCatalogEntry(connection.providerId);
1636
+ if (!entry)
1637
+ throw new Error(`Unknown Agent(0) provider: ${connection.providerId}`);
1638
+ if (entry.firstParty || entry.auth.type !== "api_key")
1639
+ return [];
1640
+ const providerId = entry.modelSource?.type === "models.dev" ? entry.modelSource.providerId ?? entry.id : undefined;
1641
+ if (!providerId)
1642
+ throw new Error(`Agent(0) provider ${connection.providerId} has no OpenCode provider source`);
1643
+ return [[providerId, { ...connection, auth: connection.auth }]];
1644
+ });
1645
+ }
1646
+ function renderCognitiveModelCostAndLimits(model) {
1647
+ if (model.inputCostPer1MTokens === undefined && model.outputCostPer1MTokens === undefined && model.contextWindow === undefined && model.outputLimit === undefined) {
1648
+ return {};
1649
+ }
1650
+ return {
1651
+ cost: {
1652
+ input: model.inputCostPer1MTokens ?? 0,
1653
+ output: model.outputCostPer1MTokens ?? 0
1654
+ },
1655
+ limit: {
1656
+ context: model.contextWindow ?? 0,
1657
+ output: model.outputLimit ?? 0
1658
+ }
1659
+ };
1660
+ }
1661
+
1662
+ // src/agent0/runtime/process.ts
1663
+ var DEFAULT_STARTUP_TIMEOUT_MS = 15000;
1664
+ var AGENT0_OPENCODE_HOSTNAME = "127.0.0.1";
1665
+ var DEFAULT_SERVER_USERNAME = "agent0";
1666
+ var OPENCODE_VERSION = "1.15.10";
1667
+ var PROVIDER_AUTH_ENV_KEYS = new Set([
1668
+ "AICORE_SERVICE_KEY",
1669
+ "ANTHROPIC_API_KEY",
1670
+ "AWS_ACCESS_KEY_ID",
1671
+ "AWS_BEARER_TOKEN_BEDROCK",
1672
+ "AWS_SECRET_ACCESS_KEY",
1673
+ "AWS_SESSION_TOKEN",
1674
+ "AZURE_OPENAI_API_KEY",
1675
+ "CEREBRAS_API_KEY",
1676
+ "CF_AIG_TOKEN",
1677
+ "CLOUDFLARE_API_KEY",
1678
+ "CLOUDFLARE_API_TOKEN",
1679
+ "COHERE_API_KEY",
1680
+ "DASHSCOPE_API_KEY",
1681
+ "DEEPSEEK_API_KEY",
1682
+ "FIREWORKS_API_KEY",
1683
+ "GEMINI_API_KEY",
1684
+ "GROQ_API_KEY",
1685
+ "MISTRAL_API_KEY",
1686
+ "MOONSHOT_API_KEY",
1687
+ "OPENAI_API_KEY",
1688
+ "OPENROUTER_API_KEY",
1689
+ "PERPLEXITY_API_KEY",
1690
+ "QWEN_API_KEY",
1691
+ "TOGETHER_API_KEY",
1692
+ "TOGETHERAI_API_KEY",
1693
+ "XAI_API_KEY"
1694
+ ]);
1695
+ function sanitizeAgent0OpenCodeBaseEnv(env) {
1696
+ return Object.fromEntries(Object.entries(env).filter(([key]) => !shouldStripEnv(key)));
1697
+ }
1698
+ function buildAgent0OpenCodeProcessEnv(options) {
1699
+ return {
1700
+ ...sanitizeAgent0OpenCodeBaseEnv(options.baseEnv),
1701
+ ...options.runtimeEnv,
1702
+ OPENCODE_SERVER_USERNAME: options.serverAuth.username,
1703
+ OPENCODE_SERVER_PASSWORD: options.serverAuth.password
1704
+ };
1705
+ }
1706
+ function buildAgent0OpenCodeAuthHeaders(auth) {
1707
+ return {
1708
+ Authorization: `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`
1709
+ };
1710
+ }
1711
+ async function resolveAgent0OpenCodeBinary(options = {}) {
1712
+ const local = (options.findNodeModulesBinary ?? findAgent0OpenCodeBinaryInNodeModules)();
1713
+ if (local)
1714
+ return local;
1715
+ const cached = getCachedAgent0OpenCodeBinary(options);
1716
+ if (cached)
1717
+ return cached;
1718
+ return downloadAgent0OpenCodeBinary(options);
1719
+ }
1720
+ function findAgent0OpenCodeBinaryInNodeModules() {
1721
+ const require2 = createRequire2(import.meta.url);
1722
+ try {
1723
+ const packageJsonPath = require2.resolve("opencode-ai/package.json");
1724
+ const packageDir = dirname3(packageJsonPath);
1725
+ const candidates = [resolve2(packageDir, "bin", "opencode.exe"), resolve2(packageDir, "bin", "opencode")];
1726
+ return candidates.find((candidate) => existsSync3(candidate)) ?? null;
1727
+ } catch {
1728
+ return null;
1729
+ }
1730
+ }
1731
+ function getCachedAgent0OpenCodeBinary(options) {
1732
+ const binary = join4(getAgent0OpenCodeCacheDir(options), getAgent0OpenCodeBinaryName());
1733
+ return existsSync3(binary) ? binary : null;
1734
+ }
1735
+ async function downloadAgent0OpenCodeBinary(options) {
1736
+ const version = options.version ?? OPENCODE_VERSION;
1737
+ if (version === "0.0.0") {
1738
+ throw new Error("Unable to resolve pinned opencode-ai version");
1739
+ }
1740
+ const { name, binary } = getAgent0OpenCodePlatformPackage();
1741
+ const tarballUrl = `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`;
1742
+ const fetchImpl = options.fetch ?? fetch;
1743
+ const cacheDir = getAgent0OpenCodeCacheDir(options);
1744
+ const tmpDirPath = join4(tmpdir(), `agent0-opencode-download-${Date.now()}`);
1745
+ options.onLog?.(`Downloading opencode v${version} (${name})...`);
1746
+ mkdirSync(cacheDir, { recursive: true });
1747
+ mkdirSync(tmpDirPath, { recursive: true });
1748
+ try {
1749
+ const tarPath = join4(tmpDirPath, "opencode.tgz");
1750
+ const response = await fetchImpl(tarballUrl);
1751
+ if (!response.ok || !response.body) {
1752
+ throw new Error(`Failed to download ${tarballUrl}: ${response.status} ${response.statusText}`);
1753
+ }
1754
+ await pipeline(response.body, createWriteStream(tarPath));
1755
+ const extractDir = join4(tmpDirPath, "extracted");
1756
+ mkdirSync(extractDir, { recursive: true });
1757
+ execFileSync("tar", ["xzf", tarPath, "-C", extractDir, `package/bin/${binary}`]);
1758
+ const extractedBinary = join4(extractDir, "package", "bin", binary);
1759
+ if (!existsSync3(extractedBinary)) {
1760
+ throw new Error(`Binary not found at expected path package/bin/${binary} in ${name}@${version} tarball`);
1761
+ }
1762
+ const destBinary = join4(cacheDir, binary);
1763
+ const tmpBinary = `${destBinary}.tmp`;
1764
+ copyFileSync(extractedBinary, tmpBinary);
1765
+ if (platform2() !== "win32")
1766
+ chmodSync(tmpBinary, 493);
1767
+ renameSync(tmpBinary, destBinary);
1768
+ options.onLog?.(`Opencode v${version} cached at ${cacheDir}`);
1769
+ return destBinary;
1770
+ } finally {
1771
+ try {
1772
+ rmSync(tmpDirPath, { recursive: true, force: true });
1773
+ } catch {}
1774
+ }
1775
+ }
1776
+ function getAgent0OpenCodeCacheDir(options) {
1777
+ return join4(options.homeDir ?? homedir2(), ".adk", "opencode", options.version ?? OPENCODE_VERSION);
1778
+ }
1779
+ function getAgent0OpenCodeBinaryName() {
1780
+ return platform2() === "win32" ? "opencode.exe" : "opencode";
1781
+ }
1782
+ function getAgent0OpenCodePlatformPackage() {
1783
+ const plat = platform2() === "win32" ? "windows" : platform2();
1784
+ const packageArch = arch() === "arm64" ? "arm64" : "x64";
1785
+ return {
1786
+ name: `opencode-${plat}-${packageArch}`,
1787
+ binary: getAgent0OpenCodeBinaryName()
1788
+ };
1789
+ }
1790
+ async function startAgent0OpenCodeProcess(options) {
1791
+ const runtime = await prepareAgent0OpenCodeRuntime(options);
1792
+ const baseEnv = options.env ?? process.env;
1793
+ const serverAuth = {
1794
+ username: options.serverUsername ?? DEFAULT_SERVER_USERNAME,
1795
+ password: options.serverPassword ?? randomUUID()
1796
+ };
1797
+ const child = spawn(options.binaryPath ?? await resolveAgent0OpenCodeBinary({ onLog: options.onLog }), ["serve", "--hostname", AGENT0_OPENCODE_HOSTNAME, "--port", "0", "--pure"], {
1798
+ cwd: options.cwd ?? options.paths.canonicalProjectPath,
1799
+ env: buildAgent0OpenCodeProcessEnv({
1800
+ baseEnv,
1801
+ runtimeEnv: {
1802
+ ...runtime.env,
1803
+ PATH: prependPath(options.paths.engineBinDir, baseEnv.PATH ?? baseEnv.Path)
1804
+ },
1805
+ serverAuth
1806
+ }),
1807
+ stdio: ["ignore", "pipe", "pipe"]
1808
+ });
1809
+ try {
1810
+ const baseURL = await waitForOpenCodeServer(child, {
1811
+ timeoutMs: options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS,
1812
+ signal: options.signal,
1813
+ onLog: options.onLog
1814
+ });
1815
+ return {
1816
+ baseURL,
1817
+ authHeaders: buildAgent0OpenCodeAuthHeaders(serverAuth),
1818
+ pid: child.pid,
1819
+ stop: () => stopAgent0OpenCodeProcess(child)
1820
+ };
1821
+ } catch (error) {
1822
+ await stopAgent0OpenCodeProcess(child);
1823
+ throw error;
1824
+ }
1825
+ }
1826
+ async function stopAgent0OpenCodeProcess(child) {
1827
+ if (child.exitCode !== null || child.signalCode !== null)
1828
+ return;
1829
+ await new Promise((resolveStop) => {
1830
+ const timeout = setTimeout(() => {
1831
+ child.kill("SIGKILL");
1832
+ resolveStop();
1833
+ }, 1000);
1834
+ child.once("exit", () => {
1835
+ clearTimeout(timeout);
1836
+ resolveStop();
1837
+ });
1838
+ child.kill("SIGTERM");
1839
+ });
1840
+ }
1841
+ function shouldStripEnv(key) {
1842
+ const normalized = key.toUpperCase();
1843
+ return normalized.startsWith("OPENCODE_") || normalized.startsWith("XDG_") || normalized.startsWith("AGENT0_") || PROVIDER_AUTH_ENV_KEYS.has(normalized);
1844
+ }
1845
+ async function waitForOpenCodeServer(child, options) {
1846
+ const chunks = [];
1847
+ return new Promise((resolveReady, rejectReady) => {
1848
+ let settled = false;
1849
+ const timeout = setTimeout(() => {
1850
+ finish(new Error(`Agent(0) private OpenCode runtime did not start within ${options.timeoutMs}ms`));
1851
+ }, options.timeoutMs);
1852
+ const finish = (error, url) => {
1853
+ if (settled)
1854
+ return;
1855
+ settled = true;
1856
+ clearTimeout(timeout);
1857
+ child.stdout.off("data", onData);
1858
+ child.stderr.off("data", onData);
1859
+ child.off("error", onError);
1860
+ child.off("exit", onExit);
1861
+ options.signal?.removeEventListener("abort", onAbort);
1862
+ if (error)
1863
+ rejectReady(appendStartupOutput(error, chunks));
1864
+ else
1865
+ resolveReady(url);
1866
+ };
1867
+ const onData = (data) => {
1868
+ const text = data.toString("utf8");
1869
+ chunks.push(text);
1870
+ options.onLog?.(text);
1871
+ const match = /opencode server listening on (http:\/\/[^\s]+)/.exec(chunks.join(""));
1872
+ if (match)
1873
+ finish(undefined, match[1]);
1874
+ };
1875
+ const onExit = (code, signal) => {
1876
+ finish(new Error(`Agent(0) private OpenCode runtime exited before startup: code=${code} signal=${signal}`));
1877
+ };
1878
+ const onError = (error) => {
1879
+ finish(error);
1880
+ };
1881
+ const onAbort = () => {
1882
+ child.kill("SIGTERM");
1883
+ finish(new Error("Agent(0) private OpenCode runtime startup aborted"));
1884
+ };
1885
+ child.stdout.on("data", onData);
1886
+ child.stderr.on("data", onData);
1887
+ child.on("error", onError);
1888
+ child.on("exit", onExit);
1889
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1890
+ if (options.signal?.aborted)
1891
+ onAbort();
1892
+ });
1893
+ }
1894
+ function appendStartupOutput(error, chunks) {
1895
+ const output = chunks.join("").trim();
1896
+ if (!output)
1897
+ return error;
1898
+ return new Error(`${error.message}
1899
+ ${output}`);
1900
+ }
1901
+ function prependPath(dir, currentPath) {
1902
+ return currentPath ? `${dir}${delimiter}${currentPath}` : dir;
1903
+ }
1904
+
1905
+ // src/agent0/runtime/client.ts
1906
+ class Agent0RuntimeClientError extends Error {
1907
+ cause;
1908
+ code;
1909
+ status;
1910
+ constructor(code, message, options = {}) {
1911
+ super(message);
1912
+ this.name = "Agent0RuntimeClientError";
1913
+ this.code = code;
1914
+ this.cause = options.cause;
1915
+ this.status = options.status;
1916
+ }
1917
+ }
1918
+ async function startAgent0RuntimeClient(options) {
1919
+ const { fetch: fetchImpl, ...processOptions } = options;
1920
+ const engine = await startAgent0OpenCodeProcess(processOptions);
1921
+ return createAgent0RuntimeClient({
1922
+ engine,
1923
+ projectPath: options.paths.canonicalProjectPath,
1924
+ fetch: fetchImpl
1925
+ });
1926
+ }
1927
+ function createAgent0RuntimeClient(options) {
1928
+ const fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
1929
+ return {
1930
+ async getStatus() {
1931
+ const pathInfo = await fetchAgent0OpenCodeJson({
1932
+ engine: options.engine,
1933
+ fetch: fetchImpl,
1934
+ path: "/path",
1935
+ searchParams: { directory: options.projectPath }
1936
+ });
1937
+ return normalizeAgent0RuntimeStatus(pathInfo, options.projectPath);
1938
+ },
1939
+ async listSessions() {
1940
+ const sessions = await fetchAgent0OpenCodeJson({
1941
+ engine: options.engine,
1942
+ fetch: fetchImpl,
1943
+ path: "/session",
1944
+ searchParams: { directory: options.projectPath, roots: "true" }
1945
+ });
1946
+ if (!Array.isArray(sessions)) {
1947
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid session list response");
1948
+ }
1949
+ return {
1950
+ sessions: sessions.map((session) => normalizeAgent0Session(session, options.projectPath)),
1951
+ warnings: []
1952
+ };
1953
+ },
1954
+ async createSession(input = {}) {
1955
+ const session = await fetchAgent0OpenCodeJson({
1956
+ engine: options.engine,
1957
+ fetch: fetchImpl,
1958
+ path: "/session",
1959
+ method: "POST",
1960
+ searchParams: { directory: options.projectPath },
1961
+ body: toOpenCodeCreateSessionInput(input)
1962
+ });
1963
+ return normalizeAgent0Session(session, options.projectPath);
1964
+ },
1965
+ async listMessages(sessionId) {
1966
+ const messages = await fetchAgent0OpenCodeJson({
1967
+ engine: options.engine,
1968
+ fetch: fetchImpl,
1969
+ path: `/session/${encodeURIComponent(sessionId)}/message`,
1970
+ searchParams: { directory: options.projectPath }
1971
+ });
1972
+ if (!Array.isArray(messages)) {
1973
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid message list response");
1974
+ }
1975
+ return {
1976
+ messages: messages.map(normalizeAgent0Message),
1977
+ warnings: []
1978
+ };
1979
+ },
1980
+ async sendMessage(sessionId, input) {
1981
+ const message = await fetchAgent0OpenCodeJson({
1982
+ engine: options.engine,
1983
+ fetch: fetchImpl,
1984
+ path: `/session/${encodeURIComponent(sessionId)}/message`,
1985
+ method: "POST",
1986
+ searchParams: { directory: options.projectPath },
1987
+ body: toOpenCodePromptInput(input)
1988
+ });
1989
+ return normalizeAgent0Message(message);
1990
+ },
1991
+ async abortSession(sessionId) {
1992
+ const result = await fetchAgent0OpenCodeJson({
1993
+ engine: options.engine,
1994
+ fetch: fetchImpl,
1995
+ path: `/session/${encodeURIComponent(sessionId)}/abort`,
1996
+ method: "POST",
1997
+ searchParams: { directory: options.projectPath }
1998
+ });
1999
+ if (typeof result !== "boolean") {
2000
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid abort response");
2001
+ }
2002
+ return { aborted: result, warnings: [] };
2003
+ },
2004
+ async listQuestions(sessionId) {
2005
+ const questions = await fetchAgent0OpenCodeJson({
2006
+ engine: options.engine,
2007
+ fetch: fetchImpl,
2008
+ path: "/question",
2009
+ searchParams: { directory: options.projectPath }
2010
+ });
2011
+ if (!Array.isArray(questions)) {
2012
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question list response");
2013
+ }
2014
+ const normalized = questions.map(normalizeAgent0QuestionRequest);
2015
+ return {
2016
+ questions: sessionId ? normalized.filter((question) => question.sessionId === sessionId) : normalized,
2017
+ warnings: []
2018
+ };
2019
+ },
2020
+ async replyQuestion(sessionId, questionId, input) {
2021
+ await ensureAgent0QuestionBelongsToSession({
2022
+ engine: options.engine,
2023
+ fetch: fetchImpl,
2024
+ projectPath: options.projectPath,
2025
+ sessionId,
2026
+ questionId
2027
+ });
2028
+ const result = await fetchAgent0OpenCodeJson({
2029
+ engine: options.engine,
2030
+ fetch: fetchImpl,
2031
+ path: `/question/${encodeURIComponent(questionId)}/reply`,
2032
+ method: "POST",
2033
+ searchParams: { directory: options.projectPath },
2034
+ body: { answers: input.answers }
2035
+ });
2036
+ if (typeof result !== "boolean") {
2037
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question reply response");
2038
+ }
2039
+ return { answered: result, warnings: [] };
2040
+ },
2041
+ async rejectQuestion(sessionId, questionId) {
2042
+ await ensureAgent0QuestionBelongsToSession({
2043
+ engine: options.engine,
2044
+ fetch: fetchImpl,
2045
+ projectPath: options.projectPath,
2046
+ sessionId,
2047
+ questionId
2048
+ });
2049
+ const result = await fetchAgent0OpenCodeJson({
2050
+ engine: options.engine,
2051
+ fetch: fetchImpl,
2052
+ path: `/question/${encodeURIComponent(questionId)}/reject`,
2053
+ method: "POST",
2054
+ searchParams: { directory: options.projectPath }
2055
+ });
2056
+ if (typeof result !== "boolean") {
2057
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question reject response");
2058
+ }
2059
+ return { rejected: result, warnings: [] };
2060
+ },
2061
+ async listCommands() {
2062
+ return {
2063
+ commands: listAgent0BuiltInCommands(),
2064
+ warnings: []
2065
+ };
2066
+ },
2067
+ async runCommand(sessionId, input) {
2068
+ const command = getAgent0BuiltInCommand(input.command);
2069
+ if (!command) {
2070
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", `Unknown Agent(0) command: ${input.command}`);
2071
+ }
2072
+ const message = await fetchAgent0OpenCodeJson({
2073
+ engine: options.engine,
2074
+ fetch: fetchImpl,
2075
+ path: `/session/${encodeURIComponent(sessionId)}/message`,
2076
+ method: "POST",
2077
+ searchParams: { directory: options.projectPath },
2078
+ body: toOpenCodePromptInput({
2079
+ parts: [{ type: "text", text: renderAgent0CommandTemplate(command.template, input.arguments) }],
2080
+ mode: input.mode,
2081
+ model: input.model,
2082
+ generateReply: true
2083
+ })
2084
+ });
2085
+ return normalizeAgent0Message(message);
2086
+ },
2087
+ streamEvents(input = {}) {
2088
+ return streamAgent0OpenCodeEvents({
2089
+ engine: options.engine,
2090
+ fetch: fetchImpl,
2091
+ projectPath: options.projectPath,
2092
+ sessionId: input.sessionId,
2093
+ signal: input.signal
2094
+ });
2095
+ },
2096
+ stop() {
2097
+ return options.engine.stop();
2098
+ }
2099
+ };
2100
+ }
2101
+ async function ensureAgent0QuestionBelongsToSession(options) {
2102
+ const questions = await fetchAgent0OpenCodeJson({
2103
+ engine: options.engine,
2104
+ fetch: options.fetch,
2105
+ path: "/question",
2106
+ searchParams: { directory: options.projectPath }
2107
+ });
2108
+ if (!Array.isArray(questions)) {
2109
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question list response");
2110
+ }
2111
+ const belongsToSession = questions.map(normalizeAgent0QuestionRequest).some((question) => question.id === options.questionId && question.sessionId === options.sessionId);
2112
+ if (!belongsToSession) {
2113
+ throw new Agent0RuntimeClientError("ENGINE_HTTP_ERROR", "Agent(0) private runtime question request was not found", {
2114
+ status: 404
2115
+ });
2116
+ }
2117
+ }
2118
+ async function fetchAgent0OpenCodeJson(options) {
2119
+ const url = new URL(options.path, options.engine.baseURL);
2120
+ for (const [key, value] of Object.entries(options.searchParams ?? {})) {
2121
+ url.searchParams.set(key, value);
2122
+ }
2123
+ let response;
2124
+ try {
2125
+ response = await options.fetch(url, {
2126
+ method: options.method ?? "GET",
2127
+ headers: {
2128
+ ...options.engine.authHeaders,
2129
+ ...options.body === undefined ? {} : { "Content-Type": "application/json" }
2130
+ },
2131
+ ...options.body === undefined ? {} : { body: JSON.stringify(options.body) }
2132
+ });
2133
+ } catch (error) {
2134
+ throw new Agent0RuntimeClientError("ENGINE_UNAVAILABLE", "Agent(0) private runtime is unavailable", {
2135
+ cause: error
2136
+ });
2137
+ }
2138
+ if (!response.ok) {
2139
+ let detail = "";
2140
+ try {
2141
+ const body = await response.text();
2142
+ if (body)
2143
+ detail = `: ${body.slice(0, 500)}`;
2144
+ } catch {}
2145
+ throw new Agent0RuntimeClientError("ENGINE_HTTP_ERROR", `Agent(0) private runtime responded with HTTP ${response.status}${detail}`, { status: response.status });
2146
+ }
2147
+ try {
2148
+ return await response.json();
2149
+ } catch (error) {
2150
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned invalid JSON", {
2151
+ cause: error
2152
+ });
2153
+ }
2154
+ }
2155
+ async function* streamAgent0OpenCodeEvents(options) {
2156
+ const url = new URL("/event", options.engine.baseURL);
2157
+ url.searchParams.set("directory", options.projectPath);
2158
+ let response;
2159
+ try {
2160
+ response = await options.fetch(url, {
2161
+ headers: options.engine.authHeaders,
2162
+ signal: options.signal
2163
+ });
2164
+ } catch (error) {
2165
+ throw new Agent0RuntimeClientError("ENGINE_UNAVAILABLE", "Agent(0) private runtime event stream is unavailable", {
2166
+ cause: error
2167
+ });
2168
+ }
2169
+ if (!response.ok) {
2170
+ throw new Agent0RuntimeClientError("ENGINE_HTTP_ERROR", `Agent(0) private runtime event stream responded with HTTP ${response.status}`, { status: response.status });
2171
+ }
2172
+ if (!response.body) {
2173
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an empty event stream");
2174
+ }
2175
+ const reader = response.body.getReader();
2176
+ const decoder = new TextDecoder;
2177
+ let buffer = "";
2178
+ try {
2179
+ while (true) {
2180
+ const chunk = await reader.read();
2181
+ if (chunk.done)
2182
+ break;
2183
+ buffer += decoder.decode(chunk.value, { stream: true }).replace(/\r\n?/g, `
2184
+ `);
2185
+ let separatorIndex;
2186
+ while ((separatorIndex = buffer.indexOf(`
2187
+
2188
+ `)) !== -1) {
2189
+ const record = buffer.slice(0, separatorIndex);
2190
+ buffer = buffer.slice(separatorIndex + 2);
2191
+ const event = normalizeOpenCodeSSERecord(record);
2192
+ if (!event || !matchesAgent0RuntimeEventSession(event, options.sessionId))
2193
+ continue;
2194
+ yield event;
2195
+ }
2196
+ }
2197
+ buffer += decoder.decode();
2198
+ if (buffer.trim().length > 0) {
2199
+ const event = normalizeOpenCodeSSERecord(buffer);
2200
+ if (event && matchesAgent0RuntimeEventSession(event, options.sessionId))
2201
+ yield event;
2202
+ }
2203
+ } finally {
2204
+ await reader.cancel().catch(() => {});
2205
+ }
2206
+ }
2207
+ function normalizeOpenCodeSSERecord(record) {
2208
+ const dataLines = [];
2209
+ for (const line of record.split(`
2210
+ `)) {
2211
+ if (line.length === 0 || line.startsWith(":"))
2212
+ continue;
2213
+ const colon = line.indexOf(":");
2214
+ const field = colon === -1 ? line : line.slice(0, colon);
2215
+ const value2 = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
2216
+ if (field === "data")
2217
+ dataLines.push(value2);
2218
+ }
2219
+ if (dataLines.length === 0)
2220
+ return;
2221
+ let value;
2222
+ try {
2223
+ value = JSON.parse(dataLines.join(`
2224
+ `));
2225
+ } catch {
2226
+ return;
2227
+ }
2228
+ try {
2229
+ return normalizeOpenCodeEvent(value);
2230
+ } catch {
2231
+ return;
2232
+ }
2233
+ }
2234
+ function normalizeOpenCodeEvent(value) {
2235
+ if (!isRecord2(value) || typeof value.type !== "string") {
2236
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid event envelope");
2237
+ }
2238
+ const id = typeof value.id === "string" ? value.id : undefined;
2239
+ const properties = isRecord2(value.properties) ? value.properties : {};
2240
+ switch (value.type) {
2241
+ case "server.connected":
2242
+ return { ...id ? { id } : {}, type: "runtime.connected" };
2243
+ case "server.heartbeat":
2244
+ return { ...id ? { id } : {}, type: "runtime.heartbeat" };
2245
+ case "message.updated": {
2246
+ if (!isRecord2(properties.info))
2247
+ return invalidOpenCodeEvent("message.updated");
2248
+ return { ...id ? { id } : {}, type: "message.updated", message: normalizeAgent0MessageInfo(properties.info) };
2249
+ }
2250
+ case "message.removed": {
2251
+ if (typeof properties.sessionID !== "string" || typeof properties.messageID !== "string") {
2252
+ return invalidOpenCodeEvent("message.removed");
2253
+ }
2254
+ return {
2255
+ ...id ? { id } : {},
2256
+ type: "message.removed",
2257
+ sessionId: properties.sessionID,
2258
+ messageId: properties.messageID
2259
+ };
2260
+ }
2261
+ case "message.part.updated": {
2262
+ if (!isRecord2(properties.part) || typeof properties.sessionID !== "string") {
2263
+ return invalidOpenCodeEvent("message.part.updated");
2264
+ }
2265
+ const messageId = typeof properties.part.messageID === "string" ? properties.part.messageID : typeof properties.messageID === "string" ? properties.messageID : undefined;
2266
+ if (!messageId)
2267
+ return invalidOpenCodeEvent("message.part.updated");
2268
+ const [part] = normalizeAgent0MessagePart(properties.part);
2269
+ if (!part)
2270
+ return;
2271
+ return {
2272
+ ...id ? { id } : {},
2273
+ type: "message.part.updated",
2274
+ sessionId: properties.sessionID,
2275
+ messageId,
2276
+ part,
2277
+ ...typeof properties.time === "number" ? { updatedAt: normalizeTimestamp(properties.time) } : {}
2278
+ };
2279
+ }
2280
+ case "message.part.delta": {
2281
+ if (typeof properties.sessionID !== "string" || typeof properties.messageID !== "string" || typeof properties.partID !== "string" || typeof properties.field !== "string" || typeof properties.delta !== "string") {
2282
+ return invalidOpenCodeEvent("message.part.delta");
2283
+ }
2284
+ return {
2285
+ ...id ? { id } : {},
2286
+ type: "message.part.delta",
2287
+ sessionId: properties.sessionID,
2288
+ messageId: properties.messageID,
2289
+ partId: properties.partID,
2290
+ field: properties.field,
2291
+ delta: properties.delta
2292
+ };
2293
+ }
2294
+ case "message.part.removed": {
2295
+ if (typeof properties.sessionID !== "string" || typeof properties.messageID !== "string" || typeof properties.partID !== "string") {
2296
+ return invalidOpenCodeEvent("message.part.removed");
2297
+ }
2298
+ return {
2299
+ ...id ? { id } : {},
2300
+ type: "message.part.removed",
2301
+ sessionId: properties.sessionID,
2302
+ messageId: properties.messageID,
2303
+ partId: properties.partID
2304
+ };
2305
+ }
2306
+ case "session.status": {
2307
+ if (typeof properties.sessionID !== "string")
2308
+ return invalidOpenCodeEvent("session.status");
2309
+ const status = normalizeAgent0SessionStatus(properties.status);
2310
+ if (!status)
2311
+ return invalidOpenCodeEvent("session.status");
2312
+ return {
2313
+ ...id ? { id } : {},
2314
+ type: "session.status",
2315
+ sessionId: properties.sessionID,
2316
+ status
2317
+ };
2318
+ }
2319
+ case "session.error": {
2320
+ if (!isRecord2(properties.error))
2321
+ return invalidOpenCodeEvent("session.error");
2322
+ return {
2323
+ ...id ? { id } : {},
2324
+ type: "session.error",
2325
+ ...typeof properties.sessionID === "string" ? { sessionId: properties.sessionID } : {},
2326
+ error: { message: normalizeErrorMessage(properties.error) }
2327
+ };
2328
+ }
2329
+ case "question.asked": {
2330
+ return { ...id ? { id } : {}, type: "question.asked", question: normalizeAgent0QuestionRequest(properties) };
2331
+ }
2332
+ case "question.replied": {
2333
+ if (typeof properties.sessionID !== "string" || typeof properties.requestID !== "string" || !Array.isArray(properties.answers)) {
2334
+ return invalidOpenCodeEvent("question.replied");
2335
+ }
2336
+ return {
2337
+ ...id ? { id } : {},
2338
+ type: "question.replied",
2339
+ sessionId: properties.sessionID,
2340
+ questionId: properties.requestID,
2341
+ answers: normalizeQuestionAnswers(properties.answers)
2342
+ };
2343
+ }
2344
+ case "question.rejected": {
2345
+ if (typeof properties.sessionID !== "string" || typeof properties.requestID !== "string") {
2346
+ return invalidOpenCodeEvent("question.rejected");
2347
+ }
2348
+ return {
2349
+ ...id ? { id } : {},
2350
+ type: "question.rejected",
2351
+ sessionId: properties.sessionID,
2352
+ questionId: properties.requestID
2353
+ };
2354
+ }
2355
+ default:
2356
+ return;
2357
+ }
2358
+ }
2359
+ function invalidOpenCodeEvent(type) {
2360
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", `Agent(0) private runtime returned an invalid ${type} event`);
2361
+ }
2362
+ function matchesAgent0RuntimeEventSession(event, sessionId) {
2363
+ if (!sessionId)
2364
+ return true;
2365
+ switch (event.type) {
2366
+ case "runtime.connected":
2367
+ case "runtime.heartbeat":
2368
+ return true;
2369
+ case "message.updated":
2370
+ return event.message.sessionId === sessionId;
2371
+ case "question.asked":
2372
+ return event.question.sessionId === sessionId;
2373
+ case "session.error":
2374
+ return event.sessionId === undefined || event.sessionId === sessionId;
2375
+ default:
2376
+ return event.sessionId === sessionId;
2377
+ }
2378
+ }
2379
+ function normalizeAgent0QuestionRequest(value) {
2380
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.sessionID !== "string") {
2381
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question request");
2382
+ }
2383
+ if (!Array.isArray(value.questions)) {
2384
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned a question request without questions");
2385
+ }
2386
+ return {
2387
+ id: value.id,
2388
+ sessionId: value.sessionID,
2389
+ questions: value.questions.map(normalizeAgent0QuestionInfo),
2390
+ ...isRecord2(value.tool) && typeof value.tool.messageID === "string" && typeof value.tool.callID === "string" ? { tool: { messageId: value.tool.messageID, callId: value.tool.callID } } : {}
2391
+ };
2392
+ }
2393
+ function normalizeAgent0QuestionInfo(value) {
2394
+ if (!isRecord2(value) || typeof value.question !== "string" || typeof value.header !== "string" || !Array.isArray(value.options)) {
2395
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid question");
2396
+ }
2397
+ return {
2398
+ question: value.question,
2399
+ header: value.header,
2400
+ options: value.options.flatMap((option) => {
2401
+ if (!isRecord2(option) || typeof option.label !== "string")
2402
+ return [];
2403
+ return [
2404
+ {
2405
+ label: option.label,
2406
+ ...typeof option.description === "string" ? { description: option.description } : {}
2407
+ }
2408
+ ];
2409
+ }),
2410
+ ...typeof value.multiple === "boolean" ? { multiple: value.multiple } : {},
2411
+ ...typeof value.custom === "boolean" ? { custom: value.custom } : {}
2412
+ };
2413
+ }
2414
+ function normalizeQuestionAnswers(value) {
2415
+ return value.map((answer) => {
2416
+ if (!Array.isArray(answer) || answer.some((item) => typeof item !== "string")) {
2417
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned invalid question answers");
2418
+ }
2419
+ return [...answer];
2420
+ });
2421
+ }
2422
+ function listAgent0BuiltInCommands() {
2423
+ return Object.entries(loadAgent0BuiltInCommandConfig()).map(([name, command]) => ({
2424
+ name,
2425
+ ...command.description ? { description: command.description } : {},
2426
+ hints: extractAgent0CommandHints(command.template),
2427
+ ...typeof command.subtask === "boolean" ? { subtask: command.subtask } : {}
2428
+ })).toSorted((left, right) => left.name.localeCompare(right.name));
2429
+ }
2430
+ function getAgent0BuiltInCommand(name) {
2431
+ return loadAgent0BuiltInCommandConfig()[name];
2432
+ }
2433
+ function extractAgent0CommandHints(template) {
2434
+ const hints = new Set;
2435
+ for (const match of template.matchAll(/\$\d+/g)) {
2436
+ hints.add(match[0]);
2437
+ }
2438
+ if (template.includes("$ARGUMENTS")) {
2439
+ hints.add("$ARGUMENTS");
2440
+ }
2441
+ return [...hints].sort();
2442
+ }
2443
+ function renderAgent0CommandTemplate(template, args) {
2444
+ return template.replaceAll("$ARGUMENTS", args?.trim() ?? "");
2445
+ }
2446
+ function normalizeAgent0Session(value, projectPath) {
2447
+ if (!isRecord2(value) || typeof value.id !== "string" || typeof value.title !== "string") {
2448
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid session response");
2449
+ }
2450
+ if (!isRecord2(value.time)) {
2451
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned a session without valid timestamps");
2452
+ }
2453
+ const mode = normalizeAgent0SessionMode(value.agent);
2454
+ return {
2455
+ id: value.id,
2456
+ title: value.title,
2457
+ projectPath,
2458
+ ...typeof value.path === "string" ? { path: value.path } : {},
2459
+ ...typeof value.parentID === "string" ? { parentId: value.parentID } : {},
2460
+ ...mode ? { mode } : {},
2461
+ ...isRecord2(value.model) ? { model: normalizeAgent0SessionModel(value.model) } : {},
2462
+ createdAt: normalizeTimestamp(value.time.created),
2463
+ updatedAt: normalizeTimestamp(value.time.updated),
2464
+ ...value.time.archived === undefined || value.time.archived === null ? {} : { archivedAt: normalizeTimestamp(value.time.archived) }
2465
+ };
2466
+ }
2467
+ function normalizeAgent0SessionModel(value) {
2468
+ if (typeof value.providerID !== "string" || typeof value.id !== "string") {
2469
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid session model reference");
2470
+ }
2471
+ return {
2472
+ providerId: value.providerID,
2473
+ modelId: value.id,
2474
+ ...typeof value.variant === "string" ? { variant: value.variant } : {}
2475
+ };
2476
+ }
2477
+ function normalizeAgent0MessageInfo(info) {
2478
+ if (typeof info.id !== "string" || typeof info.sessionID !== "string" || info.role !== "user" && info.role !== "assistant" || !isRecord2(info.time)) {
2479
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid message info response");
2480
+ }
2481
+ const model = info.role === "user" ? isRecord2(info.model) ? normalizeAgent0MessageModel(info.model) : undefined : normalizeAgent0AssistantMessageModel(info);
2482
+ const usage = normalizeAgent0MessageUsage(info);
2483
+ const mode = normalizeAgent0SessionMode(info.agent);
2484
+ return {
2485
+ id: info.id,
2486
+ sessionId: info.sessionID,
2487
+ role: info.role,
2488
+ createdAt: normalizeTimestamp(info.time.created),
2489
+ completed: info.role === "user" || typeof info.time.completed === "number" || isRecord2(info.error),
2490
+ ...typeof info.time.completed === "number" ? { completedAt: normalizeTimestamp(info.time.completed) } : {},
2491
+ ...typeof info.parentID === "string" ? { parentId: info.parentID } : {},
2492
+ ...mode ? { mode } : {},
2493
+ ...model ? { model } : {},
2494
+ ...usage ? { usage } : {},
2495
+ ...isRecord2(info.error) ? { error: { message: normalizeErrorMessage(info.error) } } : {}
2496
+ };
2497
+ }
2498
+ function normalizeAgent0Message(value) {
2499
+ if (!isRecord2(value) || !isRecord2(value.info) || !Array.isArray(value.parts)) {
2500
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid message response");
2501
+ }
2502
+ const info = normalizeAgent0MessageInfo(value.info);
2503
+ const parts = value.parts.flatMap(normalizeAgent0MessagePart);
2504
+ return {
2505
+ ...info,
2506
+ parts
2507
+ };
2508
+ }
2509
+ function normalizeAgent0MessageModel(value) {
2510
+ if (typeof value.providerID !== "string" || typeof value.modelID !== "string") {
2511
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid message model reference");
2512
+ }
2513
+ return {
2514
+ providerId: value.providerID,
2515
+ modelId: value.modelID,
2516
+ ...typeof value.variant === "string" ? { variant: value.variant } : {}
2517
+ };
2518
+ }
2519
+ function normalizeAgent0AssistantMessageModel(value) {
2520
+ if (typeof value.providerID !== "string" || typeof value.modelID !== "string")
2521
+ return;
2522
+ return {
2523
+ providerId: value.providerID,
2524
+ modelId: value.modelID,
2525
+ ...typeof value.variant === "string" ? { variant: value.variant } : {}
2526
+ };
2527
+ }
2528
+ function normalizeAgent0SessionMode(value) {
2529
+ return value === "default" || value === "guided" ? value : undefined;
2530
+ }
2531
+ function normalizeAgent0SessionStatus(value) {
2532
+ if (!isRecord2(value))
2533
+ return;
2534
+ if (value.type === "idle" || value.type === "busy")
2535
+ return { type: value.type };
2536
+ if (value.type !== "retry" || typeof value.attempt !== "number" || !Number.isFinite(value.attempt) || typeof value.message !== "string" || typeof value.next !== "number" || !Number.isFinite(value.next)) {
2537
+ return;
2538
+ }
2539
+ return {
2540
+ type: "retry",
2541
+ attempt: value.attempt,
2542
+ message: value.message,
2543
+ next: value.next,
2544
+ ...isRecord2(value.action) && typeof value.action.reason === "string" && typeof value.action.provider === "string" && typeof value.action.title === "string" && typeof value.action.message === "string" && typeof value.action.label === "string" ? {
2545
+ action: {
2546
+ reason: value.action.reason,
2547
+ provider: value.action.provider,
2548
+ title: value.action.title,
2549
+ message: value.action.message,
2550
+ label: value.action.label,
2551
+ ...typeof value.action.link === "string" ? { link: value.action.link } : {}
2552
+ }
2553
+ } : {}
2554
+ };
2555
+ }
2556
+ function normalizeAgent0MessagePart(part) {
2557
+ if (!isRecord2(part) || typeof part.id !== "string" || typeof part.type !== "string")
2558
+ return [];
2559
+ switch (part.type) {
2560
+ case "text":
2561
+ return [
2562
+ {
2563
+ id: part.id,
2564
+ type: "text",
2565
+ ...typeof part.text === "string" ? { text: part.text } : {},
2566
+ ...part.synthetic === true ? { synthetic: true } : {},
2567
+ ...part.ignored === true ? { ignored: true } : {},
2568
+ ...isRecord2(part.metadata) ? { metadata: part.metadata } : {},
2569
+ ...normalizeAgent0PartTime(part.time) ? { time: normalizeAgent0PartTime(part.time) } : {}
2570
+ }
2571
+ ];
2572
+ case "agent":
2573
+ return [
2574
+ {
2575
+ id: part.id,
2576
+ type: "agent",
2577
+ title: typeof part.name === "string" ? part.name : "Agent",
2578
+ ...typeof part.name === "string" ? { name: part.name } : {},
2579
+ ...normalizePartSource(part.source) ? { source: normalizePartSource(part.source) } : {}
2580
+ }
2581
+ ];
2582
+ case "compaction":
2583
+ return [
2584
+ {
2585
+ id: part.id,
2586
+ type: "compaction",
2587
+ title: "Compaction",
2588
+ status: "completed",
2589
+ ...part.auto === true || part.auto === false ? { auto: part.auto } : {},
2590
+ ...part.overflow === true || part.overflow === false ? { overflow: part.overflow } : {},
2591
+ ...typeof part.tail_start_id === "string" ? { tailStartId: part.tail_start_id } : {}
2592
+ }
2593
+ ];
2594
+ case "file":
2595
+ return [
2596
+ {
2597
+ id: part.id,
2598
+ type: "file",
2599
+ title: typeof part.filename === "string" ? part.filename : "File",
2600
+ ...typeof part.filename === "string" ? { filename: part.filename } : {},
2601
+ ...typeof part.mime === "string" ? { mime: part.mime } : {},
2602
+ ...typeof part.url === "string" ? { url: part.url } : {},
2603
+ ...normalizePartSource(part.source) ? { source: normalizePartSource(part.source) } : {}
2604
+ }
2605
+ ];
2606
+ case "patch":
2607
+ return [
2608
+ {
2609
+ id: part.id,
2610
+ type: "patch",
2611
+ title: "Patch",
2612
+ status: "completed",
2613
+ ...typeof part.hash === "string" ? { hash: part.hash } : {},
2614
+ ...Array.isArray(part.files) ? { files: part.files.filter((file) => typeof file === "string") } : {}
2615
+ }
2616
+ ];
2617
+ case "reasoning":
2618
+ return [
2619
+ {
2620
+ id: part.id,
2621
+ type: "reasoning",
2622
+ title: "Reasoning",
2623
+ status: normalizeTimedPartStatus(part.time),
2624
+ ...typeof part.text === "string" ? { text: part.text } : {},
2625
+ ...isRecord2(part.metadata) ? { metadata: part.metadata } : {},
2626
+ ...normalizeAgent0PartTime(part.time) ? { time: normalizeAgent0PartTime(part.time) } : {}
2627
+ }
2628
+ ];
2629
+ case "retry":
2630
+ return [
2631
+ {
2632
+ id: part.id,
2633
+ type: "retry",
2634
+ title: "Retry",
2635
+ status: "error",
2636
+ ...typeof part.attempt === "number" && Number.isFinite(part.attempt) ? { attempt: part.attempt } : {},
2637
+ ...normalizeAgent0PartTime(part.time) ? { time: normalizeAgent0PartTime(part.time) } : {},
2638
+ ...isRecord2(part.error) ? { error: { message: normalizeErrorMessage(part.error) } } : {}
2639
+ }
2640
+ ];
2641
+ case "snapshot":
2642
+ return [
2643
+ {
2644
+ id: part.id,
2645
+ type: "snapshot",
2646
+ title: "Snapshot",
2647
+ status: "completed",
2648
+ ...typeof part.snapshot === "string" ? { text: part.snapshot } : {}
2649
+ }
2650
+ ];
2651
+ case "step-start":
2652
+ return [
2653
+ {
2654
+ id: part.id,
2655
+ type: "step-start",
2656
+ title: "Step started",
2657
+ status: "running",
2658
+ ...typeof part.snapshot === "string" ? { text: part.snapshot } : {}
2659
+ }
2660
+ ];
2661
+ case "step-finish":
2662
+ return [
2663
+ {
2664
+ id: part.id,
2665
+ type: "step-finish",
2666
+ title: "Step finished",
2667
+ status: "completed",
2668
+ ...typeof part.reason === "string" ? { reason: part.reason } : {},
2669
+ ...typeof part.snapshot === "string" ? { hash: part.snapshot } : {},
2670
+ ...normalizeAgent0MessageUsage(part) ? { usage: normalizeAgent0MessageUsage(part) } : {}
2671
+ }
2672
+ ];
2673
+ case "subtask":
2674
+ return [
2675
+ {
2676
+ id: part.id,
2677
+ type: "subtask",
2678
+ title: typeof part.description === "string" ? part.description : "Subtask",
2679
+ ...typeof part.description === "string" ? { description: part.description } : {},
2680
+ ...typeof part.prompt === "string" ? { prompt: part.prompt } : {},
2681
+ ...typeof part.agent === "string" ? { agent: part.agent } : {},
2682
+ ...typeof part.command === "string" ? { command: part.command } : {},
2683
+ ...isRecord2(part.model) ? { model: normalizeAgent0MessageModel(part.model) } : {}
2684
+ }
2685
+ ];
2686
+ case "tool":
2687
+ return normalizeAgent0ToolPart(part);
2688
+ default:
2689
+ return [];
2690
+ }
2691
+ }
2692
+ function normalizeAgent0ToolPart(part) {
2693
+ if (!isRecord2(part.state))
2694
+ return [];
2695
+ const status = normalizeToolStatus(part.state.status);
2696
+ const state = {
2697
+ ...status ? { status } : { status: "pending" },
2698
+ ...isRecord2(part.state.input) ? { input: part.state.input } : {},
2699
+ ...typeof part.state.raw === "string" ? { raw: part.state.raw } : {},
2700
+ ...typeof part.state.title === "string" ? { title: part.state.title } : {},
2701
+ ...isRecord2(part.state.metadata) ? { metadata: part.state.metadata } : {},
2702
+ ..."output" in part.state ? { output: part.state.output } : {},
2703
+ ...Array.isArray(part.state.attachments) ? { attachments: normalizeAgent0MessageAttachments(part.state.attachments) } : {},
2704
+ ...typeof part.state.error === "string" ? { error: part.state.error } : {},
2705
+ ...normalizeAgent0PartTime(part.state.time) ? { time: normalizeAgent0PartTime(part.state.time) } : {}
2706
+ };
2707
+ return [
2708
+ {
2709
+ id: part.id,
2710
+ type: "tool",
2711
+ title: typeof part.state.title === "string" ? part.state.title : typeof part.tool === "string" ? part.tool : "Tool",
2712
+ ...typeof part.tool === "string" ? { toolId: part.tool } : {},
2713
+ ...typeof part.callID === "string" ? { callId: part.callID } : {},
2714
+ ...status ? { status } : {},
2715
+ ...isRecord2(part.state.input) ? { input: part.state.input } : {},
2716
+ ..."output" in part.state ? { output: part.state.output } : {},
2717
+ ...Array.isArray(part.state.attachments) ? { attachments: normalizeAgent0MessageAttachments(part.state.attachments) } : {},
2718
+ ...typeof part.state.error === "string" ? { error: { message: part.state.error } } : {},
2719
+ state,
2720
+ ...isRecord2(part.metadata) ? { metadata: part.metadata } : {}
2721
+ }
2722
+ ];
2723
+ }
2724
+ function normalizeAgent0MessageAttachments(value) {
2725
+ return value.flatMap((attachment) => {
2726
+ if (!isRecord2(attachment) || typeof attachment.mime !== "string" || typeof attachment.url !== "string")
2727
+ return [];
2728
+ return [
2729
+ {
2730
+ mime: attachment.mime,
2731
+ url: attachment.url,
2732
+ ...typeof attachment.filename === "string" ? { filename: attachment.filename } : {}
2733
+ }
2734
+ ];
2735
+ });
2736
+ }
2737
+ function normalizeToolStatus(value) {
2738
+ if (value === "pending" || value === "running" || value === "completed" || value === "error")
2739
+ return value;
2740
+ return;
2741
+ }
2742
+ function normalizeAgent0PartTime(value) {
2743
+ if (!isRecord2(value))
2744
+ return;
2745
+ const time = {
2746
+ ...typeof value.created === "number" && Number.isFinite(value.created) ? { createdAt: normalizeTimestamp(value.created) } : {},
2747
+ ...typeof value.start === "number" && Number.isFinite(value.start) ? { startedAt: normalizeTimestamp(value.start) } : {},
2748
+ ...typeof value.end === "number" && Number.isFinite(value.end) ? { endedAt: normalizeTimestamp(value.end) } : {}
2749
+ };
2750
+ return Object.keys(time).length > 0 ? time : undefined;
2751
+ }
2752
+ function normalizeTimedPartStatus(value) {
2753
+ if (!isRecord2(value))
2754
+ return;
2755
+ return typeof value.end === "number" ? "completed" : "running";
2756
+ }
2757
+ function normalizePartSource(value) {
2758
+ if (!isRecord2(value) || value.type !== "file" && value.type !== "resource" && value.type !== "symbol")
2759
+ return;
2760
+ const type = value.type;
2761
+ return {
2762
+ type,
2763
+ ...typeof value.path === "string" ? { path: value.path } : {},
2764
+ ...typeof value.uri === "string" ? { uri: value.uri } : {},
2765
+ ...typeof value.name === "string" ? { name: value.name } : {},
2766
+ ...isRecord2(value.text) && typeof value.text.value === "string" && typeof value.text.start === "number" && typeof value.text.end === "number" ? { text: { value: value.text.value, start: value.text.start, end: value.text.end } } : {}
2767
+ };
2768
+ }
2769
+ function normalizeErrorMessage(value) {
2770
+ return typeof value.message === "string" && value.message.trim().length > 0 ? value.message : "Agent(0) message failed.";
2771
+ }
2772
+ function normalizeAgent0MessageUsage(value) {
2773
+ const usage = {};
2774
+ if (typeof value.cost === "number" && Number.isFinite(value.cost))
2775
+ usage.estimatedCost = value.cost;
2776
+ if (isRecord2(value.tokens)) {
2777
+ if (typeof value.tokens.total === "number" && Number.isFinite(value.tokens.total))
2778
+ usage.totalTokens = value.tokens.total;
2779
+ if (typeof value.tokens.input === "number" && Number.isFinite(value.tokens.input))
2780
+ usage.inputTokens = value.tokens.input;
2781
+ if (typeof value.tokens.output === "number" && Number.isFinite(value.tokens.output))
2782
+ usage.outputTokens = value.tokens.output;
2783
+ if (typeof value.tokens.reasoning === "number" && Number.isFinite(value.tokens.reasoning)) {
2784
+ usage.reasoningTokens = value.tokens.reasoning;
2785
+ }
2786
+ if (isRecord2(value.tokens.cache)) {
2787
+ if (typeof value.tokens.cache.read === "number" && Number.isFinite(value.tokens.cache.read)) {
2788
+ usage.cacheReadTokens = value.tokens.cache.read;
2789
+ }
2790
+ if (typeof value.tokens.cache.write === "number" && Number.isFinite(value.tokens.cache.write)) {
2791
+ usage.cacheWriteTokens = value.tokens.cache.write;
2792
+ }
2793
+ }
2794
+ }
2795
+ return Object.keys(usage).length > 0 ? usage : undefined;
2796
+ }
2797
+ function normalizeTimestamp(value) {
2798
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2799
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid session timestamp");
2800
+ }
2801
+ return new Date(value).toISOString();
2802
+ }
2803
+ function toOpenCodePromptInput(input) {
2804
+ return {
2805
+ parts: input.parts.map(toOpenCodePromptPart),
2806
+ ...input.mode === undefined ? {} : { agent: input.mode },
2807
+ ...input.generateReply === false ? { noReply: true } : {},
2808
+ ...input.model === undefined ? {} : {
2809
+ model: {
2810
+ providerID: input.model.providerId,
2811
+ modelID: input.model.modelId
2812
+ },
2813
+ ...input.model.variant === undefined ? {} : { variant: input.model.variant }
2814
+ }
2815
+ };
2816
+ }
2817
+ function toOpenCodePromptPart(part) {
2818
+ if (part.type !== "file")
2819
+ return part;
2820
+ if (part.mime === "text/plain")
2821
+ return part;
2822
+ if (!isTextReadablePromptFile(part))
2823
+ return part;
2824
+ return {
2825
+ ...part,
2826
+ mime: "text/plain",
2827
+ url: rewriteDataUrlMime(part.url, "text/plain")
2828
+ };
2829
+ }
2830
+ function isTextReadablePromptFile(part) {
2831
+ if (part.mime.startsWith("text/"))
2832
+ return true;
2833
+ const normalizedMime = part.mime.toLowerCase().split(";")[0]?.trim() ?? "";
2834
+ if ([
2835
+ "application/json",
2836
+ "application/ld+json",
2837
+ "application/javascript",
2838
+ "application/typescript",
2839
+ "application/xml",
2840
+ "application/yaml",
2841
+ "application/x-yaml",
2842
+ "application/toml",
2843
+ "application/x-ndjson",
2844
+ "image/svg+xml"
2845
+ ].includes(normalizedMime)) {
2846
+ return true;
2847
+ }
2848
+ const filename = part.filename?.toLowerCase();
2849
+ if (!filename)
2850
+ return false;
2851
+ return [
2852
+ ".c",
2853
+ ".conf",
2854
+ ".cpp",
2855
+ ".css",
2856
+ ".csv",
2857
+ ".env",
2858
+ ".go",
2859
+ ".graphql",
2860
+ ".h",
2861
+ ".html",
2862
+ ".java",
2863
+ ".js",
2864
+ ".json",
2865
+ ".jsx",
2866
+ ".kt",
2867
+ ".log",
2868
+ ".md",
2869
+ ".mdx",
2870
+ ".py",
2871
+ ".rs",
2872
+ ".scss",
2873
+ ".sh",
2874
+ ".sql",
2875
+ ".toml",
2876
+ ".ts",
2877
+ ".tsx",
2878
+ ".txt",
2879
+ ".xml",
2880
+ ".yaml",
2881
+ ".yml"
2882
+ ].some((extension) => filename.endsWith(extension));
2883
+ }
2884
+ function rewriteDataUrlMime(url, mime) {
2885
+ if (!url.startsWith("data:"))
2886
+ return url;
2887
+ const comma = url.indexOf(",");
2888
+ if (comma === -1)
2889
+ return url;
2890
+ const metadata = url.slice("data:".length, comma);
2891
+ const parameters = metadata.split(";").slice(1).filter((parameter) => parameter.length > 0);
2892
+ return `data:${mime}${parameters.map((parameter) => `;${parameter}`).join("")}${url.slice(comma)}`;
2893
+ }
2894
+ function toOpenCodeCreateSessionInput(input) {
2895
+ return {
2896
+ ...input.title === undefined ? {} : { title: input.title },
2897
+ ...input.mode === undefined ? {} : { agent: input.mode },
2898
+ ...input.model === undefined ? {} : {
2899
+ model: {
2900
+ providerID: input.model.providerId,
2901
+ id: input.model.modelId,
2902
+ ...input.model.variant === undefined ? {} : { variant: input.model.variant }
2903
+ }
2904
+ }
2905
+ };
2906
+ }
2907
+ function normalizeAgent0RuntimeStatus(value, projectPath) {
2908
+ if (!isRecord2(value) || typeof value.directory !== "string" || typeof value.worktree !== "string") {
2909
+ throw new Agent0RuntimeClientError("ENGINE_INVALID_RESPONSE", "Agent(0) private runtime returned an invalid path response");
2910
+ }
2911
+ return {
2912
+ state: "running",
2913
+ projectPath,
2914
+ worktreePath: value.worktree
2915
+ };
2916
+ }
2917
+ function isRecord2(value) {
2918
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2919
+ }
2920
+ // src/agent0/runtime/manager.ts
2921
+ class Agent0RuntimeManagerError extends Error {
2922
+ code;
2923
+ cause;
2924
+ constructor(code, message, options = {}) {
2925
+ super(message);
2926
+ this.name = "Agent0RuntimeManagerError";
2927
+ this.code = code;
2928
+ this.cause = options.cause;
2929
+ }
2930
+ }
2931
+
2932
+ class Agent0RuntimeManager {
2933
+ options;
2934
+ state = "stopped";
2935
+ client;
2936
+ operation = Promise.resolve();
2937
+ engineGeneration = 0;
2938
+ configVersion;
2939
+ warnings = [];
2940
+ lastError;
2941
+ constructor(options) {
2942
+ this.options = {
2943
+ ...options,
2944
+ configStore: options.configStore ?? new Agent0ConfigStore,
2945
+ resolveProjectDirs: options.resolveProjectDirs ?? ensureAgent0ProjectDirs,
2946
+ startRuntimeClient: options.startRuntimeClient ?? startAgent0RuntimeClient
2947
+ };
2948
+ }
2949
+ async start() {
2950
+ return this.enqueue(async () => {
2951
+ if (this.client)
2952
+ return this;
2953
+ await this.startUnlocked("starting");
2954
+ return this;
2955
+ });
2956
+ }
2957
+ async restart() {
2958
+ return this.enqueue(async () => {
2959
+ await this.stopUnlocked("restarting");
2960
+ await this.startUnlocked("restarting");
2961
+ return this;
2962
+ });
2963
+ }
2964
+ async invalidate() {
2965
+ await this.enqueue(async () => {
2966
+ if (this.state === "stopped")
2967
+ return;
2968
+ await this.stopUnlocked("restarting");
2969
+ await this.startUnlocked("restarting");
2970
+ });
2971
+ }
2972
+ async stop() {
2973
+ await this.enqueue(async () => {
2974
+ await this.stopUnlocked("stopping");
2975
+ });
2976
+ }
2977
+ async getStatus() {
2978
+ const client = this.client;
2979
+ if (!client) {
2980
+ throw this.toNotRunningError();
2981
+ }
2982
+ return client.getStatus();
2983
+ }
2984
+ async listSessions() {
2985
+ const client = this.client;
2986
+ if (!client) {
2987
+ throw this.toNotRunningError();
2988
+ }
2989
+ return client.listSessions();
2990
+ }
2991
+ async createSession(input) {
2992
+ const client = this.client;
2993
+ if (!client) {
2994
+ throw this.toNotRunningError();
2995
+ }
2996
+ return client.createSession(input);
2997
+ }
2998
+ async listMessages(sessionId) {
2999
+ const client = this.client;
3000
+ if (!client) {
3001
+ throw this.toNotRunningError();
3002
+ }
3003
+ return client.listMessages(sessionId);
3004
+ }
3005
+ async sendMessage(sessionId, input) {
3006
+ const client = this.client;
3007
+ if (!client) {
3008
+ throw this.toNotRunningError();
3009
+ }
3010
+ return client.sendMessage(sessionId, input);
3011
+ }
3012
+ async abortSession(sessionId) {
3013
+ const client = this.client;
3014
+ if (!client) {
3015
+ throw this.toNotRunningError();
3016
+ }
3017
+ return client.abortSession(sessionId);
3018
+ }
3019
+ async listQuestions(sessionId) {
3020
+ const client = this.client;
3021
+ if (!client) {
3022
+ throw this.toNotRunningError();
3023
+ }
3024
+ return client.listQuestions(sessionId);
3025
+ }
3026
+ async replyQuestion(sessionId, questionId, input) {
3027
+ const client = this.client;
3028
+ if (!client) {
3029
+ throw this.toNotRunningError();
3030
+ }
3031
+ return client.replyQuestion(sessionId, questionId, input);
3032
+ }
3033
+ async rejectQuestion(sessionId, questionId) {
3034
+ const client = this.client;
3035
+ if (!client) {
3036
+ throw this.toNotRunningError();
3037
+ }
3038
+ return client.rejectQuestion(sessionId, questionId);
3039
+ }
3040
+ async listCommands() {
3041
+ const client = this.client;
3042
+ if (!client) {
3043
+ throw this.toNotRunningError();
3044
+ }
3045
+ return client.listCommands();
3046
+ }
3047
+ async runCommand(sessionId, input) {
3048
+ const client = this.client;
3049
+ if (!client) {
3050
+ throw this.toNotRunningError();
3051
+ }
3052
+ return client.runCommand(sessionId, input);
3053
+ }
3054
+ streamEvents(options) {
3055
+ const client = this.client;
3056
+ if (!client?.streamEvents) {
3057
+ throw this.toNotRunningError();
3058
+ }
3059
+ return client.streamEvents(options);
3060
+ }
3061
+ getSnapshot() {
3062
+ return {
3063
+ state: this.state,
3064
+ engineGeneration: this.engineGeneration,
3065
+ configVersion: this.configVersion,
3066
+ warnings: this.cloneWarnings(),
3067
+ ...this.lastError ? { error: stringifyError(this.lastError) } : {}
3068
+ };
3069
+ }
3070
+ async startUnlocked(state) {
3071
+ this.state = state;
3072
+ this.lastError = undefined;
3073
+ try {
3074
+ const [paths2, agent0Config, cognitiveModelResult] = await Promise.all([
3075
+ this.options.resolveProjectDirs(this.options.agentPath),
3076
+ this.options.configStore.read(),
3077
+ this.resolveCognitiveModels()
3078
+ ]);
3079
+ const client = await this.options.startRuntimeClient({
3080
+ paths: paths2,
3081
+ agentPath: this.options.agentPath,
3082
+ adkDevConsolePort: this.options.adkDevConsolePort,
3083
+ agent0Config,
3084
+ cognitiveModels: cognitiveModelResult.models.length > 0 ? cognitiveModelResult.models : undefined,
3085
+ startupTimeoutMs: this.options.startupTimeoutMs,
3086
+ onLog: this.options.onLog
3087
+ });
3088
+ this.client = client;
3089
+ this.engineGeneration += 1;
3090
+ this.configVersion = agent0Config.updatedAt;
3091
+ this.warnings = cognitiveModelResult.warnings;
3092
+ this.state = "running";
3093
+ } catch (error) {
3094
+ this.client = undefined;
3095
+ this.lastError = error;
3096
+ this.state = "unavailable";
3097
+ throw new Agent0RuntimeManagerError("RUNTIME_START_FAILED", `Agent(0) runtime failed to start: ${stringifyError(error)}`, { cause: error });
3098
+ }
3099
+ }
3100
+ async stopUnlocked(state) {
3101
+ const client = this.client;
3102
+ this.client = undefined;
3103
+ this.state = state;
3104
+ try {
3105
+ await client?.stop();
3106
+ } finally {
3107
+ this.state = "stopped";
3108
+ }
3109
+ }
3110
+ async resolveCognitiveModels() {
3111
+ const source2 = this.options.cognitiveSource;
3112
+ if (!source2)
3113
+ return { models: [], warnings: [] };
3114
+ const result = await source2.listModelsWithStatus();
3115
+ for (const warning of result.warnings) {
3116
+ this.options.onLog?.(`${warning.source}: ${warning.message}`);
3117
+ }
3118
+ return {
3119
+ models: result.models,
3120
+ warnings: result.warnings
3121
+ };
3122
+ }
3123
+ enqueue(operation) {
3124
+ const next = this.operation.then(operation, operation);
3125
+ this.operation = next.then(() => {
3126
+ return;
3127
+ }, () => {
3128
+ return;
3129
+ });
3130
+ return next;
3131
+ }
3132
+ toNotRunningError() {
3133
+ if (this.state === "unavailable" && this.lastError) {
3134
+ return new Agent0RuntimeManagerError("RUNTIME_NOT_RUNNING", "Agent(0) runtime is unavailable", {
3135
+ cause: this.lastError
3136
+ });
3137
+ }
3138
+ return new Agent0RuntimeManagerError("RUNTIME_NOT_RUNNING", "Agent(0) runtime is not running");
3139
+ }
3140
+ cloneWarnings() {
3141
+ return this.warnings.map((warning) => ({ ...warning }));
3142
+ }
3143
+ }
3144
+ function stringifyError(error) {
3145
+ return error instanceof Error ? error.message : String(error);
3146
+ }
3147
+ export {
3148
+ toAgent0AvailableModel,
3149
+ stopAgent0OpenCodeProcess,
3150
+ startAgent0RuntimeClient,
3151
+ startAgent0OpenCodeProcess,
3152
+ sanitizeAgent0OpenCodeBaseEnv,
3153
+ resolveAgent0OpenCodeBinary,
3154
+ resolveAgent0BuiltInSkillsRootCandidates,
3155
+ resolveAgent0BuiltInSkillsRoot,
3156
+ resolveAgent0BuiltInSkillPaths,
3157
+ resolveAgent0BuiltInInstructionFiles,
3158
+ resolveAgent0BuiltInCommandsRootCandidates,
3159
+ resolveAgent0BuiltInCommandsRoot,
3160
+ requireAgent0ProviderCatalogEntry,
3161
+ renderAgent0OpenCodeRuntime,
3162
+ redactAgent0Config,
3163
+ prepareAgent0OpenCodeRuntime,
3164
+ parseAgent0Config,
3165
+ mapModelsDevCatalog,
3166
+ loadAgent0BuiltInCommandConfig,
3167
+ listAgent0ProviderCatalog,
3168
+ hasAgent0ProviderAuth,
3169
+ getAgent0ProviderCatalogEntry,
3170
+ getAgent0ProjectPaths,
3171
+ getAgent0ProjectHash,
3172
+ getAgent0ProjectDiscoveryGitShimFilename,
3173
+ getAgent0HomeDir,
3174
+ getAgent0ConfigPath,
3175
+ ensureAgent0ProjectDiscoveryGitShim,
3176
+ ensureAgent0ProjectDirs,
3177
+ ensureAgent0Directory,
3178
+ createDefaultAgent0Config,
3179
+ createAgent0RuntimeClient,
3180
+ createAgent0DefaultProviderCatalogSource,
3181
+ canonicalizeAgent0ProjectPath,
3182
+ buildAgent0OpenCodeProcessEnv,
3183
+ buildAgent0OpenCodePermissionConfig,
3184
+ buildAgent0OpenCodeEnv,
3185
+ buildAgent0OpenCodeConfig,
3186
+ buildAgent0OpenCodeAuthHeaders,
3187
+ buildAgent0OpenCodeAuthContent,
3188
+ buildAgent0CognitiveProvider,
3189
+ buildAgent0BuiltInCapabilities,
3190
+ agent0ProviderConnectionSchema,
3191
+ agent0ProviderAuthSchema,
3192
+ agent0ConfigSchema,
3193
+ agent0ConfigPreferencesSchema,
3194
+ DEFAULT_AGENT0_PREFERENCES,
3195
+ Agent0RuntimeManagerError,
3196
+ Agent0RuntimeManager,
3197
+ Agent0RuntimeClientError,
3198
+ Agent0ProviderRegistry,
3199
+ Agent0ProviderCatalogSourceError,
3200
+ Agent0ModelsDevCatalogSource,
3201
+ Agent0ConfigStore,
3202
+ Agent0ConfigError,
3203
+ Agent0CompositeProviderCatalogSource,
3204
+ Agent0CognitiveCatalogSource,
3205
+ AGENT0_SESSION_MODES,
3206
+ AGENT0_SCREENSHOT_RAW_TOOL_PERMISSION,
3207
+ AGENT0_SCREENSHOT_MCP_TOOL_PERMISSION,
3208
+ AGENT0_PROVIDER_CATALOG,
3209
+ AGENT0_PROJECT_ID_CACHE_GUARD_ENV,
3210
+ AGENT0_HIDDEN_OPENCODE_SKILL,
3211
+ AGENT0_CONFIG_SCHEMA_VERSION,
3212
+ AGENT0_BUILT_IN_MCP_PERMISSION
3213
+ };
3214
+
3215
+ //# debugId=1EFA6274C1909E3064756E2164756E21