@botpress/adk 1.18.3 → 1.19.0-beta.10

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