eve 0.54.5 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/src/channel/adapter.d.ts +3 -2
  3. package/dist/src/channel/audience.d.ts +16 -0
  4. package/dist/src/channel/audience.js +1 -0
  5. package/dist/src/channel/conversation-context.d.ts +5 -0
  6. package/dist/src/channel/conversation-context.js +1 -0
  7. package/dist/src/channel/instrumentation.js +1 -1
  8. package/dist/src/channel/types.d.ts +9 -0
  9. package/dist/src/chunks/{use-eve-agent-CxPlg0KL.js → use-eve-agent-CMdMlS7Y.js} +0 -10
  10. package/dist/src/chunks/{use-eve-agent-D-KQzzyW.js → use-eve-agent-RUGSwq8b.js} +0 -10
  11. package/dist/src/cli/commands/agent-prompt/scaffold.md +5 -4
  12. package/dist/src/cli/commands/init-target.js +2 -2
  13. package/dist/src/cli/commands/init.js +1 -1
  14. package/dist/src/cli/commands/registry-metadata.d.ts +0 -18
  15. package/dist/src/cli/commands/registry-metadata.js +1 -1
  16. package/dist/src/cli/commands/registry-pnpm-build-policy-flow.js +1 -1
  17. package/dist/src/cli/commands/registry.js +1 -1
  18. package/dist/src/cli/dev/environment.js +1 -1
  19. package/dist/src/cli/dev/tui/blocks.d.ts +2 -0
  20. package/dist/src/cli/dev/tui/blocks.js +3 -3
  21. package/dist/src/cli/dev/tui/markdown.d.ts +8 -1
  22. package/dist/src/cli/dev/tui/markdown.js +7 -7
  23. package/dist/src/cli/dev/tui/runner.d.ts +4 -1
  24. package/dist/src/cli/dev/tui/runner.js +1 -1
  25. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +5 -1
  26. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  27. package/dist/src/cli/dev/tui/tui.d.ts +4 -1
  28. package/dist/src/cli/ui/terminal-text.js +1 -1
  29. package/dist/src/client/agent-info-schema.d.ts +0 -57
  30. package/dist/src/client/agent-info-schema.js +1 -1
  31. package/dist/src/compiled/.vendor-stamp.json +1 -1
  32. package/dist/src/compiler/extension-compatibility.d.ts +26 -16
  33. package/dist/src/compiler/extension-compatibility.js +1 -1
  34. package/dist/src/compiler/manifest.d.ts +12 -11
  35. package/dist/src/compiler/manifest.js +1 -1
  36. package/dist/src/compiler/normalize-manifest.js +1 -1
  37. package/dist/src/compiler/normalize-tool.d.ts +0 -3
  38. package/dist/src/compiler/normalize-tool.js +1 -1
  39. package/dist/src/compiler/validate-artifact.js +1 -1
  40. package/dist/src/context/dynamic-resolve-context.js +1 -1
  41. package/dist/src/context/keys.d.ts +2 -0
  42. package/dist/src/context/keys.js +1 -1
  43. package/dist/src/discover/filesystem.d.ts +3 -1
  44. package/dist/src/discover/filesystem.js +1 -1
  45. package/dist/src/discover/skills.js +1 -1
  46. package/dist/src/dynamic/definition.d.ts +6 -0
  47. package/dist/src/eve-channel/audience.d.ts +3 -0
  48. package/dist/src/eve-channel/audience.js +1 -0
  49. package/dist/src/eve-channel/index.js +1 -1
  50. package/dist/src/eve-channel/types.d.ts +14 -1
  51. package/dist/src/execution/activity-work.d.ts +2 -0
  52. package/dist/src/execution/activity-work.js +1 -1
  53. package/dist/src/execution/channel-context.js +1 -1
  54. package/dist/src/execution/coordination-dispatch-shared.d.ts +1 -0
  55. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  56. package/dist/src/execution/coordination-dispatch-step.d.ts +2 -2
  57. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  58. package/dist/src/execution/create-session-step.js +1 -1
  59. package/dist/src/execution/durable-session-store.d.ts +0 -1
  60. package/dist/src/execution/dynamic-workflow/program-step.d.ts +21 -0
  61. package/dist/src/execution/dynamic-workflow/program-step.js +1 -0
  62. package/dist/src/execution/dynamic-workflow/schema.d.ts +36 -0
  63. package/dist/src/execution/dynamic-workflow/schema.js +1 -0
  64. package/dist/src/execution/dynamic-workflow/security-step.d.ts +3 -0
  65. package/dist/src/execution/dynamic-workflow/security-step.js +1 -0
  66. package/dist/src/execution/dynamic-workflow/tool.d.ts +8 -0
  67. package/dist/src/execution/dynamic-workflow/tool.js +1 -0
  68. package/dist/src/execution/dynamic-workflow/workflow.d.ts +10 -0
  69. package/dist/src/execution/dynamic-workflow/workflow.js +1 -0
  70. package/dist/src/execution/eve-workflow-attributes.d.ts +2 -1
  71. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  72. package/dist/src/execution/inline-turn.js +1 -1
  73. package/dist/src/execution/model-call-batching.js +1 -1
  74. package/dist/src/execution/next-driver-action.d.ts +0 -8
  75. package/dist/src/execution/node-step.d.ts +0 -5
  76. package/dist/src/execution/node-step.js +1 -1
  77. package/dist/src/execution/runtime-context.js +1 -1
  78. package/dist/src/execution/scheduled-launch-delivery.d.ts +7 -0
  79. package/dist/src/execution/scheduled-launch-delivery.js +1 -0
  80. package/dist/src/execution/session-activity.js +1 -1
  81. package/dist/src/execution/session.d.ts +0 -1
  82. package/dist/src/execution/session.js +2 -2
  83. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  84. package/dist/src/execution/tasks/child/steps.js +1 -1
  85. package/dist/src/execution/tasks/parent/delegate.d.ts +9 -0
  86. package/dist/src/execution/tasks/parent/delegate.js +1 -1
  87. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  88. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  89. package/dist/src/execution/tools/subagent/invoke-step.d.ts +4 -0
  90. package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
  91. package/dist/src/execution/tools/subagent/start.d.ts +5 -0
  92. package/dist/src/execution/tools/subagent/start.js +1 -1
  93. package/dist/src/execution/turn-workflow.js +1 -1
  94. package/dist/src/execution/wire/session-inbox-contract.d.ts +2 -2
  95. package/dist/src/execution/wire/session-inbox-contract.js +1 -1
  96. package/dist/src/execution/wire/session-inbox-encoder.d.ts +6 -2
  97. package/dist/src/execution/wire/session-inbox-encoder.js +1 -1
  98. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  99. package/dist/src/execution/wire/session-inbox-wire.js +1 -1
  100. package/dist/src/execution/wire/session-inbox-wire.v7.d.ts +342 -0
  101. package/dist/src/execution/wire/session-inbox-wire.v7.js +1 -0
  102. package/dist/src/execution/workflow-runtime.js +1 -1
  103. package/dist/src/execution/workflow-steps.js +1 -1
  104. package/dist/src/harness/action-presentation.d.ts +5 -0
  105. package/dist/src/harness/action-presentation.js +1 -1
  106. package/dist/src/harness/advertised-tools.d.ts +0 -3
  107. package/dist/src/harness/advertised-tools.js +1 -1
  108. package/dist/src/harness/background-tools.d.ts +3 -1
  109. package/dist/src/harness/emission.js +1 -1
  110. package/dist/src/harness/step-hooks.js +1 -1
  111. package/dist/src/harness/tool-loop.js +2 -2
  112. package/dist/src/harness/tools.js +1 -1
  113. package/dist/src/harness/types.d.ts +0 -21
  114. package/dist/src/instrumentation/channel-delivery.js +1 -1
  115. package/dist/src/instrumentation/content-policy.d.ts +2 -2
  116. package/dist/src/instrumentation/content.js +1 -1
  117. package/dist/src/instrumentation/lifecycle.d.ts +5 -7
  118. package/dist/src/instrumentation/native-events.d.ts +2 -0
  119. package/dist/src/instrumentation/native-events.js +1 -1
  120. package/dist/src/instrumentation/principal-summary.d.ts +3 -3
  121. package/dist/src/instrumentation/runtime-global.d.ts +4 -0
  122. package/dist/src/instrumentation/runtime-global.js +1 -0
  123. package/dist/src/instrumentation/runtime.d.ts +5 -9
  124. package/dist/src/instrumentation/runtime.js +1 -1
  125. package/dist/src/instrumentation/session-context.d.ts +3 -0
  126. package/dist/src/instrumentation/session-context.js +1 -1
  127. package/dist/src/instrumentation/session-init.d.ts +5 -0
  128. package/dist/src/instrumentation/session-init.js +1 -0
  129. package/dist/src/instrumentation/setup-context.js +1 -1
  130. package/dist/src/internal/application/dev-environment.d.ts +3 -0
  131. package/dist/src/internal/application/dev-environment.js +1 -1
  132. package/dist/src/internal/application/output-publication-journal.js +1 -1
  133. package/dist/src/internal/application/output-publication-lock.js +1 -1
  134. package/dist/src/internal/application/package.js +1 -1
  135. package/dist/src/internal/authored-definition/connection.js +1 -1
  136. package/dist/src/internal/authored-definition/schema-backed.d.ts +3 -4
  137. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  138. package/dist/src/internal/instrumentation.d.ts +1 -12
  139. package/dist/src/internal/instrumentation.js +1 -1
  140. package/dist/src/internal/logging.js +1 -1
  141. package/dist/src/internal/nitro/host/build-application.js +1 -1
  142. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  143. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
  144. package/dist/src/internal/nitro/host/workflow-sandbox-runtime-plugin.js +1 -1
  145. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  146. package/dist/src/protocol/activity.d.ts +1 -0
  147. package/dist/src/protocol/activity.js +1 -1
  148. package/dist/src/public/channels/chat-sdk/audience.d.ts +8 -0
  149. package/dist/src/public/channels/chat-sdk/audience.js +1 -1
  150. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +0 -2
  151. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +1 -1
  152. package/dist/src/public/channels/discord/audience.js +1 -1
  153. package/dist/src/public/channels/discord/discordChannel.js +1 -1
  154. package/dist/src/public/channels/discord/index.d.ts +0 -1
  155. package/dist/src/public/channels/index.d.ts +2 -3
  156. package/dist/src/public/channels/slack/activity-plan.js +1 -1
  157. package/dist/src/public/channels/slack/defaults.d.ts +2 -2
  158. package/dist/src/public/channels/slack/index.d.ts +1 -1
  159. package/dist/src/public/channels/slack/slackChannel.d.ts +11 -3
  160. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  161. package/dist/src/public/channels/teams/hitl.js +1 -1
  162. package/dist/src/public/channels/teams/index.d.ts +0 -1
  163. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  164. package/dist/src/public/channels/teams/verify.js +1 -1
  165. package/dist/src/public/channels/telegram/audience.d.ts +7 -0
  166. package/dist/src/public/channels/telegram/audience.js +1 -1
  167. package/dist/src/public/channels/telegram/index.d.ts +0 -1
  168. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  169. package/dist/src/public/channels/twilio/twilioChannel.d.ts +0 -2
  170. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  171. package/dist/src/public/connections/index.d.ts +1 -1
  172. package/dist/src/public/definitions/channel.d.ts +2 -1
  173. package/dist/src/public/definitions/channel.js +1 -1
  174. package/dist/src/public/definitions/connections/mcp.d.ts +7 -1
  175. package/dist/src/public/definitions/connections/openapi.d.ts +1 -1
  176. package/dist/src/public/definitions/workspace-agent.js +1 -1
  177. package/dist/src/public/models/openai/chatgpt/auth.js +1 -1
  178. package/dist/src/public/models/openai/chatgpt/codex-app-server.js +1 -1
  179. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  180. package/dist/src/public/next/index.d.ts +6 -4
  181. package/dist/src/public/next/index.js +1 -1
  182. package/dist/src/public/next/server.js +1 -1
  183. package/dist/src/public/next/vercel-output-config.d.ts +1 -0
  184. package/dist/src/public/tools/workflow.d.ts +1 -4
  185. package/dist/src/public/tools/workflow.js +1 -1
  186. package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
  187. package/dist/src/runtime/connections/authorization-tokens.d.ts +2 -4
  188. package/dist/src/runtime/connections/mcp-client.js +1 -1
  189. package/dist/src/runtime/connections/principal.d.ts +6 -6
  190. package/dist/src/runtime/connections/principal.js +1 -1
  191. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  192. package/dist/src/runtime/resolve-agent.js +1 -1
  193. package/dist/src/runtime/resolve-connection.js +1 -1
  194. package/dist/src/runtime/resolve-tool.js +1 -1
  195. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  196. package/dist/src/runtime/types.d.ts +4 -9
  197. package/dist/src/self-modification/agent.d.ts +7 -1
  198. package/dist/src/self-modification/agent.js +1 -1
  199. package/dist/src/self-modification/extension/classify-registry-item.d.ts +3 -3
  200. package/dist/src/self-modification/extension/classify-registry-item.js +1 -1
  201. package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -7
  202. package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
  203. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  204. package/dist/src/setup/flows/registry.js +1 -1
  205. package/dist/src/setup/integrations/self-modification/setup.js +1 -1
  206. package/dist/src/setup/provider-settings.js +1 -1
  207. package/dist/src/setup/scaffold/create/project.js +6 -2
  208. package/dist/src/shared/channel-audience.d.ts +0 -3
  209. package/dist/src/shared/channel-definition.d.ts +13 -4
  210. package/dist/src/shared/connection-types.d.ts +20 -7
  211. package/dist/src/shared/conversation-context.d.ts +62 -0
  212. package/dist/src/shared/conversation-context.js +1 -0
  213. package/dist/src/shared/forwarded-trace-policy.d.ts +2 -1
  214. package/dist/src/shared/forwarded-trace-policy.js +1 -1
  215. package/dist/src/shared/instrumentation-channel-kind.d.ts +3 -0
  216. package/dist/src/shared/instrumentation-channel-kind.js +1 -0
  217. package/dist/src/shared/instrumentation-content.d.ts +9 -4
  218. package/dist/src/shared/instrumentation-content.js +1 -1
  219. package/dist/src/shared/trace-policy.d.ts +7 -6
  220. package/dist/src/shared/trace-policy.js +1 -1
  221. package/dist/src/shared/validate-authorization.js +1 -1
  222. package/dist/src/shared/workflow-sandbox.d.ts +18 -12
  223. package/dist/src/shared/workflow-sandbox.js +1 -1
  224. package/dist/src/subagents/handle-dispatch.d.ts +2 -1
  225. package/dist/src/subagents/handle-dispatch.js +1 -1
  226. package/dist/src/subagents/remote-dispatch.js +1 -1
  227. package/dist/src/subagents/start-local.d.ts +1 -0
  228. package/dist/src/subagents/start-local.js +1 -1
  229. package/dist/src/subagents/start-remote.d.ts +2 -0
  230. package/dist/src/subagents/start-remote.js +1 -1
  231. package/dist/src/subagents/tool.d.ts +3 -0
  232. package/dist/src/subagents/tool.js +1 -1
  233. package/dist/src/svelte/index.js +1 -1
  234. package/dist/src/svelte/use-eve-agent.js +1 -1
  235. package/dist/src/tasks/session-index.d.ts +13 -0
  236. package/dist/src/tasks/session-index.js +1 -1
  237. package/dist/src/tools/auth.d.ts +5 -6
  238. package/dist/src/tools/provided/workflow.d.ts +12 -0
  239. package/dist/src/tools/provided/workflow.js +1 -0
  240. package/dist/src/tools/workflow-program-input.d.ts +6 -0
  241. package/dist/src/tools/workflow-program-input.js +1 -0
  242. package/dist/src/tracing/agent-invocation-coordinator.d.ts +3 -2
  243. package/dist/src/tracing/agent-invocation-coordinator.js +1 -1
  244. package/dist/src/tracing/agent-memory-instrumentation.d.ts +3 -1
  245. package/dist/src/tracing/agent-memory-instrumentation.js +1 -1
  246. package/dist/src/tracing/agent-otel-provider.d.ts +2 -0
  247. package/dist/src/tracing/agent-otel-provider.js +2 -2
  248. package/dist/src/tracing/agent-otel-runtime-context.d.ts +2 -1
  249. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  250. package/dist/src/tracing/agent-otel-session-context.d.ts +2 -0
  251. package/dist/src/tracing/agent-otel-session-context.js +1 -1
  252. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  253. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  254. package/dist/src/tracing/agent-trace-state.d.ts +2 -0
  255. package/dist/src/tracing/content-attributes.js +1 -1
  256. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  257. package/dist/src/tracing/local-instrumentation-runtime.d.ts +1 -1
  258. package/dist/src/tracing/local-instrumentation-runtime.js +1 -1
  259. package/dist/src/vue/index.js +1 -1
  260. package/dist/src/vue/use-eve-agent.js +1 -1
  261. package/docs/agent-config.md +1 -1
  262. package/docs/channels/chat-sdk.mdx +7 -0
  263. package/docs/channels/custom.mdx +32 -2
  264. package/docs/channels/eve.mdx +39 -0
  265. package/docs/channels/linear.mdx +7 -3
  266. package/docs/channels/overview.mdx +13 -0
  267. package/docs/channels/slack.mdx +41 -1
  268. package/docs/connections/mcp.mdx +18 -1
  269. package/docs/connections/openapi.mdx +8 -2
  270. package/docs/connections/overview.mdx +16 -13
  271. package/docs/getting-started.mdx +1 -1
  272. package/docs/guides/deployment/self-hosting.md +1 -1
  273. package/docs/guides/deployment/vercel.mdx +2 -2
  274. package/docs/guides/dev-tui.md +4 -4
  275. package/docs/guides/dynamic-capabilities.md +4 -4
  276. package/docs/guides/frontend/nextjs.mdx +12 -10
  277. package/docs/guides/hooks.md +1 -1
  278. package/docs/guides/instrumentation/meta.json +4 -0
  279. package/docs/guides/instrumentation/otel.mdx +149 -0
  280. package/docs/guides/instrumentation/overview.md +199 -0
  281. package/docs/guides/instrumentation/providers.mdx +169 -0
  282. package/docs/guides/meta.json +0 -1
  283. package/docs/guides/remote-agents.md +19 -21
  284. package/docs/install-integrations.mdx +3 -5
  285. package/docs/patterns/multi-tenant-auth.md +3 -3
  286. package/docs/reference/cli.md +22 -21
  287. package/docs/reference/typescript-api.md +9 -9
  288. package/docs/subagents/index.mdx +5 -3
  289. package/docs/tools/workflows.mdx +56 -1
  290. package/package.json +1 -1
  291. package/dist/src/cli/commands/registry-package.d.ts +0 -52
  292. package/dist/src/cli/commands/registry-package.js +0 -1
  293. package/dist/src/harness/workflow-continuation-security.d.ts +0 -5
  294. package/dist/src/harness/workflow-continuation-security.js +0 -1
  295. package/dist/src/harness/workflow-interrupt-state.d.ts +0 -20
  296. package/dist/src/harness/workflow-interrupt-state.js +0 -1
  297. package/dist/src/harness/workflow-lifecycle.d.ts +0 -32
  298. package/dist/src/harness/workflow-lifecycle.js +0 -1
  299. package/dist/src/harness/workflow-sandbox.d.ts +0 -28
  300. package/dist/src/harness/workflow-sandbox.js +0 -2
  301. package/dist/src/harness/workflow-subagent-limit.d.ts +0 -28
  302. package/dist/src/harness/workflow-subagent-limit.js +0 -1
  303. package/dist/src/harness/workflow-task-state.d.ts +0 -9
  304. package/dist/src/harness/workflow-task-state.js +0 -1
  305. package/dist/src/harness/workflow-tool-description.d.ts +0 -22
  306. package/dist/src/harness/workflow-tool-description.js +0 -37
  307. package/dist/src/tools/workflow.d.ts +0 -37
  308. package/dist/src/tools/workflow.js +0 -1
  309. package/docs/guides/instrumentation-providers.md +0 -247
  310. package/docs/guides/instrumentation.md +0 -453
@@ -1 +1 @@
1
- import{resolveEveDestinationPrefix}from"./server.js";import{ensureEveVercelOutputConfig}from"./vercel-output-config.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{isAbsolute,resolve}from"node:path";import{assertValidPublicAgentName}from"#internal/agent-name.js";import{quoteVercelShellArgument,toVercelRelativePath}from"#internal/vercel/build-command.js";import{resolveEveBinaryPath}from"#shared/resolve-eve-binary.js";const EVE_NEXT_SERVICE_PREFIX=`/_eve_internal/eve`,EVE_NEXT_PRODUCTION_PORT_ENV=`EVE_NEXT_PRODUCTION_PORT`;function resolveApplicationRoot(e){return e===void 0||e.length===0?process.cwd():isAbsolute(e)?e:resolve(process.cwd(),e)}function resolveDevServerTimeout(e){if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw Error(`eve Next.js development server timeout must be a positive number.`);return e}}function normalizeRoutePrefix(e){let t=(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``);if(t.length===0)throw Error(`eve Next.js service prefix cannot resolve to the root route.`);return t}function joinRoutePrefix(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function createNamedAgentRoutePrefix(e){return joinRoutePrefix(`/eve/agents`,e)}function createNamedAgentServicePrefix(e,t){return joinRoutePrefix(e,t)}function createAgentRewriteSource(e){return joinRoutePrefix(e,`${EVE_ROUTE_PREFIX}/:path+`)}function normalizeOrigin(e){return new URL(e.trim()).origin}function readLocalProductionPort(e){let t=process.env[EVE_NEXT_PRODUCTION_PORT_ENV],n=t===void 0||t.trim().length===0?4274:Number.parseInt(t,10);if(t!==void 0&&t.trim().length>0&&String(n)!==t.trim())throw Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} must be an integer between 1 and 65535.`);let r=n+e;if(r<1||r>65535)throw Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} plus the eve agent count exceeds 65535.`);return r}function resolveProductionDestination(e){if(process.env.VERCEL)return{destinationPrefix:e.servicePrefix};let t=process.env.EVE_NEXT_PRODUCTION_ORIGIN;if(t!==void 0&&t.trim().length>0)return{destinationPrefix:joinRoutePrefix(normalizeOrigin(t),e.servicePrefix)};let n=`http://127.0.0.1:${String(readLocalProductionPort(e.localProductionPortOffset))}`;return{destinationPrefix:n,localServerOrigin:n}}function createEveRewriteRule(e){let t=createAgentRewriteSource(e.publicRoutePrefix);return{destination:joinRoutePrefix(e.destinationPrefix,`${EVE_ROUTE_PREFIX}/:path+`),source:t}}async function resolveExistingRewrites(e){return await e?.()}function mergeRewriteRules(e,t){return e===void 0?{beforeFiles:t}:isRewriteSections(e)?{...e,beforeFiles:[...t,...e.beforeFiles??[]]}:{afterFiles:e,beforeFiles:t}}function isRewriteSections(e){return!Array.isArray(e)}async function resolveNextConfig(e,t,n){return typeof e==`function`?await e(t,n):e}function assertValidAgentName(e){assertValidPublicAgentName(e,`eve Next.js agent name`)}function createDefaultBuildCommand(e){let t=toVercelRelativePath(e.agentRoot,resolveEveBinaryPath(e.agentRoot));return`node ${quoteVercelShellArgument(t)} build`}function normalizeAgentsConfig(e){let t=normalizeRoutePrefix(e.servicePrefix??`/_eve_internal/eve`),resolveBuildCommand=(t,n)=>n??e.eveBuildCommand??createDefaultBuildCommand({agentRoot:t});if(e.agents===void 0){let n=resolveApplicationRoot(e.eveRoot);return[{appRoot:n,buildCommand:resolveBuildCommand(n,void 0),localProductionPortOffset:0,publicRoutePrefix:``,servicePrefix:t}]}if(e.eveRoot!==void 0)throw Error(`withEve cannot combine eveRoot with agents. Use one configuration form.`);let n=Object.entries(e.agents);if(n.length===0)throw Error(`withEve agents must contain at least one named eve agent.`);return n.map(([e,n],r)=>{assertValidAgentName(e);let i=typeof n==`string`?{root:n}:n,a=resolveApplicationRoot(i.root);return{appRoot:a,buildCommand:resolveBuildCommand(a,i.buildCommand),localProductionPortOffset:r,name:e,publicRoutePrefix:createNamedAgentRoutePrefix(e),servicePrefix:normalizeRoutePrefix(i.servicePrefix??createNamedAgentServicePrefix(t,e))}})}function withEve(e,t={}){let n=process.cwd(),r=resolveDevServerTimeout(t.devServerTimeoutMs),i=normalizeAgentsConfig(t);return async function(t,a){let o=await resolveNextConfig(e,t,a),s=o.rewrites,c=await ensureEveVercelOutputConfig({agents:i.map(e=>({appRoot:e.appRoot,buildCommand:e.buildCommand,name:e.name,publicRoutePrefix:e.publicRoutePrefix,servicePrefix:e.servicePrefix})),nextRoot:n});if(process.env.VERCEL)return o;let l=new Map(c.agents.map(e=>[e.name,e])),u=i.map(e=>{let t=l.get(e.name),n=resolveProductionDestination({localProductionPortOffset:e.localProductionPortOffset,servicePrefix:t?.servicePrefix??e.servicePrefix});return{...e,productionDestination:n}});return{...o,async rewrites(){let[e,n]=await Promise.all([resolveExistingRewrites(s),Promise.all(u.map(async e=>createEveRewriteRule({destinationPrefix:await resolveEveDestinationPrefix({appRoot:e.appRoot,devServerTimeoutMs:r,logLabel:e.name,phase:t,productionDestinationPrefix:e.productionDestination.destinationPrefix,productionServerOrigin:e.productionDestination.localServerOrigin}),publicRoutePrefix:e.publicRoutePrefix})))]);return mergeRewriteRules(e,n)}}}}export{EVE_NEXT_SERVICE_PREFIX,withEve};
1
+ import{resolveEveDestinationPrefix}from"./server.js";import{ensureEveVercelOutputConfig}from"./vercel-output-config.js";import{EVE_ROUTE_PREFIX}from"#protocol/routes.js";import{isAbsolute,resolve}from"node:path";import{findEveProjectContext}from"#internal/project-context.js";import{assertValidPublicAgentName}from"#internal/agent-name.js";import{quoteVercelShellArgument,toVercelRelativePath}from"#internal/vercel/build-command.js";import{resolveEveBinaryPath}from"#shared/resolve-eve-binary.js";const EVE_NEXT_SERVICE_PREFIX=`/_eve_internal/eve`,EVE_NEXT_PRODUCTION_PORT_ENV=`EVE_NEXT_PRODUCTION_PORT`;function resolveApplicationRoot(e){return e===void 0||e.length===0?process.cwd():isAbsolute(e)?e:resolve(process.cwd(),e)}function resolveDevServerTimeout(e){if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw Error(`eve Next.js development server timeout must be a positive number.`);return e}}function normalizeRoutePrefix(e){let t=(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``);if(t.length===0)throw Error(`eve Next.js service prefix cannot resolve to the root route.`);return t}function joinRoutePrefix(e,t){return`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`}function createNamedAgentRoutePrefix(e){return joinRoutePrefix(`/eve/agents`,e)}function createNamedAgentServicePrefix(e,t){return joinRoutePrefix(e,t)}function createAgentRewriteSource(e){return joinRoutePrefix(e,`${EVE_ROUTE_PREFIX}/:path+`)}function normalizeOrigin(e){return new URL(e.trim()).origin}function readLocalProductionPort(e){let t=process.env[EVE_NEXT_PRODUCTION_PORT_ENV],n=t===void 0||t.trim().length===0?4274:Number.parseInt(t,10);if(t!==void 0&&t.trim().length>0&&String(n)!==t.trim())throw Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} must be an integer between 1 and 65535.`);let r=n+e;if(r<1||r>65535)throw Error(`${EVE_NEXT_PRODUCTION_PORT_ENV} plus the eve agent count exceeds 65535.`);return r}function resolveProductionDestination(e){if(process.env.VERCEL)return{destinationPrefix:e.servicePrefix};let t=process.env.EVE_NEXT_PRODUCTION_ORIGIN;if(t!==void 0&&t.trim().length>0)return{destinationPrefix:joinRoutePrefix(normalizeOrigin(t),e.servicePrefix)};let n=`http://127.0.0.1:${String(readLocalProductionPort(e.localProductionPortOffset))}`;return{destinationPrefix:n,localServerOrigin:n}}function createEveRewriteRule(e){let t=createAgentRewriteSource(e.publicRoutePrefix);return{destination:joinRoutePrefix(e.destinationPrefix,`${EVE_ROUTE_PREFIX}/:path+`),source:t}}async function resolveExistingRewrites(e){return await e?.()}function mergeRewriteRules(e,t){return e===void 0?{beforeFiles:t}:isRewriteSections(e)?{...e,beforeFiles:[...t,...e.beforeFiles??[]]}:{afterFiles:e,beforeFiles:t}}function isRewriteSections(e){return!Array.isArray(e)}async function resolveNextConfig(e,t,n){return typeof e==`function`?await e(t,n):e}function assertValidAgentName(e){assertValidPublicAgentName(e,`eve Next.js agent name`)}function assertValidWithEveOptions(e){if(e.agents===void 0)return;if(e.eveRoot!==void 0)throw Error(`withEve cannot combine eveRoot with agents. Use one configuration form.`);let t=Object.keys(e.agents);if(t.length===0)throw Error(`withEve agents must contain at least one named eve agent.`);for(let e of t)assertValidAgentName(e)}function createDefaultBuildCommand(e){let t=toVercelRelativePath(e.agentRoot,resolveEveBinaryPath(e.agentRoot));return`node ${quoteVercelShellArgument(t)} build`}async function normalizeAgentsConfig(e,t){let n=normalizeRoutePrefix(e.servicePrefix??`/_eve_internal/eve`),resolveBuildCommand=(t,n)=>n??e.eveBuildCommand??createDefaultBuildCommand({agentRoot:t});if(e.agents===void 0){if(e.eveRoot===void 0){let e=await findEveProjectContext(t);if(e?.kind===`workspace`&&e.workspace.root===t&&e.workspace.members.length>0)return e.workspace.members.map((e,t)=>({appRoot:e.appRoot,buildCommand:resolveBuildCommand(e.appRoot,void 0),localProductionPortOffset:t,name:e.name,publicRoutePrefix:createNamedAgentRoutePrefix(e.name),servicePrefix:createNamedAgentServicePrefix(n,e.name),workspaceMember:!0}))}let r=resolveApplicationRoot(e.eveRoot);return[{appRoot:r,buildCommand:resolveBuildCommand(r,void 0),localProductionPortOffset:0,publicRoutePrefix:``,servicePrefix:n}]}let r=Object.entries(e.agents);if(r.length===0)throw Error(`withEve agents must contain at least one named eve agent.`);return r.map(([e,t],r)=>{assertValidAgentName(e);let i=typeof t==`string`?{root:t}:t,a=resolveApplicationRoot(i.root);return{appRoot:a,buildCommand:resolveBuildCommand(a,i.buildCommand),localProductionPortOffset:r,name:e,publicRoutePrefix:createNamedAgentRoutePrefix(e),servicePrefix:normalizeRoutePrefix(i.servicePrefix??createNamedAgentServicePrefix(n,e))}})}function withEve(e,t={}){let n=process.cwd(),r=resolveDevServerTimeout(t.devServerTimeoutMs);return assertValidWithEveOptions(t),async function(i,a){let[o,s]=await Promise.all([normalizeAgentsConfig(t,n),resolveNextConfig(e,i,a)]),c=s.rewrites,l=await ensureEveVercelOutputConfig({agents:o.map(e=>{let t={appRoot:e.appRoot,buildCommand:e.buildCommand,name:e.name,publicRoutePrefix:e.publicRoutePrefix,servicePrefix:e.servicePrefix};return e.workspaceMember===!0&&(t.workspaceMember=!0),t}),nextRoot:n});if(process.env.VERCEL)return s;let u=new Map(l.agents.map(e=>[e.name,e])),d=o.map(e=>{let t=u.get(e.name),n=resolveProductionDestination({localProductionPortOffset:e.localProductionPortOffset,servicePrefix:t?.servicePrefix??e.servicePrefix});return{...e,productionDestination:n}});return{...s,async rewrites(){let[e,t]=await Promise.all([resolveExistingRewrites(c),Promise.all(d.map(async e=>createEveRewriteRule({destinationPrefix:await resolveEveDestinationPrefix({appRoot:e.appRoot,devServerTimeoutMs:r,logLabel:e.name,phase:i,productionDestinationPrefix:e.productionDestination.destinationPrefix,productionServerOrigin:e.productionDestination.localServerOrigin}),publicRoutePrefix:e.publicRoutePrefix})))]);return mergeRewriteRules(e,t)}}}}export{EVE_NEXT_SERVICE_PREFIX,withEve};
@@ -1,2 +1,2 @@
1
1
  import{mkdir,open,readFile,rm,stat,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageRoot}from"#internal/application/package.js";import{existsSync}from"node:fs";import{spawn}from"node:child_process";import{readDevelopmentRuntimeArtifactsRevision}from"#services/dev-client/runtime-artifacts.js";const DEFAULT_SERVER_READY_TIMEOUT_MS=18e4,ANSI_ESCAPE_PATTERN=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),SERVER_URL_CANDIDATE_PATTERN=/https?:\/\/[^\s"'<>]+/g,globalStateSymbol=Symbol.for(`eve.next.state`);function getGlobalState(){let e=globalThis;return e[globalStateSymbol]??={servers:new Map},e[globalStateSymbol]}function normalizeOrigin(e){return new URL(e).origin}function readEveBaseUrlEnvironment(){let e=process.env.EVE_BASE_URL;if(e!==void 0&&e.trim().length!==0)return normalizeOrigin(e)}function isNodeErrorWithCode(e,t){return e instanceof Error&&`code`in e&&e.code===t}function delay(e){return new Promise(t=>setTimeout(t,e))}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function resolveEveCacheDirectory(e){return join(e,`.eve`)}function resolveEveDevServerRegistryPath(e){return join(resolveEveCacheDirectory(e),`next-dev-server.json`)}function resolveEveDevServerLockPath(e){return join(resolveEveCacheDirectory(e),`next-dev-server.lock`)}function normalizeDevServerRegistry(e){if(isRecord(e)&&typeof e.appRoot==`string`&&typeof e.origin==`string`&&typeof e.updatedAt==`string`&&(e.pid===null||typeof e.pid==`number`))try{return{appRoot:e.appRoot,origin:normalizeOrigin(e.origin),pid:e.pid,updatedAt:e.updatedAt}}catch{return}}async function readUsableEveDevServerRegistry(e){try{let t=normalizeDevServerRegistry(JSON.parse(await readFile(resolveEveDevServerRegistryPath(e),`utf8`)));return t===void 0||t.appRoot!==e||await readDevelopmentRuntimeArtifactsRevision({serverUrl:t.origin,timeoutMs:1e3})===void 0?void 0:t.origin}catch(e){if(isNodeErrorWithCode(e,`ENOENT`))return;throw e}}async function writeEveDevServerRegistry(e,t){await mkdir(resolveEveCacheDirectory(e),{recursive:!0}),await writeFile(resolveEveDevServerRegistryPath(e),`${JSON.stringify({appRoot:e,origin:t.origin,pid:t.process?.pid??null,updatedAt:new Date().toISOString()},null,2)}\n`)}async function removeStaleEveDevServerLock(e){try{let t=await stat(e);Date.now()-t.mtimeMs>3e4&&await rm(e,{force:!0})}catch(e){if(!isNodeErrorWithCode(e,`ENOENT`))throw e}}async function acquireEveDevServerLock(e,t){let n=resolveEveCacheDirectory(e),r=resolveEveDevServerLockPath(e),i=Date.now()+t;for(await mkdir(n,{recursive:!0});;)try{let e=await open(r,`wx`);return await e.writeFile(`${String(process.pid)}\n`),await e.close(),async()=>{await rm(r,{force:!0})}}catch(n){if(!isNodeErrorWithCode(n,`EEXIST`))throw n;if(await readUsableEveDevServerRegistry(e)!==void 0)return async()=>{};if(await removeStaleEveDevServerLock(r),Date.now()>i)throw Error(`Timed out after ${t}ms waiting for another Next.js process to start eve.`);await delay(100)}}function createEveBinaryPath(){return join(resolvePackageRoot(),`bin`,`eve.js`)}function isLoopbackHostname(e){return e===`localhost`||e===`::1`||e===`[::1]`||/^127(?:\.\d{1,3}){3}$/.test(e)}function parseLocalServerOrigin(e){let t=URL.parse(e);if(!(t===null||t.protocol!==`http:`&&t.protocol!==`https:`||!isLoopbackHostname(t.hostname)||t.port.length===0))return t.origin}function findLocalServerOrigin(e){for(let t of e.matchAll(SERVER_URL_CANDIDATE_PATTERN)){let e=t[0],n=parseLocalServerOrigin(e);if(n!==void 0)return n}}function formatEveDevOutputLine(e,t){let n=e.replace(/\r$/,``),r=n.replace(ANSI_ESCAPE_PATTERN,``).trim();if(r.length===0||/^☰eve\b/.test(r)||r===`CONFIGURATION_FIELD_CONFLICT`||r.startsWith(`[CONFIGURATION_FIELD_CONFLICT]`))return;let i=t===void 0?`[eve:dev]`:`[eve:dev:${t}]`,a=/server listening at\s+(https?:\/\/[^\s]+)/i.exec(n);return a===null?`${i} ${n}`:`${i} server listening at ${a[1]}`}function createEveDevOutputWriter(e){let t=``,writeLine=t=>{let n=formatEveDevOutputLine(t,e.logLabel);n!==void 0&&e.stream.write(`${n}\n`)};return{flush(){t.length!==0&&(writeLine(t),t=``)},write(e){t+=e.toString(`utf8`);let n=t.split(`
2
- `);t=n.pop()??``;for(let e of n)writeLine(e)}}}function startServerProcess(e){return new Promise((t,n)=>{let r=spawn(e.command,e.args,{cwd:e.cwd,env:{...process.env,...e.env},stdio:[`ignore`,`pipe`,`pipe`]}),i=createEveDevOutputWriter({logLabel:e.logLabel,stream:process.stderr}),a=createEveDevOutputWriter({logLabel:e.logLabel,stream:process.stdout}),o=setTimeout(()=>{r.kill(),n(Error(`Timed out after ${e.timeoutMs??DEFAULT_SERVER_READY_TIMEOUT_MS}ms waiting for eve to print its server URL.`))},e.timeoutMs??DEFAULT_SERVER_READY_TIMEOUT_MS),cleanup=()=>{clearTimeout(o),r.off(`error`,handleError),r.off(`exit`,handleEarlyExit)},flushOutput=()=>{a.flush(),i.flush()},handleError=e=>{flushOutput(),cleanup(),n(e)},handleEarlyExit=(e,t)=>{flushOutput(),cleanup(),n(Error(`eve server process exited before printing its server URL (code ${String(e)}, signal ${String(t)}).`))},handleOutput=e=>{let n=findLocalServerOrigin(e.toString(`utf8`));n!==void 0&&(cleanup(),t({origin:n,process:r}))};r.once(`error`,handleError),r.once(`exit`,handleEarlyExit),r.stdout.on(`data`,e=>{a.write(e),handleOutput(e)}),r.stderr.on(`data`,e=>{i.write(e),handleOutput(e)})})}function installProcessShutdown(e){let t=e.process;if(t===void 0)return e;let close=()=>{t.killed||t.kill()};return process.once(`beforeExit`,close),process.once(`exit`,close),e}function startEveDevServer(e,t,n){return startServerProcess({args:[createEveBinaryPath(),`dev`,`--no-ui`,`--port`,`0`],command:process.execPath,cwd:e,logLabel:n,timeoutMs:t}).then(e=>installProcessShutdown(e))}function startEveProductionServer(e){let t=new URL(e.origin),n=t.port,r=join(e.appRoot,`.output`,`server`,`index.mjs`);if(existsSync(r))return startServerProcess({args:[r],command:process.execPath,cwd:e.appRoot,env:{HOST:t.hostname,NITRO_HOST:t.hostname,NITRO_PORT:n,PORT:n}}).then(installProcessShutdown)}async function resolveSharedEveDevServer(e,t,n){let r=await readUsableEveDevServerRegistry(e);if(r!==void 0)return{origin:r};let i=await acquireEveDevServerLock(e,t);try{let r=await readUsableEveDevServerRegistry(e);if(r!==void 0)return{origin:r};let i=await startEveDevServer(e,t,n);return await writeEveDevServerRegistry(e,i),i}finally{await i()}}async function resolveEveDestinationPrefix(e){let t=getGlobalState();if(process.env.NODE_ENV===`production`){if(e.phase===`phase-production-build`)return e.productionDestinationPrefix;let n=`production:${e.appRoot}`,r=t.servers.get(n);return r===void 0&&(r=process.env.VERCEL||e.productionServerOrigin===void 0?void 0:startEveProductionServer({appRoot:e.appRoot,origin:e.productionServerOrigin}),r!==void 0&&(r=r.catch(e=>{throw t.servers.delete(n),e}),t.servers.set(n,r))),r===void 0?e.productionDestinationPrefix:(await r).origin}let n=readEveBaseUrlEnvironment();if(n!==void 0)return n;if(process.env.NODE_ENV!==`development`)return e.productionDestinationPrefix;let r=`dev:${e.appRoot}`,i=t.servers.get(r);return i===void 0&&(i=resolveSharedEveDevServer(e.appRoot,e.devServerTimeoutMs??18e4,e.logLabel).catch(e=>{throw t.servers.delete(r),e}),t.servers.set(r,i)),(await i).origin}export{resolveEveDestinationPrefix};
2
+ `);t=n.pop()??``;for(let e of n)writeLine(e)}}}function startServerProcess(e){return new Promise((t,n)=>{let r=spawn(e.command,e.args,{cwd:e.cwd,env:{...process.env,...e.env},stdio:[`ignore`,`pipe`,`pipe`]}),i=createEveDevOutputWriter({logLabel:e.logLabel,stream:process.stderr}),a=createEveDevOutputWriter({logLabel:e.logLabel,stream:process.stdout}),o=setTimeout(()=>{r.kill(),n(Error(`Timed out after ${e.timeoutMs??DEFAULT_SERVER_READY_TIMEOUT_MS}ms waiting for eve to print its server URL.`))},e.timeoutMs??DEFAULT_SERVER_READY_TIMEOUT_MS),cleanup=()=>{clearTimeout(o),r.off(`error`,handleError),r.off(`exit`,handleEarlyExit)},flushOutput=()=>{a.flush(),i.flush()},handleError=e=>{flushOutput(),cleanup(),n(e)},handleEarlyExit=(e,t)=>{flushOutput(),cleanup(),n(Error(`eve server process exited before printing its server URL (code ${String(e)}, signal ${String(t)}).`))},handleOutput=e=>{let n=findLocalServerOrigin(e.toString(`utf8`));n!==void 0&&(cleanup(),t({origin:n,process:r}))};r.once(`error`,handleError),r.once(`exit`,handleEarlyExit),r.stdout.on(`data`,e=>{a.write(e),handleOutput(e)}),r.stderr.on(`data`,e=>{i.write(e),handleOutput(e)})})}function installProcessShutdown(e){let t=e.process;if(t===void 0)return e;let close=()=>{t.killed||t.kill()};return process.once(`beforeExit`,close),process.once(`exit`,close),e}function startEveDevServer(e,t,n){return startServerProcess({args:[createEveBinaryPath(),`dev`,`--no-ui`,`--port`,`0`],command:process.execPath,cwd:e,logLabel:n,timeoutMs:t}).then(e=>installProcessShutdown(e))}function startEveProductionServer(e){let t=new URL(e.origin),n=t.port,r=join(e.appRoot,`.output`,`server`,`index.mjs`);if(!existsSync(r))throw Error(`eve production output is missing at ${r}. Run eve build from ${e.appRoot} before starting Next.js.`);return startServerProcess({args:[r],command:process.execPath,cwd:e.appRoot,env:{HOST:t.hostname,NITRO_HOST:t.hostname,NITRO_PORT:n,PORT:n}}).then(installProcessShutdown)}async function resolveSharedEveDevServer(e,t,n){let r=await readUsableEveDevServerRegistry(e);if(r!==void 0)return{origin:r};let i=await acquireEveDevServerLock(e,t);try{let r=await readUsableEveDevServerRegistry(e);if(r!==void 0)return{origin:r};let i=await startEveDevServer(e,t,n);return await writeEveDevServerRegistry(e,i),i}finally{await i()}}async function resolveEveDestinationPrefix(e){let t=getGlobalState();if(process.env.NODE_ENV===`production`){if(e.phase===`phase-production-build`)return e.productionDestinationPrefix;let n=`production:${e.appRoot}`,r=t.servers.get(n);return r===void 0&&(r=process.env.VERCEL||e.productionServerOrigin===void 0?void 0:startEveProductionServer({appRoot:e.appRoot,origin:e.productionServerOrigin}),r!==void 0&&(r=r.catch(e=>{throw t.servers.delete(n),e}),t.servers.set(n,r))),r===void 0?e.productionDestinationPrefix:(await r).origin}let n=readEveBaseUrlEnvironment();if(n!==void 0)return n;if(process.env.NODE_ENV!==`development`)return e.productionDestinationPrefix;let r=`dev:${e.appRoot}`,i=t.servers.get(r);return i===void 0&&(i=resolveSharedEveDevServer(e.appRoot,e.devServerTimeoutMs??18e4,e.logLabel).catch(e=>{throw t.servers.delete(r),e}),t.servers.set(r,i)),(await i).origin}export{resolveEveDestinationPrefix};
@@ -7,6 +7,7 @@ export interface EnsureVercelOutputConfigAgentInput {
7
7
  readonly name?: string;
8
8
  readonly publicRoutePrefix: string;
9
9
  readonly servicePrefix: string;
10
+ readonly workspaceMember?: boolean;
10
11
  }
11
12
  export interface EnsureVercelOutputConfigAgentResult {
12
13
  readonly name?: string;
@@ -1,4 +1 @@
1
- /**
2
- * Experimental Workflow tool authoring helpers.
3
- */
4
- export { type ExperimentalWorkflowToolDefinition, type ExperimentalWorkflowToolInput, experimental_workflow, isExperimentalWorkflowToolDefinition, } from "#tools/workflow.js";
1
+ export { workflow, type WorkflowTool, type WorkflowToolInput, type WorkflowToolOptions, } from "#tools/provided/workflow.js";
@@ -1 +1 @@
1
- import{experimental_workflow,isExperimentalWorkflowToolDefinition}from"#tools/workflow.js";export{experimental_workflow,isExperimentalWorkflowToolDefinition};
1
+ import{workflow}from"#tools/provided/workflow.js";export{workflow};
@@ -1,4 +1,4 @@
1
- import{z}from"#compiled/zod/index.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{MockLanguageModelV3}from"ai/test";import{FINAL_OUTPUT_TOOL_NAME}from"#harness/final-output.js";import{BOOTSTRAP_RUNTIME_MODEL_ID,BOOTSTRAP_RUNTIME_SYSTEM_PROMPT}from"#runtime/agent/bootstrap.js";import{createBootstrapGenerateResult,createBootstrapStreamResult,estimateTokenCount,getLastUserPromptText,getPromptContentText,getPromptText,isAgentsAnnouncementText}from"#runtime/agent/bootstrap-model-utils.js";import{createMockAuthoredToolInput,formatToolOutput,resolveMockFixtureToken,resolveWeatherCity}from"#runtime/agent/mock-model-fixtures.js";import{findRelevantSkill,getActivatedSkillIds,getAvailableSkills}from"#runtime/agent/mock-model-skill-selection.js";import{createJsonSchemaSample}from"#runtime/agent/mock-structured-output.js";const authoredRuntimeModelMocks=new Map,bootstrapWeatherPayloadSchema=z.object({city:z.string(),condition:z.string(),summary:z.string(),temperatureF:z.number().finite()}).strict();function shouldMockAuthoredRuntimeModels(){return process.env.NODE_ENV===`test`||process.env.EVE_MOCK_AUTHORED_MODELS===`1`}function createMockAuthoredRuntimeModel(e){let t=authoredRuntimeModelMocks.get(e.id);if(t!==void 0)return t;let n=new MockLanguageModelV3({modelId:e.id,provider:`eve-runtime-mock`,doGenerate:async t=>createMockModelResult(t,e.id),doStream:async t=>createBootstrapStreamResult(createMockModelResult(t,e.id))});return authoredRuntimeModelMocks.set(e.id,n),n}function createMockModelResult(e,t){let n=getLastAuthoredToolResult(e.prompt);if(n!==null){let r=createFollowUpToolCallResult({modelId:t,options:e,result:n});if(r!==null)return r}else{let n=createParallelAuthoredToolCallsResult(e,t)??createSubagentDelegationResult(e,t)??createSkillLoadResult(e.prompt,t)??createAuthoredToolCallResult(e,t);if(n!==null)return n}let r=createFinalOutputResult(e,t);if(r!==null)return r;let i=n===null?createAssistantMessage(e.prompt):formatToolResultReply(n,e.prompt);return createBootstrapGenerateResult({inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(i),text:i})}function createFinalOutputResult(e,t){let n=getAvailableTools(e).find(e=>e.name===FINAL_OUTPUT_TOOL_NAME);if(n===void 0)return null;let r=createJsonSchemaSample(n.inputSchema);return createToolCallGenerateResult({input:r,inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(JSON.stringify(r)),toolCallId:createToolCallId(FINAL_OUTPUT_TOOL_NAME),toolName:FINAL_OUTPUT_TOOL_NAME})}function resolveMockAuthoredRuntimeModel(e){return!shouldMockAuthoredRuntimeModels()||e.id===BOOTSTRAP_RUNTIME_MODEL_ID?null:createMockAuthoredRuntimeModel(e)}function createSkillLoadResult(e,t){let n=getLastUserPromptText(e);if(n===null||getActivatedSkillIds(e).length>0)return null;let r=findRelevantSkill(getAvailableSkills(e),n);return r===null?null:createToolCallGenerateResult({input:{skill:r.name},inputTokens:estimateTokenCount(getPromptText(e)),modelId:t,outputTokens:estimateTokenCount(r.name),toolCallId:`call_load_skill`,toolName:LOAD_SKILL_TOOL_NAME})}const SUBAGENT_DELEGATION_DIRECTIVE=/\bdelegate\s+(?:(through\s+workflow)\s+)?to\s+a\s+subagent\s*:\s*(.+)$/iu,PARALLEL_AUTHORED_TOOLS_DIRECTIVE=/^call tools in parallel:\s*(.+)$/imu;function createParallelAuthoredToolCallsResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null)return null;let r=PARALLEL_AUTHORED_TOOLS_DIRECTIVE.exec(n)?.[1]?.split(`,`).map(e=>e.trim()).filter(Boolean);if(r===void 0||r.length<2||new Set(r).size!==r.length)return null;let i=new Map(getAvailableTools(e).map(e=>[e.name,e])),a=[];for(let e of r){let t=i.get(e);if(t===void 0)return null;a.push(t)}let o=resolveWeatherCity(n);return createToolCallsGenerateResult({calls:a.map(e=>({input:createMockAuthoredToolInput(e,n,o),toolCallId:createToolCallId(e.name),toolName:e.name})),inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(n)})}function createSubagentDelegationResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null)return null;let r=SUBAGENT_DELEGATION_DIRECTIVE.exec(n);if(r?.[2]===void 0)return null;let i=r[1]===void 0?`agent`:`Workflow`;if(getAvailableTools(e).find(e=>e.name===i)===void 0)return null;let a=r[2].trim();return createToolCallGenerateResult({input:i===`Workflow`?{js:`return await tools.agent({ message: ${JSON.stringify(a)} });`}:{message:a},inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(a),toolCallId:createToolCallId(i),toolName:i})}function createAuthoredToolCallResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null||/^Background task task_[a-z0-9]+\b/iu.test(n))return null;let r=findRelevantTool(getAvailableTools(e),n);if(r===null)return null;let i=resolveWeatherCity(n),a=createMockAuthoredToolInput(r,n,i);return createToolCallGenerateResult({input:a,inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(Object.values(a).join(` `)),toolCallId:createToolCallId(r.name),toolName:r.name})}function createFollowUpToolCallResult(e){let t=findNextExplicitToolAfterResult({previousToolName:e.result.toolName,prompt:e.options.prompt,tools:getAvailableTools(e.options)});if(t===null)return null;let n=createFollowUpToolInput(e.result.output);return n===null?null:createToolCallGenerateResult({input:n,inputTokens:estimateTokenCount(getPromptText(e.options.prompt)),modelId:e.modelId,outputTokens:estimateTokenCount(Object.values(n).join(` `)),toolCallId:createToolCallId(t.name),toolName:t.name})}function createAssistantMessage(e){let t=getLastUserPromptText(e)??`Hello from eve`,n=getSystemPromptLabels(e),r=resolveSystemProbe(e),i=resolveMockFixtureToken(e);return i===null?n.length>0?r===null?`Bootstrap reply [${n.join(`, `)}]: ${t}`:`Bootstrap reply [${n.join(`, `)}; probe=${r}]: ${t}`:r===null?`Bootstrap reply: ${t}`:`Bootstrap reply [probe=${r}]: ${t}`:i}function formatToolResultReply(e,t){if(e.isError)return`Local weather tool failed: ${formatToolOutput(e.output)}`;if(isWeatherPayload(e.output))return`Used local weather tool for ${e.output.city}: ${e.output.condition}, ${e.output.temperatureF}F. ${e.output.summary}`;let n=getLastUserPromptText(t)??`Hello from eve`;return`Used ${e.toolName} for "${n}": ${formatToolOutput(e.output)}`}function createToolCallGenerateResult(e){return createToolCallsGenerateResult({calls:[{input:e.input,toolCallId:e.toolCallId,toolName:e.toolName}],inputTokens:e.inputTokens,modelId:e.modelId,outputTokens:e.outputTokens})}function createToolCallsGenerateResult(e){return{content:e.calls.map(e=>({input:JSON.stringify(e.input),toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-call`})),finishReason:{raw:void 0,unified:`tool-calls`},response:{id:`bootstrap-response`,modelId:e.modelId,timestamp:new Date(`2026-03-16T00:00:00.000Z`)},usage:{inputTokens:{cacheRead:0,cacheWrite:0,noCache:e.inputTokens,total:e.inputTokens},outputTokens:{reasoning:0,text:e.outputTokens,total:e.outputTokens}},warnings:[]}}function getAvailableTools(e){return(e.tools??[]).flatMap(e=>e.type===`function`?[{description:e.description,inputSchema:`inputSchema`in e?e.inputSchema:void 0,name:e.name,outputSchema:`outputSchema`in e?e.outputSchema:void 0}]:[])}function getLastAuthoredToolResult(e){for(let t of[...e].reverse()){if(t.role===`user`){if(isAgentsAnnouncementText(getPromptContentText(t.content).trim()))continue;return null}if(t.role===`tool`||t.role===`assistant`){for(let e of[...t.content].reverse())if(typeof e!=`string`&&e.type===`tool-result`&&e.toolName!==LOAD_SKILL_TOOL_NAME)return{isError:e.output.type===`error-json`||e.output.type===`error-text`||e.output.type===`execution-denied`,output:e.output.type===`execution-denied`?{reason:e.output.reason??null,type:e.output.type}:e.output.value,toolCallId:e.toolCallId,toolName:e.toolName}}}return null}function findNextExplicitToolAfterResult(e){let t=getLastUserPromptText(e.prompt);if(t===null)return null;let n=normalizeText(t),r=n.indexOf(normalizeText(e.previousToolName));return r<0?null:e.tools.filter(t=>t.name!==e.previousToolName).flatMap(e=>{let t=n.indexOf(normalizeText(e.name),r+1);return t<0?[]:[{index:t,tool:e}]}).sort((e,t)=>e.index-t.index)[0]?.tool??null}function createFollowUpToolInput(e){return isRecord(e)&&typeof e.stepKey==`string`?{stepKey:e.stepKey}:null}function getSystemPromptLabels(e){let t=e.filter(e=>e.role===`system`);if(t.length===0)return[];let n=t.flatMap(e=>{let t=getPromptContentText(e.content);if(t.startsWith(`Available skills
1
+ import{z}from"#compiled/zod/index.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{MockLanguageModelV3}from"ai/test";import{FINAL_OUTPUT_TOOL_NAME}from"#harness/final-output.js";import{BOOTSTRAP_RUNTIME_MODEL_ID,BOOTSTRAP_RUNTIME_SYSTEM_PROMPT}from"#runtime/agent/bootstrap.js";import{createBootstrapGenerateResult,createBootstrapStreamResult,estimateTokenCount,getLastUserPromptText,getPromptContentText,getPromptText,isAgentsAnnouncementText}from"#runtime/agent/bootstrap-model-utils.js";import{createMockAuthoredToolInput,formatToolOutput,resolveMockFixtureToken,resolveWeatherCity}from"#runtime/agent/mock-model-fixtures.js";import{findRelevantSkill,getActivatedSkillIds,getAvailableSkills}from"#runtime/agent/mock-model-skill-selection.js";import{createJsonSchemaSample}from"#runtime/agent/mock-structured-output.js";const authoredRuntimeModelMocks=new Map,bootstrapWeatherPayloadSchema=z.object({city:z.string(),condition:z.string(),summary:z.string(),temperatureF:z.number().finite()}).strict();function shouldMockAuthoredRuntimeModels(){return process.env.NODE_ENV===`test`||process.env.EVE_MOCK_AUTHORED_MODELS===`1`}function createMockAuthoredRuntimeModel(e){let t=authoredRuntimeModelMocks.get(e.id);if(t!==void 0)return t;let n=new MockLanguageModelV3({modelId:e.id,provider:`eve-runtime-mock`,doGenerate:async t=>createMockModelResult(t,e.id),doStream:async t=>createBootstrapStreamResult(createMockModelResult(t,e.id))});return authoredRuntimeModelMocks.set(e.id,n),n}function createMockModelResult(e,t){let n=getLastAuthoredToolResult(e.prompt);if(n!==null){let r=createFollowUpToolCallResult({modelId:t,options:e,result:n});if(r!==null)return r}else{let n=createParallelAuthoredToolCallsResult(e,t)??createSubagentDelegationResult(e,t)??createSkillLoadResult(e.prompt,t)??createAuthoredToolCallResult(e,t);if(n!==null)return n}let r=createFinalOutputResult(e,t);if(r!==null)return r;let i=n===null?createAssistantMessage(e.prompt):formatToolResultReply(n,e.prompt);return createBootstrapGenerateResult({inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(i),text:i})}function createFinalOutputResult(e,t){let n=getAvailableTools(e).find(e=>e.name===FINAL_OUTPUT_TOOL_NAME);if(n===void 0)return null;let r=createJsonSchemaSample(n.inputSchema);return createToolCallGenerateResult({input:r,inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(JSON.stringify(r)),toolCallId:createToolCallId(FINAL_OUTPUT_TOOL_NAME),toolName:FINAL_OUTPUT_TOOL_NAME})}function resolveMockAuthoredRuntimeModel(e){return!shouldMockAuthoredRuntimeModels()||e.id===BOOTSTRAP_RUNTIME_MODEL_ID?null:createMockAuthoredRuntimeModel(e)}function createSkillLoadResult(e,t){let n=getLastUserPromptText(e);if(n===null||getActivatedSkillIds(e).length>0)return null;let r=findRelevantSkill(getAvailableSkills(e),n);return r===null?null:createToolCallGenerateResult({input:{skill:r.name},inputTokens:estimateTokenCount(getPromptText(e)),modelId:t,outputTokens:estimateTokenCount(r.name),toolCallId:`call_load_skill`,toolName:LOAD_SKILL_TOOL_NAME})}const SUBAGENT_DELEGATION_DIRECTIVE=/\bdelegate\s+to\s+a\s+subagent\s*:\s*(.+)$/iu,PARALLEL_AUTHORED_TOOLS_DIRECTIVE=/^call tools in parallel:\s*(.+)$/imu;function createParallelAuthoredToolCallsResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null)return null;let r=PARALLEL_AUTHORED_TOOLS_DIRECTIVE.exec(n)?.[1]?.split(`,`).map(e=>e.trim()).filter(Boolean);if(r===void 0||r.length<2||new Set(r).size!==r.length)return null;let i=new Map(getAvailableTools(e).map(e=>[e.name,e])),a=[];for(let e of r){let t=i.get(e);if(t===void 0)return null;a.push(t)}let o=resolveWeatherCity(n);return createToolCallsGenerateResult({calls:a.map(e=>({input:createMockAuthoredToolInput(e,n,o),toolCallId:createToolCallId(e.name),toolName:e.name})),inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(n)})}function createSubagentDelegationResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null)return null;let r=SUBAGENT_DELEGATION_DIRECTIVE.exec(n);if(r?.[1]===void 0)return null;let i=`agent`;if(getAvailableTools(e).find(e=>e.name===i)===void 0)return null;let a=r[1].trim();return createToolCallGenerateResult({input:{message:a},inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(a),toolCallId:createToolCallId(i),toolName:i})}function createAuthoredToolCallResult(e,t){let n=getLastUserPromptText(e.prompt);if(n===null||/^Background task task_[a-z0-9]+\b/iu.test(n))return null;let r=findRelevantTool(getAvailableTools(e),n);if(r===null)return null;let i=resolveWeatherCity(n),a=createMockAuthoredToolInput(r,n,i);return createToolCallGenerateResult({input:a,inputTokens:estimateTokenCount(getPromptText(e.prompt)),modelId:t,outputTokens:estimateTokenCount(Object.values(a).join(` `)),toolCallId:createToolCallId(r.name),toolName:r.name})}function createFollowUpToolCallResult(e){let t=findNextExplicitToolAfterResult({previousToolName:e.result.toolName,prompt:e.options.prompt,tools:getAvailableTools(e.options)});if(t===null)return null;let n=createFollowUpToolInput(e.result.output);return n===null?null:createToolCallGenerateResult({input:n,inputTokens:estimateTokenCount(getPromptText(e.options.prompt)),modelId:e.modelId,outputTokens:estimateTokenCount(Object.values(n).join(` `)),toolCallId:createToolCallId(t.name),toolName:t.name})}function createAssistantMessage(e){let t=getLastUserPromptText(e)??`Hello from eve`,n=getSystemPromptLabels(e),r=resolveSystemProbe(e),i=resolveMockFixtureToken(e);return i===null?n.length>0?r===null?`Bootstrap reply [${n.join(`, `)}]: ${t}`:`Bootstrap reply [${n.join(`, `)}; probe=${r}]: ${t}`:r===null?`Bootstrap reply: ${t}`:`Bootstrap reply [probe=${r}]: ${t}`:i}function formatToolResultReply(e,t){if(e.isError)return`Local weather tool failed: ${formatToolOutput(e.output)}`;if(isWeatherPayload(e.output))return`Used local weather tool for ${e.output.city}: ${e.output.condition}, ${e.output.temperatureF}F. ${e.output.summary}`;let n=getLastUserPromptText(t)??`Hello from eve`;return`Used ${e.toolName} for "${n}": ${formatToolOutput(e.output)}`}function createToolCallGenerateResult(e){return createToolCallsGenerateResult({calls:[{input:e.input,toolCallId:e.toolCallId,toolName:e.toolName}],inputTokens:e.inputTokens,modelId:e.modelId,outputTokens:e.outputTokens})}function createToolCallsGenerateResult(e){return{content:e.calls.map(e=>({input:JSON.stringify(e.input),toolCallId:e.toolCallId,toolName:e.toolName,type:`tool-call`})),finishReason:{raw:void 0,unified:`tool-calls`},response:{id:`bootstrap-response`,modelId:e.modelId,timestamp:new Date(`2026-03-16T00:00:00.000Z`)},usage:{inputTokens:{cacheRead:0,cacheWrite:0,noCache:e.inputTokens,total:e.inputTokens},outputTokens:{reasoning:0,text:e.outputTokens,total:e.outputTokens}},warnings:[]}}function getAvailableTools(e){return(e.tools??[]).flatMap(e=>e.type===`function`?[{description:e.description,inputSchema:`inputSchema`in e?e.inputSchema:void 0,name:e.name,outputSchema:`outputSchema`in e?e.outputSchema:void 0}]:[])}function getLastAuthoredToolResult(e){for(let t of[...e].reverse()){if(t.role===`user`){if(isAgentsAnnouncementText(getPromptContentText(t.content).trim()))continue;return null}if(t.role===`tool`||t.role===`assistant`){for(let e of[...t.content].reverse())if(typeof e!=`string`&&e.type===`tool-result`&&e.toolName!==LOAD_SKILL_TOOL_NAME)return{isError:e.output.type===`error-json`||e.output.type===`error-text`||e.output.type===`execution-denied`,output:e.output.type===`execution-denied`?{reason:e.output.reason??null,type:e.output.type}:e.output.value,toolCallId:e.toolCallId,toolName:e.toolName}}}return null}function findNextExplicitToolAfterResult(e){let t=getLastUserPromptText(e.prompt);if(t===null)return null;let n=normalizeText(t),r=n.indexOf(normalizeText(e.previousToolName));return r<0?null:e.tools.filter(t=>t.name!==e.previousToolName).flatMap(e=>{let t=n.indexOf(normalizeText(e.name),r+1);return t<0?[]:[{index:t,tool:e}]}).sort((e,t)=>e.index-t.index)[0]?.tool??null}function createFollowUpToolInput(e){return isRecord(e)&&typeof e.stepKey==`string`?{stepKey:e.stepKey}:null}function getSystemPromptLabels(e){let t=e.filter(e=>e.role===`system`);if(t.length===0)return[];let n=t.flatMap(e=>{let t=getPromptContentText(e.content);if(t.startsWith(`Available skills
2
2
  `))return[];let n=t.split(`
3
3
  `).map(e=>e.trim()).filter(e=>e.length>0),r=[];for(let e of n){if(e===BOOTSTRAP_RUNTIME_SYSTEM_PROMPT||e===`Available skills`)continue;let t=/^System \((.+)\)$/.exec(e);if(t?.[1]){r.push(t[1]);continue}let n=/^Skill \((.+)\)$/.exec(e);n?.[1]&&r.push(n[1])}if(r.length>0)return r;let i=n.find(e=>e!==BOOTSTRAP_RUNTIME_SYSTEM_PROMPT&&e!==`Available skills`);return i===void 0?[]:[i]});return[...new Set(n)]}function findRelevantTool(e,t){let n=normalizeText(t),r=e.find(e=>e.name!==`agent`&&e.name!==LOAD_SKILL_TOOL_NAME&&n.includes(normalizeText(e.name)));return r===void 0?/\b(forecast|temperature|weather|wind|rain|snow)\b/u.test(n)?e.find(e=>/\b(forecast|temperature|weather|wind|rain|snow)\b/u.test(normalizeText(`${e.name} ${e.description??``}`)))??null:null:r}function normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,` `).trim()}function createToolCallId(e){return`call_${e.toLowerCase().replace(/[^a-z0-9]+/gu,`_`).replace(/^_+|_+$/gu,``)||`tool`}`}function resolveSystemProbe(e){let t=e.filter(e=>e.role===`system`).map(e=>getPromptContentText(e.content)).join(`
4
4
  `);return/hmr-probe:\s*([^\n]+)/iu.exec(t)?.[1]?.trim()||null}function isWeatherPayload(e){return z.validate(bootstrapWeatherPayloadSchema,e)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{createMockAuthoredRuntimeModel,resolveMockAuthoredRuntimeModel,shouldMockAuthoredRuntimeModels};
@@ -20,10 +20,8 @@ import type { TokenResult } from "#shared/connection-types.js";
20
20
  * Virtual context key mapping authorization scope to a per-principal
21
21
  * {@link TokenResult} cache.
22
22
  *
23
- * The principal sub-key is produced by
24
- * {@link principalKey} so identical string keys (for example
25
- * `"user:${issuer}:${id}"`) collide only when the resolved principal
26
- * genuinely matches.
23
+ * The principal sub-key is produced by {@link principalKey}, so JSON tuple
24
+ * encoding only collides when the resolved principal genuinely matches.
27
25
  */
28
26
  export declare const ConnectionAuthorizationTokensKey: ContextKey<Readonly<Record<string, Readonly<Record<string, TokenResult>>>>>;
29
27
  /**
@@ -1 +1 @@
1
- import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{ConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpConnectionClient=class{#e;#t;#n;#r;#i;constructor(e){this.#i=e}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let e=await resolveHeaders(this.#i),t=this.#i.url;try{return await createMCPClient({transport:{type:`http`,url:t,headers:e}})}catch(n){if(!isMcpHttpFallbackRetryableError(n))throw n;return await createMCPClient({transport:{type:`sse`,url:t,headers:e}})}}async getToolMetadata(){return(await this.#o()).metadata}async getTools(){return(await this.#o()).tools}async executeTool(e,t,n){try{let{tools:r}=await this.#o(),i=r[e];if(i?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let a=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});return await i.execute(a,{abortSignal:n.abortSignal})}catch(e){return await this.#l(e)}}async#o(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#s();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#s(){try{return await this.#c()}catch(e){return await this.#l(e)}}async#c(){let e=await this.connect(),t=await e.listTools(),n=this.#i.tools,r=n===void 0?t.tools:t.tools.filter(e=>passesToolFilter(e.name,n)),i=Object.keys(this.#i.toolCall?.providedArguments??{}),a=r.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,i)})),o=e.toolsFromDefinitions({tools:a});return{metadata:a.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:o}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#l(e){throw isMcpAuthRequiredError(e)?(await this.#u(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (the server rejected the token).`})):e}async#u(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?t.allow.includes(e):!t.block.includes(e)}async function resolveHeaders(e){let t={},n,getCallbackContext=()=>n??=buildCallbackContext(),r=await resolveConnectionAuthorization(e,typeof e.authorization==`function`?getCallbackContext():void 0);if(r!==void 0&&(t.Authorization=`Bearer ${(await resolveToken(e,r)).token}`),e.headers!==void 0){let n=await resolveHeadersDefinition(e.headers,getCallbackContext);for(let[i,a]of Object.entries(n)){if(r!==void 0&&i.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);t[i]=a}}return t}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{McpConnectionClient,isMcpAuthRequiredError,passesToolFilter,resolveHeaders};
1
+ import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{ConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpConnectionClient=class{#e;#t;#n;#r;#i;constructor(e){this.#i=e}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let e=await resolveHeaders(this.#i),t=this.#i.url;try{return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{type:`http`,url:t,headers:e}})}catch(n){if(!isMcpHttpFallbackRetryableError(n))throw n;return await createMCPClient({protocolVersionDiscovery:this.#i.protocolVersionDiscovery,transport:{type:`sse`,url:t,headers:e}})}}async getToolMetadata(){return(await this.#o()).metadata}async getTools(){return(await this.#o()).tools}async executeTool(e,t,n){try{let{tools:r}=await this.#o(),i=r[e];if(i?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let a=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});return await i.execute(a,{abortSignal:n.abortSignal})}catch(e){return await this.#l(e)}}async#o(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#s();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#s(){try{return await this.#c()}catch(e){return await this.#l(e)}}async#c(){let e=await this.connect(),t=await e.listTools(),n=this.#i.tools,r=n===void 0?t.tools:t.tools.filter(e=>passesToolFilter(e.name,n)),i=Object.keys(this.#i.toolCall?.providedArguments??{}),a=r.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,i)})),o=e.toolsFromDefinitions({tools:a});return{metadata:a.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:o}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#l(e){throw isMcpAuthRequiredError(e)?(await this.#u(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (the server rejected the token).`})):e}async#u(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?t.allow.includes(e):!t.block.includes(e)}async function resolveHeaders(e){let t={},n,getCallbackContext=()=>n??=buildCallbackContext(),r=await resolveConnectionAuthorization(e,typeof e.authorization==`function`?getCallbackContext():void 0);if(r!==void 0&&(t.Authorization=`Bearer ${(await resolveToken(e,r)).token}`),e.headers!==void 0){let n=await resolveHeadersDefinition(e.headers,getCallbackContext);for(let[i,a]of Object.entries(n)){if(r!==void 0&&i.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);t[i]=a}}return t}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{McpConnectionClient,isMcpAuthRequiredError,passesToolFilter,resolveHeaders};
@@ -17,12 +17,12 @@ import type { AuthorizationDefinition, ConnectionPrincipal } from "#shared/conne
17
17
  * per-principal token cache.
18
18
  *
19
19
  * - `{ type: "app" }` → `"app"`. Shared across all sessions.
20
- * - `{ type: "user", issuer, id }` → `"user:${issuer}:${id}"`. The
21
- * issuer prefix prevents collisions when the same `id` across
22
- * identity providers (for example Slack `U123` vs Google `U123`)
23
- * would otherwise alias to the same cache slot.
24
- * - `{ type: "user", id }` → `"user:${id}"`. This is the native
25
- * Vercel Connect user projection.
20
+ * - `{ type: "user", issuer, id }` → `["user", issuer, id]` JSON.
21
+ * - `{ type: "user", id }` → `["user", null, id]` JSON. This is the
22
+ * native Vercel Connect user projection.
23
+ *
24
+ * JSON tuple encoding preserves the boundaries between issuer and id, so
25
+ * user-provided separators and percent sequences cannot alias cache entries.
26
26
  */
27
27
  export declare function principalKey(principal: ConnectionPrincipal): string;
28
28
  /**
@@ -1 +1 @@
1
- import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{contextStorage}from"#context/container.js";import{AuthKey}from"#context/keys.js";import{ConnectionAuthorizationFailedError}from"#connections/errors.js";function principalKey(e){return e.type===`app`?`app`:e.issuer===void 0?`user:${e.id}`:`user:${e.issuer}:${e.id}`}function resolveConnectionPrincipal(e,t,n=contextStorage.getStore()){return resolveConnectionPrincipalFromAuth(e,t,n?.get(AuthKey),n)}function resolveConnectionPrincipalFromAuth(e,t,n,r){if(t.principalType===`app`)return{type:`app`};if(n==null||n.principalType!==`user`)throw new ConnectionAuthorizationFailedError(e,{message:buildUserPrincipalRequiredMessage(e,t,r,n),reason:`principal_required`,retryable:!1});return t.vercelConnect!==void 0&&isVercelDevelopmentUser(n)?{attributes:n.attributes,id:n.subject??n.principalId,type:`user`}:{attributes:n.attributes,id:n.principalId,issuer:n.issuer??n.authenticator,type:`user`}}function isVercelDevelopmentUser(e){return e.authenticator===`oidc`&&isVercelOidcIssuer(e.issuer)&&e.attributes.environment===`development`&&e.subject===e.attributes.user_id}function buildUserPrincipalRequiredMessage(e,t,n,r){let i;return i=n===void 0?`it was invoked outside an eve context, so no authenticated user can be resolved.`:r==null?`the active session has no authenticated user.`:t.vercelConnect!==void 0&&r.authenticator===`local-dev`?`the local request fell back to local development access instead of authenticating a Vercel user. Ensure this directory is linked and the Vercel CLI can mint a Vercel OIDC token, then retry.`:`the active session is scoped to "${r.principalType}", not an authenticated user.`,`Connection "${e}" is user-scoped, but ${i} User-scoped connections require route auth that resolves an authenticated user. If this connection should use credentials shared by the agent instead, configure it as an app-scoped connection.`}export{principalKey,resolveConnectionPrincipal,resolveConnectionPrincipalFromAuth};
1
+ import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{contextStorage}from"#context/container.js";import{AuthKey}from"#context/keys.js";import{ConnectionAuthorizationFailedError}from"#connections/errors.js";function principalKey(e){return e.type===`app`?`app`:JSON.stringify([`user`,e.issuer??null,e.id])}function resolveConnectionPrincipal(e,t,n=contextStorage.getStore()){return resolveConnectionPrincipalFromAuth(e,t,n?.get(AuthKey),n)}function resolveConnectionPrincipalFromAuth(e,t,n,r){if(t.principalType===`app`)return{type:`app`};if(n==null||n.principalType!==`user`)throw new ConnectionAuthorizationFailedError(e,{message:buildUserPrincipalRequiredMessage(e,t,r,n),reason:`principal_required`,retryable:!1});return t.vercelConnect!==void 0&&isVercelDevelopmentUser(n)?{attributes:n.attributes,id:n.subject??n.principalId,type:`user`}:{attributes:n.attributes,id:n.principalId,issuer:n.issuer??n.authenticator,type:`user`}}function isVercelDevelopmentUser(e){return e.authenticator===`oidc`&&isVercelOidcIssuer(e.issuer)&&e.attributes.environment===`development`&&e.subject===e.attributes.user_id}function buildUserPrincipalRequiredMessage(e,t,n,r){let i;return i=n===void 0?`it was invoked outside an eve context, so no authenticated user can be resolved.`:r==null?`the active session has no authenticated user.`:t.vercelConnect!==void 0&&r.authenticator===`local-dev`?`the local request fell back to local development access instead of authenticating a Vercel user. Ensure this directory is linked and the Vercel CLI can mint a Vercel OIDC token, then retry.`:`the active session is scoped to "${r.principalType}", not an authenticated user.`,`Connection "${e}" is user-scoped, but ${i} User-scoped connections require route auth that resolves an authenticated user. If this connection should use credentials shared by the agent instead, configure it as an app-scoped connection.`}export{principalKey,resolveConnectionPrincipal,resolveConnectionPrincipalFromAuth};
@@ -1 +1 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{validateCompiledModuleMap}from"#compiler/validate-artifact.js";import{createRuntimeSubagentRegistry}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{createRuntimeToolRegistry}from"#runtime/tools/registry.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createResolvedRuntimeTurnAgent}from"#runtime/agent/bootstrap.js";import{createWorkspacePromptSection}from"#runtime/workspace/spec.js";import{createRuntimeHookRegistry}from"#runtime/hooks/registry.js";import{resolveAgent}from"#runtime/resolve-agent.js";import{resolveDynamicSubagentDefinition}from"#runtime/resolve-dynamic-subagent.js";import{createRuntimeSandboxRegistry}from"#runtime/sandbox/registry.js";var ResolveRuntimeAgentGraphError=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function resolveRuntimeAgentGraph(e){validateCompiledModuleMap(e.manifest,e.moduleMap);let t=new Map,n=createChildNodeIdsByParentNodeId(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e])),i=await resolveRuntimeAgentNode({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:ROOT_COMPILED_AGENT_NODE_ID,nodesByNodeId:t,subagentNodesById:r});return attachInheritedSandboxWorkspaceResources({manifest:e.manifest,nodesByNodeId:t}),{nodesByNodeId:t,root:i}}async function resolveRuntimeAgentNode(e){let t=toRuntimeNodeId(e.nodeId);if(e.nodesByNodeId.has(t))throw new ResolveRuntimeAgentGraphError(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await resolveAgent({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=await createRuntimeToolRegistry({tools:n.tools},{nodeId:t,reservedToolNames:[WORKFLOW_TOOL_NAME]}),i=createRuntimeSandboxRegistry({sandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),a=createRuntimeSubagentRegistry({reservedToolNames:[LOAD_SKILL_TOOL_NAME,...r.preparedTools.map(e=>e.name)],subagents:await resolveRuntimeSubagents({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.manifest,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),o={agent:n,channels:n.channels,hookRegistry:createRuntimeHookRegistry(n.hooks),nodeId:t,sandboxRegistry:i,sourceId:e.sourceId,subagentRegistry:a,toolRegistry:r,turnAgent:createResolvedRuntimeTurnAgent({agent:n,dynamicSubagentsAvailable:a.dynamicResolvers.length>0,id:e.agentId,nodeId:t,tools:[...r.preparedTools,...a.preparedTools]})};return e.nodesByNodeId.set(t,o),o}async function resolveRuntimeSubagents(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new ResolveRuntimeAgentGraphError(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:toRuntimeNodeId(e.parentNodeId),sourceId:r});t.push(await resolveRuntimeSubagent({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}for(let n of e.manifest.remoteAgents)t.push(await resolveRuntimeRemoteAgent({moduleMap:e.moduleMap,nodeScopeId:e.parentNodeId,sourceRef:n}));return t}async function resolveRuntimeSubagent(e){let t={...e.sourceRef.configResolver===void 0?{description:e.sourceRef.description}:{dynamic:await resolveDynamicSubagentDefinition({definition:e.sourceRef.configResolver,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId})},kind:`subagent`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:toRuntimeNodeId(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await resolveRuntimeAgentNode({agentId:e.sourceRef.name,childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}async function resolveRuntimeRemoteAgent(e){let t=await loadResolvedModuleExport({definition:e.sourceRef,kindLabel:`remote agent`,moduleMap:e.moduleMap,nodeId:e.nodeScopeId}),n=expectObjectRecord(t,`Expected remote agent source "${e.sourceRef.logicalPath}" to export an object.`),r={description:e.sourceRef.description,kind:`remote`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:toRuntimeNodeId(e.sourceRef.nodeId),outputSchema:e.sourceRef.outputSchema,path:e.sourceRef.path,sourceId:e.sourceRef.sourceId,sourceKind:`module`,url:await resolveRemoteAgentUrl({bakedUrl:e.sourceRef.url,logicalPath:e.sourceRef.logicalPath,resolvedUrl:n.url})};typeof n.auth==`function`&&(r.auth=n.auth),n.forwardPrincipal===!0&&(r.forwardPrincipal=!0);let i=resolveRemoteAgentHeaders(n.headers);return i!==void 0&&(r.headers=i),r}async function resolveRemoteAgentUrl(e){if(typeof e.resolvedUrl==`function`){let t=await e.resolvedUrl();if(typeof t!=`string`||t.length===0)throw Error(`Remote agent "${e.logicalPath}" url function must return a non-empty string.`);return t}let t=e.bakedUrl??(typeof e.resolvedUrl==`string`?e.resolvedUrl:``);if(t.length===0)throw Error(`Remote agent "${e.logicalPath}" is missing a url.`);return t}function resolveRemoteAgentHeaders(e){if(e===void 0)return;if(typeof e==`function`)return e;if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function attachInheritedSandboxWorkspaceResources(e){let t=new Map(e.manifest.subagents.map(e=>[e.nodeId,e.parentNodeId]));for(let[n,r]of e.nodesByNodeId){if(r.sandboxRegistry.sandbox.definition.inheritsParent!==!0)continue;if(r.agent.dynamicSkillResolvers.length>0)throw new ResolveRuntimeAgentGraphError(`Sandbox "${r.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${n}" defines dynamic skills. Remove the child dynamic skills or give the child its own sandbox.`,{nodeId:n});let i=t.get(n);if(i===void 0)throw new ResolveRuntimeAgentGraphError(`Sandbox "${r.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${n}" has no parent.`,{nodeId:n});let a=resolveSandboxOwnerNode({nodeId:i,nodesByNodeId:e.nodesByNodeId,parentNodeIdByChildNodeId:t});r.sandboxRegistry.sandbox.inheritance={definition:a.sandboxRegistry.sandbox.definition,nodeId:a.nodeId,workspaceResourceRoot:a.sandboxRegistry.sandbox.workspaceResourceRoot};let o=createWorkspacePromptSection(a.agent.workspaceSpec);o!==void 0&&(r.turnAgent.instructions=[...r.turnAgent.instructions,o])}}function resolveSandboxOwnerNode(e){let t=e.nodesByNodeId.get(toRuntimeNodeId(e.nodeId));if(t===void 0)throw new ResolveRuntimeAgentGraphError(`Missing parent runtime node "${e.nodeId}".`,{nodeId:e.nodeId});if(t.sandboxRegistry.sandbox.definition.inheritsParent!==!0)return t;let n=e.parentNodeIdByChildNodeId.get(e.nodeId);if(n===void 0)throw new ResolveRuntimeAgentGraphError(`Inherited sandbox node "${e.nodeId}" has no parent.`,{nodeId:e.nodeId});return resolveSandboxOwnerNode({...e,nodeId:n})}function createChildNodeIdsByParentNodeId(e){let t=new Map;for(let n of e.subagents){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.nodeId]);continue}e.push(n.nodeId)}return t}function toRuntimeNodeId(e){return e===ROOT_COMPILED_AGENT_NODE_ID?ROOT_RUNTIME_AGENT_NODE_ID:e}export{resolveRuntimeAgentGraph};
1
+ import{expectObjectRecord}from"#internal/authored-module.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{validateCompiledModuleMap}from"#compiler/validate-artifact.js";import{createRuntimeSubagentRegistry}from"#runtime/subagents/registry.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{createRuntimeToolRegistry}from"#runtime/tools/registry.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createResolvedRuntimeTurnAgent}from"#runtime/agent/bootstrap.js";import{createWorkspacePromptSection}from"#runtime/workspace/spec.js";import{createRuntimeHookRegistry}from"#runtime/hooks/registry.js";import{resolveAgent}from"#runtime/resolve-agent.js";import{resolveDynamicSubagentDefinition}from"#runtime/resolve-dynamic-subagent.js";import{createRuntimeSandboxRegistry}from"#runtime/sandbox/registry.js";var ResolveRuntimeAgentGraphError=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function resolveRuntimeAgentGraph(e){validateCompiledModuleMap(e.manifest,e.moduleMap);let t=new Map,n=createChildNodeIdsByParentNodeId(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e])),i=await resolveRuntimeAgentNode({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:ROOT_COMPILED_AGENT_NODE_ID,nodesByNodeId:t,subagentNodesById:r});return attachInheritedSandboxWorkspaceResources({manifest:e.manifest,nodesByNodeId:t}),{nodesByNodeId:t,root:i}}async function resolveRuntimeAgentNode(e){let t=toRuntimeNodeId(e.nodeId);if(e.nodesByNodeId.has(t))throw new ResolveRuntimeAgentGraphError(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await resolveAgent({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=await createRuntimeToolRegistry({tools:n.tools},{nodeId:t}),i=createRuntimeSandboxRegistry({sandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),a=createRuntimeSubagentRegistry({reservedToolNames:[LOAD_SKILL_TOOL_NAME,...r.preparedTools.map(e=>e.name)],subagents:await resolveRuntimeSubagents({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.manifest,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),o={agent:n,channels:n.channels,hookRegistry:createRuntimeHookRegistry(n.hooks),nodeId:t,sandboxRegistry:i,sourceId:e.sourceId,subagentRegistry:a,toolRegistry:r,turnAgent:createResolvedRuntimeTurnAgent({agent:n,dynamicSubagentsAvailable:a.dynamicResolvers.length>0,id:e.agentId,nodeId:t,tools:[...r.preparedTools,...a.preparedTools]})};return e.nodesByNodeId.set(t,o),o}async function resolveRuntimeSubagents(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new ResolveRuntimeAgentGraphError(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:toRuntimeNodeId(e.parentNodeId),sourceId:r});t.push(await resolveRuntimeSubagent({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}for(let n of e.manifest.remoteAgents)t.push(await resolveRuntimeRemoteAgent({moduleMap:e.moduleMap,nodeScopeId:e.parentNodeId,sourceRef:n}));return t}async function resolveRuntimeSubagent(e){let t={...e.sourceRef.configResolver===void 0?{description:e.sourceRef.description}:{dynamic:await resolveDynamicSubagentDefinition({definition:e.sourceRef.configResolver,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId})},kind:`subagent`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:toRuntimeNodeId(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await resolveRuntimeAgentNode({agentId:e.sourceRef.name,childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}async function resolveRuntimeRemoteAgent(e){let t=await loadResolvedModuleExport({definition:e.sourceRef,kindLabel:`remote agent`,moduleMap:e.moduleMap,nodeId:e.nodeScopeId}),n=expectObjectRecord(t,`Expected remote agent source "${e.sourceRef.logicalPath}" to export an object.`),r={description:e.sourceRef.description,kind:`remote`,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:toRuntimeNodeId(e.sourceRef.nodeId),outputSchema:e.sourceRef.outputSchema,path:e.sourceRef.path,sourceId:e.sourceRef.sourceId,sourceKind:`module`,url:await resolveRemoteAgentUrl({bakedUrl:e.sourceRef.url,logicalPath:e.sourceRef.logicalPath,resolvedUrl:n.url})};typeof n.auth==`function`&&(r.auth=n.auth),n.forwardPrincipal===!0&&(r.forwardPrincipal=!0);let i=resolveRemoteAgentHeaders(n.headers);return i!==void 0&&(r.headers=i),r}async function resolveRemoteAgentUrl(e){if(typeof e.resolvedUrl==`function`){let t=await e.resolvedUrl();if(typeof t!=`string`||t.length===0)throw Error(`Remote agent "${e.logicalPath}" url function must return a non-empty string.`);return t}let t=e.bakedUrl??(typeof e.resolvedUrl==`string`?e.resolvedUrl:``);if(t.length===0)throw Error(`Remote agent "${e.logicalPath}" is missing a url.`);return t}function resolveRemoteAgentHeaders(e){if(e===void 0)return;if(typeof e==`function`)return e;if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function attachInheritedSandboxWorkspaceResources(e){let t=new Map(e.manifest.subagents.map(e=>[e.nodeId,e.parentNodeId]));for(let[n,r]of e.nodesByNodeId){if(r.sandboxRegistry.sandbox.definition.inheritsParent!==!0)continue;if(r.agent.dynamicSkillResolvers.length>0)throw new ResolveRuntimeAgentGraphError(`Sandbox "${r.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${n}" defines dynamic skills. Remove the child dynamic skills or give the child its own sandbox.`,{nodeId:n});let i=t.get(n);if(i===void 0)throw new ResolveRuntimeAgentGraphError(`Sandbox "${r.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${n}" has no parent.`,{nodeId:n});let a=resolveSandboxOwnerNode({nodeId:i,nodesByNodeId:e.nodesByNodeId,parentNodeIdByChildNodeId:t});r.sandboxRegistry.sandbox.inheritance={definition:a.sandboxRegistry.sandbox.definition,nodeId:a.nodeId,workspaceResourceRoot:a.sandboxRegistry.sandbox.workspaceResourceRoot};let o=createWorkspacePromptSection(a.agent.workspaceSpec);o!==void 0&&(r.turnAgent.instructions=[...r.turnAgent.instructions,o])}}function resolveSandboxOwnerNode(e){let t=e.nodesByNodeId.get(toRuntimeNodeId(e.nodeId));if(t===void 0)throw new ResolveRuntimeAgentGraphError(`Missing parent runtime node "${e.nodeId}".`,{nodeId:e.nodeId});if(t.sandboxRegistry.sandbox.definition.inheritsParent!==!0)return t;let n=e.parentNodeIdByChildNodeId.get(e.nodeId);if(n===void 0)throw new ResolveRuntimeAgentGraphError(`Inherited sandbox node "${e.nodeId}" has no parent.`,{nodeId:e.nodeId});return resolveSandboxOwnerNode({...e,nodeId:n})}function createChildNodeIdsByParentNodeId(e){let t=new Map;for(let n of e.subagents){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.nodeId]);continue}e.push(n.nodeId)}return t}function toRuntimeNodeId(e){return e===ROOT_COMPILED_AGENT_NODE_ID?ROOT_RUNTIME_AGENT_NODE_ID:e}export{resolveRuntimeAgentGraph};
@@ -1 +1 @@
1
- import{resolveConnectionDefinition}from"#runtime/resolve-connection.js";import{ResolveAgentError,createResolvedModuleSourceRef}from"#runtime/resolve-helpers.js";import{resolveChannelDefinition}from"#runtime/resolve-channel.js";import{resolveDynamicConnectionDefinition}from"#runtime/resolve-dynamic-connection.js";import{resolveHookDefinition}from"#runtime/resolve-hook.js";import{resolveSandboxDefinition}from"#runtime/resolve-sandbox.js";import{resolveDynamicInstructionsDefinition}from"#runtime/resolve-dynamic-instructions.js";import{resolveDynamicSkillDefinition}from"#runtime/resolve-dynamic-skill.js";import{resolveDynamicToolDefinition}from"#runtime/resolve-dynamic-tool.js";import{resolveToolDefinition}from"#runtime/resolve-tool.js";import{resolveMemoryDefinition}from"#runtime/resolve-memory.js";async function resolveAgent(e){let t=e.manifest.skills.map(t=>({...t,owner:requireCompiledSourceOwner(e.manifest,t),metadata:t.metadata===void 0?void 0:{...t.metadata}})),n=await Promise.all(e.manifest.channelRoutes.effective.map(t=>resolveChannelDefinition(t,e.moduleMap,e.nodeId))),r=await Promise.all(e.manifest.tools.map(t=>resolveToolDefinition(t,e.moduleMap,e.nodeId,requireBindingOwner(e.manifest,t.sourceId)))),i=await Promise.all(e.manifest.dynamicConnections.map(t=>resolveDynamicConnectionDefinition(t,e.moduleMap,e.nodeId))),a=await Promise.all((e.manifest.dynamicInstructions??[]).map(t=>resolveDynamicInstructionsDefinition(t,e.moduleMap,e.nodeId))),o=await Promise.all((e.manifest.dynamicSkills??[]).map(t=>resolveDynamicSkillDefinition(t,e.moduleMap,e.nodeId))),s=await Promise.all(e.manifest.dynamicTools.map(t=>resolveDynamicToolDefinition(t,e.moduleMap,e.nodeId))),c=await Promise.all(e.manifest.hooks.map(t=>resolveHookDefinition(t,e.moduleMap,e.nodeId))),l=await Promise.all(e.manifest.connections.map(t=>resolveConnectionDefinition(t,e.moduleMap,e.nodeId))),u=await Promise.all(e.manifest.memories.map(t=>resolveMemoryDefinition(t,e.moduleMap,e.nodeId))),d=await resolveSandboxDefinition(e.manifest.sandbox,e.moduleMap,e.nodeId),f=e.manifest.instructions.map(t=>createResolvedInstructionsDefinition(e.manifest,t)),p=e.manifest.workspaceResourceRoot,m={channels:n,connections:l,dynamicConnectionResolvers:i,workflowTool:e.manifest.workflowTool===void 0?void 0:{maxSubagents:e.manifest.workflowTool.maxSubagents},dynamicInstructionsResolvers:a,dynamicSkillResolvers:o,dynamicToolResolvers:s,hooks:c,instructions:f,metadata:{agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,diagnosticsSummary:e.manifest.diagnosticsSummary},memories:u,sandbox:d,workspaceResourceRoot:p,skills:t,tools:r,workspaceSpec:{rootEntries:[...p.rootEntries]}};return`config`in e.manifest?{...m,config:createResolvedAgentConfig(e.manifest)}:m}function requireBindingOwner(e,t){let n=e.bindings[t];if(n===void 0)throw Error(`Compiled source "${t}" has no binding.`);return n.owner}function createResolvedInstructionsDefinition(e,t){return{content:t.content,name:t.name,owner:requireCompiledSourceOwner(e,t),logicalPath:t.logicalPath,role:t.role,sourceId:t.sourceId,sourceKind:t.sourceKind}}function requireCompiledSourceOwner(e,t){let n=e.bindings[t.sourceId]?.owner??t.owner;if(n===void 0)throw Error(`Compiled source "${t.sourceId}" has no owner.`);return n}function createResolvedAgentConfig(e){let t={name:e.config.name};if(e.config.defaultTools!==void 0&&(t.defaultTools=e.config.defaultTools),e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,maxOutputTokens:e.config.compaction.model.maxOutputTokens,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,maxOutputTokens:e.config.compaction.model.maxOutputTokens,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}if(e.config.experimental!==void 0&&(t.experimental={instrumentationProviders:e.config.experimental.instrumentationProviders,workflow:e.config.experimental.workflow===void 0?void 0:{modelCallsPerStep:e.config.experimental.workflow.modelCallsPerStep,retention:e.config.experimental.workflow.retention,world:e.config.experimental.workflow.world}}),e.config.outputSchema!==void 0&&(t.outputSchema=e.config.outputSchema),e.config.reasoning!==void 0&&(t.reasoning=e.config.reasoning),e.config.source!==void 0&&(t.source=createResolvedModuleSourceRef(e.config.source)),e.config.limits!==void 0&&(t.limits={maxInputTokensPerSession:e.config.limits.maxInputTokensPerSession,maxOutputTokensPerSession:e.config.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:e.config.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:e.config.limits.sessionTimeoutMs}),e.config.dynamicModel!==void 0)return{...t,dynamicModel:{...createResolvedModuleSourceRef(e.config.dynamicModel),eventNames:[...e.config.dynamicModel.eventNames]}};let n=e.config.model;return{...t,model:n.source===void 0?{id:n.id,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens,providerOptions:n.providerOptions}:{contextWindowTokens:n.contextWindowTokens,id:n.id,maxOutputTokens:n.maxOutputTokens,providerOptions:n.providerOptions,source:{exportName:n.source.exportName,sourceKind:`module`,logicalPath:n.source.logicalPath,sourceId:n.source.sourceId}}}}export{ResolveAgentError,resolveAgent};
1
+ import{resolveConnectionDefinition}from"#runtime/resolve-connection.js";import{ResolveAgentError,createResolvedModuleSourceRef}from"#runtime/resolve-helpers.js";import{resolveChannelDefinition}from"#runtime/resolve-channel.js";import{resolveDynamicConnectionDefinition}from"#runtime/resolve-dynamic-connection.js";import{resolveHookDefinition}from"#runtime/resolve-hook.js";import{resolveSandboxDefinition}from"#runtime/resolve-sandbox.js";import{resolveDynamicInstructionsDefinition}from"#runtime/resolve-dynamic-instructions.js";import{resolveDynamicSkillDefinition}from"#runtime/resolve-dynamic-skill.js";import{resolveDynamicToolDefinition}from"#runtime/resolve-dynamic-tool.js";import{resolveToolDefinition}from"#runtime/resolve-tool.js";import{resolveMemoryDefinition}from"#runtime/resolve-memory.js";async function resolveAgent(e){let t=e.manifest.skills.map(t=>({...t,owner:requireCompiledSourceOwner(e.manifest,t),metadata:t.metadata===void 0?void 0:{...t.metadata}})),n=await Promise.all(e.manifest.channelRoutes.effective.map(t=>resolveChannelDefinition(t,e.moduleMap,e.nodeId))),r=await Promise.all(e.manifest.tools.map(t=>resolveToolDefinition(t,e.moduleMap,e.nodeId,requireBindingOwner(e.manifest,t.sourceId)))),i=await Promise.all(e.manifest.dynamicConnections.map(t=>resolveDynamicConnectionDefinition(t,e.moduleMap,e.nodeId))),a=await Promise.all((e.manifest.dynamicInstructions??[]).map(t=>resolveDynamicInstructionsDefinition(t,e.moduleMap,e.nodeId))),o=await Promise.all((e.manifest.dynamicSkills??[]).map(t=>resolveDynamicSkillDefinition(t,e.moduleMap,e.nodeId))),s=await Promise.all(e.manifest.dynamicTools.map(t=>resolveDynamicToolDefinition(t,e.moduleMap,e.nodeId))),c=await Promise.all(e.manifest.hooks.map(t=>resolveHookDefinition(t,e.moduleMap,e.nodeId))),l=await Promise.all(e.manifest.connections.map(t=>resolveConnectionDefinition(t,e.moduleMap,e.nodeId))),u=await Promise.all(e.manifest.memories.map(t=>resolveMemoryDefinition(t,e.moduleMap,e.nodeId))),d=await resolveSandboxDefinition(e.manifest.sandbox,e.moduleMap,e.nodeId),f=e.manifest.instructions.map(t=>createResolvedInstructionsDefinition(e.manifest,t)),p=e.manifest.workspaceResourceRoot,m={channels:n,connections:l,dynamicConnectionResolvers:i,dynamicInstructionsResolvers:a,dynamicSkillResolvers:o,dynamicToolResolvers:s,hooks:c,instructions:f,metadata:{agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,diagnosticsSummary:e.manifest.diagnosticsSummary},memories:u,sandbox:d,workspaceResourceRoot:p,skills:t,tools:r,workspaceSpec:{rootEntries:[...p.rootEntries]}};return`config`in e.manifest?{...m,config:createResolvedAgentConfig(e.manifest)}:m}function requireBindingOwner(e,t){let n=e.bindings[t];if(n===void 0)throw Error(`Compiled source "${t}" has no binding.`);return n.owner}function createResolvedInstructionsDefinition(e,t){return{content:t.content,name:t.name,owner:requireCompiledSourceOwner(e,t),logicalPath:t.logicalPath,role:t.role,sourceId:t.sourceId,sourceKind:t.sourceKind}}function requireCompiledSourceOwner(e,t){let n=e.bindings[t.sourceId]?.owner??t.owner;if(n===void 0)throw Error(`Compiled source "${t.sourceId}" has no owner.`);return n}function createResolvedAgentConfig(e){let t={name:e.config.name};if(e.config.defaultTools!==void 0&&(t.defaultTools=e.config.defaultTools),e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,maxOutputTokens:e.config.compaction.model.maxOutputTokens,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,maxOutputTokens:e.config.compaction.model.maxOutputTokens,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}if(e.config.experimental!==void 0&&(t.experimental={instrumentationProviders:e.config.experimental.instrumentationProviders,workflow:e.config.experimental.workflow===void 0?void 0:{modelCallsPerStep:e.config.experimental.workflow.modelCallsPerStep,retention:e.config.experimental.workflow.retention,world:e.config.experimental.workflow.world}}),e.config.outputSchema!==void 0&&(t.outputSchema=e.config.outputSchema),e.config.reasoning!==void 0&&(t.reasoning=e.config.reasoning),e.config.source!==void 0&&(t.source=createResolvedModuleSourceRef(e.config.source)),e.config.limits!==void 0&&(t.limits={maxInputTokensPerSession:e.config.limits.maxInputTokensPerSession,maxOutputTokensPerSession:e.config.limits.maxOutputTokensPerSession,maxTokenCostUsdPerSession:e.config.limits.maxTokenCostUsdPerSession,sessionTimeoutMs:e.config.limits.sessionTimeoutMs}),e.config.dynamicModel!==void 0)return{...t,dynamicModel:{...createResolvedModuleSourceRef(e.config.dynamicModel),eventNames:[...e.config.dynamicModel.eventNames]}};let n=e.config.model;return{...t,model:n.source===void 0?{id:n.id,contextWindowTokens:n.contextWindowTokens,maxOutputTokens:n.maxOutputTokens,providerOptions:n.providerOptions}:{contextWindowTokens:n.contextWindowTokens,id:n.id,maxOutputTokens:n.maxOutputTokens,providerOptions:n.providerOptions,source:{exportName:n.source.exportName,sourceKind:`module`,logicalPath:n.source.logicalPath,sourceId:n.source.sourceId}}}}export{ResolveAgentError,resolveAgent};
@@ -1 +1 @@
1
- import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createConnectionInstanceId}from"#runtime/connections/instance-identity.js";async function resolveConnectionDefinition(e,t,n){try{let r=await loadResolvedModuleExport({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),i=expectObjectRecord(r,`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`),a={kind:`connection`,logicalPath:e.logicalPath,name:e.connectionName},o=`connection-source:${e.sourceId}`;stampDefinitionKey(i,o),registerDefinitionSource(o,a),registerDefinitionSource(`connection:${e.url}`,a);let s=i.auth!==void 0,c=i.headers!==void 0,l=e.protocol===`openapi`?i.operations:i.tools,u={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,instanceId:createConnectionInstanceId({connectionName:e.connectionName,instanceKey:typeof i.instanceKey==`string`?i.instanceKey:void 0,protocol:e.protocol,sourceId:e.sourceId,url:e.url}),protocol:e.protocol,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(s){if(typeof i.auth==`function`)u.authorization=i.auth;else try{u.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new ResolveAgentError(toErrorMessage(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}}return c&&(u.headers=i.headers),i.toolCall!==void 0&&(u.toolCall=i.toolCall),l!==void 0&&(u.tools=l),e.protocol===`openapi`&&i.spec!==void 0&&(u.spec=i.spec),typeof i.approval==`function`&&(u.approval=i.approval),u}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function resolveDynamicConnectionValue(e,t){let n=readStampedConnectionProtocol(e),r=`Dynamic connection "${t.connectionName}" from "${t.logicalPath}" must be created by defineMcpClientConnection() or defineOpenAPIConnection().`;if(n===void 0)throw Error(r);let i={kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName},a=`dynamic-connection-source:${t.sourceId}:${t.connectionName}`;if(stampDefinitionKey(e,a),registerDefinitionSource(a,i),n===`openapi`){let i=normalizeOpenApiConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(i.auth,i.instanceKey,r),omitUndefined({approval:i.approval,authorization:i.auth,connectionName:t.connectionName,description:i.description,exportName:t.exportName,headers:i.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:i.instanceKey,protocol:n,sourceId:t.sourceId,url:i.baseUrl??``}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,spec:i.spec,toolCall:i.toolCall,tools:i.operations,url:i.baseUrl??``})}let o=normalizeMcpClientConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(o.auth,o.instanceKey,r),omitUndefined({approval:o.approval,authorization:o.auth,connectionName:t.connectionName,description:o.description,exportName:t.exportName,headers:o.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:o.instanceKey,protocol:n,sourceId:t.sourceId,url:o.url}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,toolCall:o.toolCall,tools:o.tools,url:o.url})}function assertAuthenticatedDynamicInstanceKey(e,t,n){if(e!==void 0&&t===void 0)throw Error(`${n} Authenticated dynamic connections must set "instanceKey" to a stable, non-secret account or tenant identifier.`)}function omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}export{resolveConnectionDefinition,resolveDynamicConnectionValue};
1
+ import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createConnectionInstanceId}from"#runtime/connections/instance-identity.js";async function resolveConnectionDefinition(e,t,n){try{let r=await loadResolvedModuleExport({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),i=expectObjectRecord(r,`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`),a={kind:`connection`,logicalPath:e.logicalPath,name:e.connectionName},o=`connection-source:${e.sourceId}`;stampDefinitionKey(i,o),registerDefinitionSource(o,a),registerDefinitionSource(`connection:${e.url}`,a);let s=i.auth!==void 0,c=i.headers!==void 0,l=e.protocol===`openapi`?i.operations:i.tools,u={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,instanceId:createConnectionInstanceId({connectionName:e.connectionName,instanceKey:typeof i.instanceKey==`string`?i.instanceKey:void 0,protocol:e.protocol,sourceId:e.sourceId,url:e.url}),protocol:e.protocol,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(s){if(typeof i.auth==`function`)u.authorization=i.auth;else try{u.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new ResolveAgentError(toErrorMessage(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}}if(e.protocol===`mcp`&&i.protocolVersionDiscovery!==void 0){if(typeof i.protocolVersionDiscovery!=`boolean`)throw Error(`"protocolVersionDiscovery" must be a boolean.`);u.protocolVersionDiscovery=i.protocolVersionDiscovery}return c&&(u.headers=i.headers),i.toolCall!==void 0&&(u.toolCall=i.toolCall),l!==void 0&&(u.tools=l),e.protocol===`openapi`&&i.spec!==void 0&&(u.spec=i.spec),typeof i.approval==`function`&&(u.approval=i.approval),u}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function resolveDynamicConnectionValue(e,t){let n=readStampedConnectionProtocol(e),r=`Dynamic connection "${t.connectionName}" from "${t.logicalPath}" must be created by defineMcpClientConnection() or defineOpenAPIConnection().`;if(n===void 0)throw Error(r);let i={kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName},a=`dynamic-connection-source:${t.sourceId}:${t.connectionName}`;if(stampDefinitionKey(e,a),registerDefinitionSource(a,i),n===`openapi`){let i=normalizeOpenApiConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(i.auth,i.instanceKey,r),omitUndefined({approval:i.approval,authorization:i.auth,connectionName:t.connectionName,description:i.description,exportName:t.exportName,headers:i.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:i.instanceKey,protocol:n,sourceId:t.sourceId,url:i.baseUrl??``}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,spec:i.spec,toolCall:i.toolCall,tools:i.operations,url:i.baseUrl??``})}let o=normalizeMcpClientConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(o.auth,o.instanceKey,r),omitUndefined({approval:o.approval,authorization:o.auth,connectionName:t.connectionName,description:o.description,exportName:t.exportName,headers:o.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:o.instanceKey,protocol:n,sourceId:t.sourceId,url:o.url}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,toolCall:o.toolCall,protocolVersionDiscovery:o.protocolVersionDiscovery,tools:o.tools,url:o.url})}function assertAuthenticatedDynamicInstanceKey(e,t,n){if(e!==void 0&&t===void 0)throw Error(`${n} Authenticated dynamic connections must set "instanceKey" to a stable, non-secret account or tenant identifier.`)}function omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}export{resolveConnectionDefinition,resolveDynamicConnectionValue};
@@ -1 +1 @@
1
- import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{isToolSchema,toInputSchema,toOutputSchema}from"#tools/schema.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function resolveToolDefinition(e,t,n,r){if(!e.hasExecute)return{behavior:e.behavior,description:e.description,inputSchema:toInputSchema(e.inputSchema),logicalPath:e.logicalPath,name:e.name,outputSchema:toOutputSchema(e.outputSchema),owner:r,sourceId:e.sourceId,sourceKind:`module`};try{let i=await loadResolvedModuleExport({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),a=expectObjectRecord(i,describe(e,`to return an object`)),o={kind:`tool`,logicalPath:e.logicalPath,name:e.name,owner:r},s=`tool-source:${e.sourceId}`;stampDefinitionKey(a,s),registerDefinitionSource(s,o),registerDefinitionSource(`tool:${a.description}`,o);let c=expectFunction(a.execute,describe(e,`to provide an execute function`)),l=isToolSchema(a.inputSchema)?a.inputSchema:toInputSchema(e.inputSchema),u=isToolSchema(a.outputSchema)?a.outputSchema:toOutputSchema(e.outputSchema);return{behavior:e.behavior,description:e.description,execute:c,execution:e.execution,exportName:e.exportName,inputSchema:l,logicalPath:e.logicalPath,name:e.name,owner:r,outputSchema:u,sourceId:e.sourceId,sourceKind:`module`,...extractOptionalHooks(a,e)}}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to attach the tool execute function from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function extractOptionalHooks(e,t){let n={};if(e.label!==void 0){let r=expectObjectRecord(e.label,describe(t,`to provide a valid label definition`));n.label={complete:r.complete===void 0?void 0:expectFunction(r.complete,describe(t,`to provide an label complete function`)),delta:r.delta===void 0?void 0:expectFunction(r.delta,describe(t,`to provide an label delta function`)),start:expectFunction(r.start,describe(t,`to provide a label start callback function`))}}return e.approval!==void 0&&(n.approval=normalizeApproval(e.approval,describe(t,`to provide a valid approval definition`))),e.approvalKey!==void 0&&(n.approvalKey=expectFunction(e.approvalKey,describe(t,`to provide an approvalKey function`))),e.toModelOutput!==void 0&&(n.toModelOutput=expectFunction(e.toModelOutput,describe(t,`to provide a toModelOutput function`))),n}function describe(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}export{resolveToolDefinition};
1
+ import{expectFunction,expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{isToolSchema,toInputSchema,toOutputSchema}from"#tools/schema.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{createWorkflowProgramExecuteInput}from"#tools/workflow-program-input.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";async function resolveToolDefinition(e,t,n,r){if(!e.hasExecute)return{behavior:e.behavior,description:e.description,inputSchema:toInputSchema(e.inputSchema),logicalPath:e.logicalPath,name:e.name,outputSchema:toOutputSchema(e.outputSchema),owner:r,sourceId:e.sourceId,sourceKind:`module`};try{let i=await loadResolvedModuleExport({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),a=expectObjectRecord(i,describe(e,`to return an object`)),o={kind:`tool`,logicalPath:e.logicalPath,name:e.name,owner:r},s=`tool-source:${e.sourceId}`;stampDefinitionKey(a,s),registerDefinitionSource(s,o),registerDefinitionSource(`tool:${a.description}`,o);let c=expectFunction(a.execute,describe(e,`to provide an execute function`)),l=isToolSchema(a.inputSchema)?a.inputSchema:toInputSchema(e.inputSchema),u=isToolSchema(a.outputSchema)?a.outputSchema:toOutputSchema(e.outputSchema),d=e.workflowProgram,f=d===void 0?void 0:e=>createWorkflowProgramExecuteInput(d,e);return{behavior:e.behavior,description:e.description,execute:c,executeInput:f,execution:e.execution,exportName:e.exportName,inputSchema:l,logicalPath:e.logicalPath,name:e.name,owner:r,outputSchema:u,sourceId:e.sourceId,sourceKind:`module`,...extractOptionalHooks(a,e)}}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to attach the tool execute function from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function extractOptionalHooks(e,t){let n={};if(e.label!==void 0){let r=expectObjectRecord(e.label,describe(t,`to provide a valid label definition`));n.label={complete:r.complete===void 0?void 0:expectFunction(r.complete,describe(t,`to provide an label complete function`)),delta:r.delta===void 0?void 0:expectFunction(r.delta,describe(t,`to provide an label delta function`)),start:expectFunction(r.start,describe(t,`to provide a label start callback function`))}}return e.approval!==void 0&&(n.approval=normalizeApproval(e.approval,describe(t,`to provide a valid approval definition`))),e.approvalKey!==void 0&&(n.approvalKey=expectFunction(e.approvalKey,describe(t,`to provide an approvalKey function`))),e.toModelOutput!==void 0&&(n.toModelOutput=expectFunction(e.toModelOutput,describe(t,`to provide a toModelOutput function`))),n}function describe(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}export{resolveToolDefinition};
@@ -1 +1 @@
1
- import{getAdapterKind}from"#channel/adapter.js";import{ContextKey}from"#context/key.js";import{CHANNEL_CONTEXT_KEY_NAME}from"#context/key-names.js";import{buildChannelInstrumentationProjection}from"#channel/instrumentation.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource,serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{deserializeRuntimeAdapter}from"#runtime/channels/registry.js";const ChannelKey=new ContextKey(CHANNEL_CONTEXT_KEY_NAME,{codec:{serialize(e){let t=buildChannelInstrumentationProjection({adapter:e});return{kind:getAdapterKind(e),state:e.state?{...e.state}:{},audience:t.metadata.audience}},deserialize(e,t){let n=t.get(BundleKey);if(n===void 0)throw Error(`Cannot deserialize "eve.channel" before "eve.bundle". The runtime bundle must be present in context.`);return deserializeRuntimeAdapter(n.adapterRegistry,e)}}}),BundleKey=new ContextKey(`eve.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:serializeDurableCompiledArtifactsSource(e.compiledArtifactsSource)}),deserialize:e=>{let{source:t,nodeId:n}=e;return getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(t),nodeId:n})}}});export{BundleKey,ChannelKey};
1
+ import{getAdapterKind}from"#channel/adapter.js";import{ContextKey}from"#context/key.js";import{CHANNEL_CONTEXT_KEY_NAME}from"#context/key-names.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDurableCompiledArtifactsSource,serializeDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{deserializeRuntimeAdapter}from"#runtime/channels/registry.js";const ChannelKey=new ContextKey(CHANNEL_CONTEXT_KEY_NAME,{codec:{serialize(e){return{kind:getAdapterKind(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(BundleKey);if(n===void 0)throw Error(`Cannot deserialize "eve.channel" before "eve.bundle". The runtime bundle must be present in context.`);return deserializeRuntimeAdapter(n.adapterRegistry,e)}}}),BundleKey=new ContextKey(`eve.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:serializeDurableCompiledArtifactsSource(e.compiledArtifactsSource)}),deserialize:e=>{let{source:t,nodeId:n}=e;return getCompiledRuntimeAgentBundle({compiledArtifactsSource:resolveDurableCompiledArtifactsSource(t),nodeId:n})}}});export{BundleKey,ChannelKey};
@@ -15,7 +15,7 @@ import type { AuthorizationDefinition, ConnectionAuthResolver, ConnectionProtoco
15
15
  import type { OpenAPISpecSource } from "#public/definitions/connections/openapi.js";
16
16
  import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";
17
17
  import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";
18
- import type { JsonObject } from "#shared/json.js";
18
+ import type { JsonObject, JsonValue } from "#shared/json.js";
19
19
  import type { Optional } from "#shared/optional.js";
20
20
  import type { Node } from "#shared/node.js";
21
21
  import type { SourceRef, ModuleSourceRef, SkillPackageSourceRef, MarkdownSourceRef } from "#shared/source-ref.js";
@@ -78,6 +78,7 @@ export type ResolvedScheduleDefinition = Readonly<SourceRef & {
78
78
  * server that requires no authentication (e.g. localhost) may omit both.
79
79
  */
80
80
  export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
81
+ readonly protocolVersionDiscovery?: boolean;
81
82
  readonly approval?: Approval;
82
83
  readonly authorization?: Readonly<AuthorizationDefinition> | ConnectionAuthResolver;
83
84
  readonly connectionName: string;
@@ -141,6 +142,8 @@ export type ResolvedToolDefinition = Readonly<Omit<Optional<InternalToolDefiniti
141
142
  * rehydrated before entering this runtime-owned definition.
142
143
  */
143
144
  readonly inputSchema: ToolSchema | null;
145
+ /** Framework-owned input projected before a workflow tool executor starts. */
146
+ readonly executeInput?: (input: unknown) => JsonValue;
144
147
  /** Presentation projected from tool lifecycle values. */
145
148
  readonly label?: import("#tools/definition.js").InternalToolLabelDefinition;
146
149
  /**
@@ -359,14 +362,6 @@ export interface ResolvedAgent {
359
362
  readonly config?: ResolvedAgentDefinition;
360
363
  readonly connections: readonly ResolvedConnectionDefinition[];
361
364
  readonly dynamicConnectionResolvers?: readonly ResolvedDynamicConnectionResolver[];
362
- /**
363
- * Configuration for the experimental framework `Workflow` orchestration
364
- * tool. Present when an authored tool module exports
365
- * `experimental_workflow(...)`.
366
- */
367
- readonly workflowTool?: {
368
- readonly maxSubagents?: number;
369
- };
370
365
  /** AI Gateway provider selected for the framework `web_search` tool. */
371
366
  readonly dynamicInstructionsResolvers: readonly ResolvedDynamicInstructionsResolver[];
372
367
  readonly dynamicSkillResolvers: readonly ResolvedDynamicSkillResolver[];
@@ -1,4 +1,4 @@
1
- import { type AgentStaticModelDefinition } from "#public/index.js";
1
+ import { type AgentReasoningDefinition, type AgentStaticModelDefinition } from "#public/index.js";
2
2
  import { type SelfModificationConfig } from "./config.js";
3
3
  /** Default model used by the self-modification subagent. */
4
4
  export declare const DEFAULT_SELF_MODIFICATION_MODEL = "anthropic/claude-sonnet-5";
@@ -12,14 +12,20 @@ export interface SelfModificationAgentOptions {
12
12
  * @default "anthropic/claude-sonnet-5"
13
13
  */
14
14
  readonly model?: AgentStaticModelDefinition;
15
+ /**
16
+ * Reasoning effort used by the self-modification subagent.
17
+ */
18
+ readonly reasoning?: AgentReasoningDefinition;
15
19
  }
16
20
  /** Defines the environment-aware self-modification dynamic subagent. */
17
21
  export declare function defineSelfModificationAgent(options?: SelfModificationAgentOptions): import("#dynamic/definition.js").DynamicSentinel<import("#public/index.js").DefinedAgent<{
18
22
  description: string;
19
23
  model: AgentStaticModelDefinition;
24
+ reasoning: AgentReasoningDefinition | undefined;
20
25
  }> | null>;
21
26
  declare const _default: import("#dynamic/definition.js").DynamicSentinel<import("#public/index.js").DefinedAgent<{
22
27
  description: string;
23
28
  model: AgentStaticModelDefinition;
29
+ reasoning: AgentReasoningDefinition | undefined;
24
30
  }> | null>;
25
31
  export default _default;
@@ -1 +1 @@
1
- import{resolveSelfModificationConfig}from"./config.js";import{hasGitHubCredential}from"./credentials.js";import{resolveSelfModificationMode}from"./mode.js";import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function renderDescription(e){return e.filter(e=>e.length>0).join(` `)}function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5`,n=resolveSelfModificationConfig(e.config),resolve=async(e,r)=>{let i=resolveSelfModificationMode(n),a=renderDescription([`Delegate here when the user asks to change this eve agent or its authored source.`,`If the requested change references a tool or skill, include the exact identifier. Do not infer source paths; let the child resolve the appropriate file under /source. Delegate the requested change and existing constraints without adding unrequested features, implementation steps, or reporting requirements.`,`Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the requester does not mention files or source code. Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround.`,`Treat questions phrased as whether you can install, add, enable, or connect to a named product or service as requests to extend this eve agent and delegate immediately. Do not assume they refer to device software, ask what kind of installation they mean, or deny them because you lack access to the user's device. The subagent determines whether the request maps to an integration, channel, connection, or other capability, then checks registry availability and any required setup.`,i===`local`?`Delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them.`:`Delegate requests to add integrations, channels, connections, or capabilities: the subagent searches the official eve registry and can install source changes into the draft proposal. Setup may require non-secret answers or an external action, and secret binding remains separate.`,i===`local`?`Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted.`:``,`Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.`,i===`local`?`Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn.`:`Source edits do not affect the caller’s current turn. The subagent can publish only a draft pull request, and changes become effective only after review, merge, and redeployment.`]);if(i===`local`)return defineAgent({description:a,model:t});if(i!==`deployed`||n.deployed===void 0||n.deployed.credentials.kind===`pat`&&!hasGitHubCredential())return null;try{if(!await n.deployed.authorize({channel:r.channel,principal:r.session.auth.current}))return null}catch{return null}return defineAgent({description:a,model:t})};return defineDynamic({events:{"session.started":resolve,"turn.started":resolve}})}var agent_default=defineSelfModificationAgent();export{DEFAULT_SELF_MODIFICATION_MODEL,agent_default as default,defineSelfModificationAgent};
1
+ import{resolveSelfModificationConfig}from"./config.js";import{hasGitHubCredential}from"./credentials.js";import{resolveSelfModificationMode}from"./mode.js";import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function renderDescription(e){return e.filter(e=>e.length>0).join(` `)}function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5`,n=e.reasoning,r=resolveSelfModificationConfig(e.config),resolve=async(e,i)=>{let a=resolveSelfModificationMode(r),o=renderDescription([`Delegate here when the user asks to change this eve agent or its authored source.`,`If the requested change references a tool or skill, include the exact identifier. Do not infer source paths; let the child resolve the appropriate file under /source. Delegate the requested change and existing constraints without adding unrequested features, implementation steps, or reporting requirements.`,`Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the requester does not mention files or source code. Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround.`,`Treat questions phrased as whether you can install, add, enable, or connect to a named product or service as requests to extend this eve agent and delegate immediately. Do not assume they refer to device software, ask what kind of installation they mean, or deny them because you lack access to the user's device. The subagent determines whether the request maps to an integration, channel, connection, or other capability, then checks registry availability and any required setup.`,a===`local`?`Delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them.`:`Delegate requests to add integrations, channels, connections, or capabilities: the subagent searches the official eve registry and can install source changes into the draft proposal. Setup may require non-secret answers or an external action, and secret binding remains separate.`,a===`local`?`Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted.`:``,`Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.`,a===`local`?`Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn.`:`Source edits do not affect the caller’s current turn. The subagent can publish only a draft pull request, and changes become effective only after review, merge, and redeployment.`]);if(a===`local`)return defineAgent({description:o,model:t,reasoning:n});if(a!==`deployed`||r.deployed===void 0||r.deployed.credentials.kind===`pat`&&!hasGitHubCredential())return null;try{if(!await r.deployed.authorize({channel:i.channel,principal:i.session.auth.current}))return null}catch{return null}return defineAgent({description:o,model:t,reasoning:n})};return defineDynamic({events:{"session.started":resolve,"turn.started":resolve}})}var agent_default=defineSelfModificationAgent();export{DEFAULT_SELF_MODIFICATION_MODEL,agent_default as default,defineSelfModificationAgent};
@@ -2,9 +2,9 @@ import type { CatalogEntry } from "./tools/search_registry.js";
2
2
  /**
3
3
  * The split rule.
4
4
  *
5
- * An item that declares no setup and no components is installed by the tool. An
6
- * item that declares either is handed to the terminal whole, before anything is
7
- * installed — every question a setup flow asks, and every browser
5
+ * An item that declares no setup is installed by the tool. An item that declares
6
+ * setup is handed to the terminal whole, before anything is installed — every
7
+ * question a setup flow asks, and every browser
8
8
  * authorization or secret it needs, belongs to the surface built to ask.
9
9
  *
10
10
  * The rule reads catalog metadata only. It never predicts whether a particular
@@ -1 +1 @@
1
- function classifyCatalogEntry(e){return e.components!==void 0&&e.components.length>0?{kind:`needs-terminal`,reason:`${e.address} is a bundle of ${e.components.join(`, `)}. Choosing which components to install is a question, so the whole bundle goes to the terminal.`}:e.declaresSetup===!0?{kind:`needs-terminal`,reason:`${e.address} declares a setup flow, which can ask for credentials or open a browser authorization. Neither can be answered from a chat turn.`}:{kind:`installable`}}export{classifyCatalogEntry};
1
+ function classifyCatalogEntry(e){return e.declaresSetup===!0?{kind:`needs-terminal`,reason:`${e.address} declares a setup flow, which can ask for credentials or open a browser authorization. Neither can be answered from a chat turn.`}:{kind:`installable`}}export{classifyCatalogEntry};
@@ -8,9 +8,6 @@ export interface CatalogEntry {
8
8
  readonly title: string;
9
9
  readonly description?: string;
10
10
  readonly category?: Category;
11
- readonly components?: readonly string[];
12
- /** Component addresses, labels, and descriptions used to search bundles. */
13
- readonly componentSearchTerms?: readonly string[];
14
11
  readonly requires?: string;
15
12
  /** Authored path this item installs, used to detect an existing install. */
16
13
  readonly authoredTarget?: string;
@@ -25,7 +22,6 @@ export interface FoundIntegration {
25
22
  readonly title: string;
26
23
  readonly description?: string;
27
24
  readonly category?: Category;
28
- readonly components?: readonly string[];
29
25
  readonly requires?: string;
30
26
  readonly installed?: boolean;
31
27
  }
@@ -39,9 +35,7 @@ export declare function parseRegistryIndex(value: unknown): readonly CatalogEntr
39
35
  /**
40
36
  * Filters and bounds catalog entries for one search.
41
37
  *
42
- * A bundle matches when one of its components matches the requested category,
43
- * so asking for channels still surfaces `linear` (which installs a channel)
44
- * instead of hiding it behind its uncategorized address.
38
+ * Category filters match the leading segment of each registry address.
45
39
  */
46
40
  export declare function selectIntegrations(input: {
47
41
  readonly category?: Category;
@@ -1 +1 @@
1
- import{defineTool}from"eve/tools";const CATEGORIES=[`channel`,`connection`,`extension`,`instrumentation`,`memory`],INDEX_PATH=`/registry.json`,FETCH_TIMEOUT_MS=1e4,inputSchema={type:`object`,additionalProperties:!1,properties:{query:{type:`string`,maxLength:200,description:`Free-text match against integration names, titles, and descriptions.`},category:{type:`string`,enum:[...CATEGORIES],description:`Restrict results to one registry category.`},limit:{type:`integer`,minimum:1,maximum:25,description:`Maximum number of items to return (default 10, maximum 25).`},offset:{type:`integer`,minimum:0,description:`Number of matching items to skip. Use nextOffset from a prior result to retrieve the next page.`}}},outputSchema={type:`object`,additionalProperties:!1,properties:{items:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{address:{type:`string`},title:{type:`string`},description:{type:`string`},category:{type:`string`},components:{type:`array`,items:{type:`string`}},requires:{type:`string`},installed:{type:`boolean`}},required:[`address`,`title`]}},errors:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{registry:{type:`string`},message:{type:`string`}},required:[`registry`,`message`]}},total:{type:`integer`},hasMore:{type:`boolean`},nextOffset:{type:`integer`}},required:[`items`,`errors`,`total`,`hasMore`]};function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function optionalString(e){return typeof e==`string`&&e.length>0?e:void 0}function isCategory(e){return CATEGORIES.includes(e)}function categoryOf(e){let t=e.split(`/`)[0];return t!==void 0&&e.includes(`/`)&&isCategory(t)?t:void 0}function titleFromAddress(e){return(e.split(`/`).at(-1)??e).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function eveMetadata(e){let t=e.meta;if(!isRecord(t))return{};let n=t.eve;return isRecord(n)?n:{}}function componentMetadata(e){let t=e.components;if(!Array.isArray(t))return;let n=[],r=[];for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.item);if(t===void 0)continue;n.push(t),r.push(t);let i=optionalString(e.label);i!==void 0&&r.push(i);let a=optionalString(e.description);a!==void 0&&r.push(a)}return n.length>0?{addresses:n,searchTerms:r}:void 0}function authoredTargetOf(e){let t=e.files;if(Array.isArray(t))for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.target);if(t?.startsWith(`agent/`)===!0)return t}}function declaredEnvVars(e){let t=e.envVars;return isRecord(t)?Object.keys(t):[]}function parseRegistryIndex(e){if(!isRecord(e)||!Array.isArray(e.items))return[];let t=[];for(let n of e.items){if(!isRecord(n))continue;let e=optionalString(n.name);if(e===void 0)continue;let r=eveMetadata(n);if(r.hidden===!0)continue;let i={address:e,title:optionalString(n.title)??titleFromAddress(e)},a=categoryOf(e);a!==void 0&&(i.category=a);let o=optionalString(n.description);o!==void 0&&(i.description=o);let s=componentMetadata(r);s!==void 0&&(i.components=s.addresses,i.componentSearchTerms=s.searchTerms);let c=optionalString(r.requires);c!==void 0&&(i.requires=c);let l=authoredTargetOf(n);l!==void 0&&(i.authoredTarget=l),r.setup!==void 0&&r.setup!==null&&(i.declaresSetup=!0);let u=declaredEnvVars(n);u.length>0&&(i.envVars=u),t.push(i)}return t}function selectIntegrations(e){return selectIntegrationPage(e).items}function selectIntegrationPage(e){let t=Math.min(Math.max(e.limit??10,1),25),n=Math.max(e.offset??0,0),r=(e.query??``).toLowerCase().split(/\s+/u).filter(e=>e.length>0),i=e.entries.map((e,t)=>{let n=`${e.address} ${e.title}`.toLowerCase();return{entry:e,haystack:[n,e.description??``,...e.componentSearchTerms??e.components??[]].join(` `).toLowerCase(),index:t,primaryTerms:n}}),a=new Map(r.map(e=>{let t=i.filter(({haystack:t})=>t.includes(e)).length;return[e,Math.log((i.length+1)/(t+1))+1]})),o=i.map(({entry:t,haystack:n,index:i,primaryTerms:o})=>{if(e.category!==void 0&&!matchesCategory(t,e.category))return;if(r.length===0)return{entry:t,index:i,score:0};let s=r.reduce((e,t)=>{let r=a.get(t)??0;return o.includes(t)?e+2*r:n.includes(t)?e+r:e},0);return s>0?{entry:t,index:i,score:s}:void 0}).filter(e=>e!==void 0).sort((e,t)=>t.score-e.score||e.index-t.index),s=(o[0]?.score??0)*.4,c=o.filter(({score:e})=>e>=s),l=c.slice(n,n+t).map(({entry:e})=>{let t={address:e.address,title:e.title};return e.category!==void 0&&(t.category=e.category),e.components!==void 0&&(t.components=e.components),e.description!==void 0&&(t.description=e.description),e.requires!==void 0&&(t.requires=e.requires),t}),u=n+l.length,d={hasMore:u<c.length,items:l,total:c.length};return u<c.length&&(d.nextOffset=u),d}function matchesCategory(e,t){return e.category===t||e.components?.some(e=>categoryOf(e)===t)===!0}function officialRegistryIndexUrl(){return`https://eve.dev/r${INDEX_PATH}`}function resolveRegistryIndexUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return officialRegistryIndexUrl();let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=`${t.pathname.replace(/\/+$/u,``)}${INDEX_PATH}`,t.toString()}let cache;function clearRegistryIndexCache(){cache=void 0}async function loadRegistryIndex(e){if(cache!==void 0&&cache.url===e.url&&e.nowMs-cache.fetchedAtMs<3e5)return cache.entries;let t=await fetch(e.url,{headers:{accept:`application/json`},signal:AbortSignal.any(e.signal===void 0?[AbortSignal.timeout(FETCH_TIMEOUT_MS)]:[e.signal,AbortSignal.timeout(FETCH_TIMEOUT_MS)])});if(!t.ok)throw Error(`Could not read the eve registry (${t.status}).`);let n=parseRegistryIndex(await t.json());return cache={entries:n,fetchedAtMs:e.nowMs,url:e.url},n}async function annotateInstalled(e){let t=new Map(e.entries.flatMap(e=>e.authoredTarget===void 0?[]:[[e.address,e.authoredTarget]]));if(e.rows.every(e=>t.get(e.address)===void 0))return e.rows;let n;try{n=await e.ctx.getSandbox()}catch{return e.rows}return await Promise.all(e.rows.map(async e=>{let r=t.get(e.address);if(r===void 0)return e;let i=`/source/${r.slice(6)}`;try{let t=await n.readTextFile({path:i});return{...e,installed:t!==null}}catch{return e}}))}var search_registry_default=defineTool({description:"Search the eve registry for integrations this project can add: channels, MCP connections, extensions, memory providers, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(e,t){let n=[],r;try{r=resolveRegistryIndexUrl()}catch(e){return{errors:[{message:errorMessage(e),registry:`eve`}],hasMore:!1,items:[],total:0}}let i=[];try{i=await loadRegistryIndex({nowMs:Date.now(),signal:t.abortSignal,url:r})}catch(e){n.push({message:errorMessage(e),registry:r})}let a={entries:i},o=typeof e.category==`string`?e.category:void 0;o!==void 0&&isCategory(o)&&(a.category=o),typeof e.limit==`number`&&(a.limit=e.limit),typeof e.offset==`number`&&(a.offset=e.offset),typeof e.query==`string`&&(a.query=e.query);let s=selectIntegrationPage(a),c={errors:n,hasMore:s.hasMore,items:await annotateInstalled({ctx:t,entries:i,rows:s.items}),total:s.total};return s.nextOffset!==void 0&&(c.nextOffset=s.nextOffset),c}});function errorMessage(e){return e instanceof Error?e.message:String(e)}export{clearRegistryIndexCache,search_registry_default as default,loadRegistryIndex,officialRegistryIndexUrl,parseRegistryIndex,resolveRegistryIndexUrl,selectIntegrationPage,selectIntegrations};
1
+ import{defineTool}from"eve/tools";const CATEGORIES=[`channel`,`connection`,`extension`,`instrumentation`,`memory`],INDEX_PATH=`/registry.json`,FETCH_TIMEOUT_MS=1e4,inputSchema={type:`object`,additionalProperties:!1,properties:{query:{type:`string`,maxLength:200,description:`Free-text match against integration names, titles, and descriptions.`},category:{type:`string`,enum:[...CATEGORIES],description:`Restrict results to one registry category.`},limit:{type:`integer`,minimum:1,maximum:25,description:`Maximum number of items to return (default 10, maximum 25).`},offset:{type:`integer`,minimum:0,description:`Number of matching items to skip. Use nextOffset from a prior result to retrieve the next page.`}}},outputSchema={type:`object`,additionalProperties:!1,properties:{items:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{address:{type:`string`},title:{type:`string`},description:{type:`string`},category:{type:`string`},requires:{type:`string`},installed:{type:`boolean`}},required:[`address`,`title`]}},errors:{type:`array`,items:{type:`object`,additionalProperties:!1,properties:{registry:{type:`string`},message:{type:`string`}},required:[`registry`,`message`]}},total:{type:`integer`},hasMore:{type:`boolean`},nextOffset:{type:`integer`}},required:[`items`,`errors`,`total`,`hasMore`]};function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function optionalString(e){return typeof e==`string`&&e.length>0?e:void 0}function isCategory(e){return CATEGORIES.includes(e)}function categoryOf(e){let t=e.split(`/`)[0];return t!==void 0&&e.includes(`/`)&&isCategory(t)?t:void 0}function titleFromAddress(e){return(e.split(`/`).at(-1)??e).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function eveMetadata(e){let t=e.meta;if(!isRecord(t))return{};let n=t.eve;return isRecord(n)?n:{}}function authoredTargetOf(e){let t=e.files;if(Array.isArray(t))for(let e of t){if(!isRecord(e))continue;let t=optionalString(e.target);if(t?.startsWith(`agent/`)===!0)return t}}function declaredEnvVars(e){let t=e.envVars;return isRecord(t)?Object.keys(t):[]}function parseRegistryIndex(e){if(!isRecord(e)||!Array.isArray(e.items))return[];let t=[];for(let n of e.items){if(!isRecord(n))continue;let e=optionalString(n.name);if(e===void 0)continue;let r=eveMetadata(n);if(r.hidden===!0)continue;let i={address:e,title:optionalString(n.title)??titleFromAddress(e)},a=categoryOf(e);a!==void 0&&(i.category=a);let o=optionalString(n.description);o!==void 0&&(i.description=o);let s=optionalString(r.requires);s!==void 0&&(i.requires=s);let c=authoredTargetOf(n);c!==void 0&&(i.authoredTarget=c),r.setup!==void 0&&r.setup!==null&&(i.declaresSetup=!0);let l=declaredEnvVars(n);l.length>0&&(i.envVars=l),t.push(i)}return t}function selectIntegrations(e){return selectIntegrationPage(e).items}function selectIntegrationPage(e){let t=Math.min(Math.max(e.limit??10,1),25),n=Math.max(e.offset??0,0),r=(e.query??``).toLowerCase().split(/\s+/u).filter(e=>e.length>0),i=e.entries.map((e,t)=>{let n=`${e.address} ${e.title}`.toLowerCase();return{entry:e,haystack:[n,e.description??``].join(` `).toLowerCase(),index:t,primaryTerms:n}}),a=new Map(r.map(e=>{let t=i.filter(({haystack:t})=>t.includes(e)).length;return[e,Math.log((i.length+1)/(t+1))+1]})),o=i.map(({entry:t,haystack:n,index:i,primaryTerms:o})=>{if(e.category!==void 0&&!matchesCategory(t,e.category))return;if(r.length===0)return{entry:t,index:i,score:0};let s=r.reduce((e,t)=>{let r=a.get(t)??0;return o.includes(t)?e+2*r:n.includes(t)?e+r:e},0);return s>0?{entry:t,index:i,score:s}:void 0}).filter(e=>e!==void 0).sort((e,t)=>t.score-e.score||e.index-t.index),s=(o[0]?.score??0)*.4,c=o.filter(({score:e})=>e>=s),l=c.slice(n,n+t).map(({entry:e})=>{let t={address:e.address,title:e.title};return e.category!==void 0&&(t.category=e.category),e.description!==void 0&&(t.description=e.description),e.requires!==void 0&&(t.requires=e.requires),t}),u=n+l.length,d={hasMore:u<c.length,items:l,total:c.length};return u<c.length&&(d.nextOffset=u),d}function matchesCategory(e,t){return e.category===t}function officialRegistryIndexUrl(){return`https://eve.dev/r${INDEX_PATH}`}function resolveRegistryIndexUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return officialRegistryIndexUrl();let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=`${t.pathname.replace(/\/+$/u,``)}${INDEX_PATH}`,t.toString()}let cache;function clearRegistryIndexCache(){cache=void 0}async function loadRegistryIndex(e){if(cache!==void 0&&cache.url===e.url&&e.nowMs-cache.fetchedAtMs<3e5)return cache.entries;let t=await fetch(e.url,{headers:{accept:`application/json`},signal:AbortSignal.any(e.signal===void 0?[AbortSignal.timeout(FETCH_TIMEOUT_MS)]:[e.signal,AbortSignal.timeout(FETCH_TIMEOUT_MS)])});if(!t.ok)throw Error(`Could not read the eve registry (${t.status}).`);let n=parseRegistryIndex(await t.json());return cache={entries:n,fetchedAtMs:e.nowMs,url:e.url},n}async function annotateInstalled(e){let t=new Map(e.entries.flatMap(e=>e.authoredTarget===void 0?[]:[[e.address,e.authoredTarget]]));if(e.rows.every(e=>t.get(e.address)===void 0))return e.rows;let n;try{n=await e.ctx.getSandbox()}catch{return e.rows}return await Promise.all(e.rows.map(async e=>{let r=t.get(e.address);if(r===void 0)return e;let i=`/source/${r.slice(6)}`;try{let t=await n.readTextFile({path:i});return{...e,installed:t!==null}}catch{return e}}))}var search_registry_default=defineTool({description:"Search the eve registry for integrations this project can add: channels, MCP connections, extensions, memory providers, and observability. Read-only — it installs nothing. Call it before writing an integration by hand, then pass an exact item address (for example `channel/slack`) to selfmod__registry_add.",inputSchema,outputSchema,async execute(e,t){let n=[],r;try{r=resolveRegistryIndexUrl()}catch(e){return{errors:[{message:errorMessage(e),registry:`eve`}],hasMore:!1,items:[],total:0}}let i=[];try{i=await loadRegistryIndex({nowMs:Date.now(),signal:t.abortSignal,url:r})}catch(e){n.push({message:errorMessage(e),registry:r})}let a={entries:i},o=typeof e.category==`string`?e.category:void 0;o!==void 0&&isCategory(o)&&(a.category=o),typeof e.limit==`number`&&(a.limit=e.limit),typeof e.offset==`number`&&(a.offset=e.offset),typeof e.query==`string`&&(a.query=e.query);let s=selectIntegrationPage(a),c={errors:n,hasMore:s.hasMore,items:await annotateInstalled({ctx:t,entries:i,rows:s.items}),total:s.total};return s.nextOffset!==void 0&&(c.nextOffset=s.nextOffset),c}});function errorMessage(e){return e instanceof Error?e.message:String(e)}export{clearRegistryIndexCache,search_registry_default as default,loadRegistryIndex,officialRegistryIndexUrl,parseRegistryIndex,resolveRegistryIndexUrl,selectIntegrationPage,selectIntegrations};
@@ -1 +1 @@
1
- import{createHash,randomBytes}from"node:crypto";import{createServer}from"node:http";import{spawn}from"node:child_process";import{WizardCancelledError}from"#setup/step.js";import{createProcessOutputBuffer}from"#setup/primitives/process-output.js";import{isErrnoCode,isObject}from"#shared/guards.js";import{setTimeout as setTimeout$1}from"node:timers/promises";import{getDefaultCodexTokenBroker}from"#public/models/openai/chatgpt/token-broker.js";import{ChatGptInvalidStoredSessionError,getDefaultChatGptCredentialStore}from"#public/models/openai/chatgpt/credential-store.js";import{CHATGPT_CLIENT_ID,CHATGPT_ISSUER,readChatGptAuthResponse,requestChatGptTokens}from"#public/models/openai/chatgpt/oauth.js";import{openUrl}from"#setup/primitives/open-url.js";const REDIRECT_URI=`http://localhost:1455/auth/callback`;async function ensureChatGptAuth(e={}){let t=e.broker??getDefaultCodexTokenBroker(),n=e.store??getDefaultChatGptCredentialStore();e.signal?.throwIfAborted();let r=await t.refreshState();if(r.kind===`ready`)return;let i=t.credentialOwner();if(i===void 0)throw Error(`ChatGPT credential owner could not be resolved.`);if(i===`codex`){if(r.kind===`unavailable`)throw Error(r.reason);try{let n=e.log??(e=>process.stdout.write(`${e}\n`));await(e.codexLogin??(e=>loginWithCodex(e,n)))(e.signal),await assertChatGptAuthReady(t,`Codex login completed without a usable ChatGPT session.`);return}catch(e){if(!isErrnoCode(e,`ENOENT`))throw e;let n=await t.refreshState();if(t.credentialOwner()!==`eve`)throw e;if(n.kind===`ready`)return;if(n.kind===`unavailable`)throw Error(n.reason)}}try{await n.read()}catch(e){if(!(e instanceof ChatGptInvalidStoredSessionError))throw e}await signInWithOwnedCredentials(e,t,n)}async function signInWithOwnedCredentials(e,t,n){let r=new AbortController,cancel=()=>r.abort(new WizardCancelledError);process.once(`SIGINT`,cancel);let i=setTimeout(()=>r.abort(Error(`ChatGPT sign-in timed out. Retry from /model.`)),3e5),a=AbortSignal.any([r.signal,...e.signal?[e.signal]:[]]),o=e.log??(e=>process.stdout.write(`${e}\n`)),s=e.open??openUrl;try{let r=e.headless??!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)?await deviceLogin({...e,signal:a,log:o,open:s}):await browserLogin({...e,signal:a,log:o,open:s});a.throwIfAborted(),await n.update(async()=>(a.throwIfAborted(),r),{replace:!0}),await assertChatGptAuthReady(t,`ChatGPT sign-in could not be verified. Retry from /model.`),o(`ChatGPT subscription connected.`)}catch(e){throw a.throwIfAborted(),e}finally{clearTimeout(i),process.removeListener(`SIGINT`,cancel)}}async function assertChatGptAuthReady(e,t){if((await e.refreshState()).kind!==`ready`)throw Error(t)}async function loginWithCodex(e,t){let n=spawn(`codex`,[`login`],{stdio:[`ignore`,`pipe`,`pipe`],...e!==void 0&&{signal:e}}),r=createProcessOutputBuffer(({text:e})=>t(e));n.stdout.on(`data`,e=>r.write(`stdout`,e)),n.stderr.on(`data`,e=>r.write(`stderr`,e));try{await new Promise((e,t)=>{n.once(`error`,t),n.once(`close`,(n,r)=>{n===0?e():t(Error(`codex login failed (${r??n??`unknown`}).`))})})}finally{r.flush()}}async function browserLogin(e){let t=randomBytes(32).toString(`base64url`),n=randomBytes(32).toString(`base64url`),r=new URL(`${CHATGPT_ISSUER}/oauth/authorize`);r.search=new URLSearchParams({response_type:`code`,client_id:CHATGPT_CLIENT_ID,redirect_uri:REDIRECT_URI,scope:`openid profile email offline_access`,code_challenge:createHash(`sha256`).update(t).digest(`base64url`),code_challenge_method:`S256`,id_token_add_organizations:`true`,codex_cli_simplified_flow:`true`,state:n,originator:`eve`}).toString();let i=Promise.withResolvers();i.promise.catch(()=>{});let a=createServer({requestTimeout:1e4,headersTimeout:1e4,maxHeaderSize:8192},(e,t)=>{let r=URL.parse(e.url??``,REDIRECT_URI);if(t.setHeader(`content-type`,`text/plain; charset=utf-8`),t.setHeader(`cache-control`,`no-store`),e.method!==`GET`||r?.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found.`);return}if(r.searchParams.get(`state`)!==n){t.writeHead(400).end(`This sign-in belongs to another attempt. Return to eve and use its sign-in link.`);return}if(r.searchParams.has(`error`)){t.writeHead(400).end(`ChatGPT sign-in was declined. Return to eve to retry.`),i.reject(Error(`ChatGPT sign-in was declined. Retry from /model.`));return}let a=r.searchParams.get(`code`);if(!a){t.writeHead(400).end(`Missing authorization code.`);return}t.end(`Authorization received. Return to eve to finish connecting your ChatGPT subscription.`),i.resolve(a)});a.maxConnections=10;let abort=()=>i.reject(e.signal.reason);e.signal.addEventListener(`abort`,abort,{once:!0});try{e.signal.throwIfAborted();try{await new Promise((e,t)=>{a.once(`error`,t),a.listen(1455,`127.0.0.1`,e)})}catch(t){if(!isErrnoCode(t,`EADDRINUSE`))throw Error(`Could not start ChatGPT sign-in on localhost:1455. Free the port and retry from /model.`);return e.log(`Local sign-in port is in use. Continuing with a device code.`),await deviceLogin(e)}e.signal.throwIfAborted(),e.log(`Sign in to ChatGPT in your browser:\n${r.href}\nWaiting for sign-in. Press Ctrl+C to cancel.`),e.open(r.href);let n=await i.promise;return await requestChatGptTokens({grant_type:`authorization_code`,code:n,code_verifier:t,redirect_uri:REDIRECT_URI},e)}finally{e.signal.removeEventListener(`abort`,abort),a.closeAllConnections(),await new Promise(e=>a.close(()=>e()))}}async function deviceLogin(e){let t=await deviceRequest(`usercode`,{client_id:CHATGPT_CLIENT_ID},e);if(!t.ok)throw Error(`ChatGPT device sign-in is unavailable (HTTP ${t.status}). Enable device code authorization in ChatGPT Settings > Security, then retry from /model.`);let n=await readChatGptAuthResponse(t);if(!isObject(n)||typeof n.device_auth_id!=`string`||!n.device_auth_id||typeof n.user_code!=`string`||!/^[A-Z0-9-]{4,32}$/iu.test(n.user_code))throw Error(`ChatGPT returned an invalid device code. Retry from /model.`);let r=Math.min(30,Math.max(1,Number(n.interval)||5))*1e3,i=`${CHATGPT_ISSUER}/codex/device`;for(e.log(`Open ${i} and enter code: ${n.user_code}\nIf prompted, enable device code authorization in ChatGPT Settings > Security.\nWaiting for sign-in. Press Ctrl+C to cancel.`),e.open(i);;){await setTimeout$1(r+1e3,void 0,{signal:e.signal});let t=await deviceRequest(`token`,{device_auth_id:n.device_auth_id,user_code:n.user_code},e);if(t.status===403||t.status===404)continue;if(!t.ok)throw Error(`ChatGPT device sign-in failed (HTTP ${t.status}). Retry from /model.`);let i=await readChatGptAuthResponse(t);if(!isObject(i)||typeof i.authorization_code!=`string`||!i.authorization_code||typeof i.code_verifier!=`string`||!i.code_verifier)throw Error(`ChatGPT returned an invalid device authorization. Retry from /model.`);return requestChatGptTokens({grant_type:`authorization_code`,code:i.authorization_code,code_verifier:i.code_verifier,redirect_uri:`${CHATGPT_ISSUER}/deviceauth/callback`},e)}}async function deviceRequest(e,t,n){try{return await(n.fetch??fetch)(`${CHATGPT_ISSUER}/api/accounts/deviceauth/${e}`,{method:`POST`,headers:{"content-type":`application/json`,"user-agent":`eve`},body:JSON.stringify(t),redirect:`error`,signal:AbortSignal.any([n.signal,AbortSignal.timeout(3e4)])})}catch{throw n.signal.throwIfAborted(),Error(`Could not reach ChatGPT device sign-in. Check your connection and retry from /model.`)}}export{ensureChatGptAuth};
1
+ import{createHash,randomBytes}from"node:crypto";import{isErrnoCode,isObject}from"#shared/guards.js";import{createServer}from"node:http";import{spawn}from"node:child_process";import{WizardCancelledError}from"#setup/step.js";import{createProcessOutputBuffer}from"#setup/primitives/process-output.js";import{setTimeout as setTimeout$1}from"node:timers/promises";import{getDefaultCodexTokenBroker}from"#public/models/openai/chatgpt/token-broker.js";import{ChatGptInvalidStoredSessionError,getDefaultChatGptCredentialStore}from"#public/models/openai/chatgpt/credential-store.js";import{CHATGPT_CLIENT_ID,CHATGPT_ISSUER,readChatGptAuthResponse,requestChatGptTokens}from"#public/models/openai/chatgpt/oauth.js";import{openUrl}from"#setup/primitives/open-url.js";const REDIRECT_URI=`http://localhost:1455/auth/callback`;async function ensureChatGptAuth(e={}){let t=e.broker??getDefaultCodexTokenBroker(),n=e.store??getDefaultChatGptCredentialStore();e.signal?.throwIfAborted();let r=await t.refreshState();if(r.kind===`ready`)return;let i=t.credentialOwner();if(i===void 0)throw Error(`ChatGPT credential owner could not be resolved.`);if(i===`codex`){if(r.kind===`unavailable`)throw Error(r.reason);try{let n=e.log??(e=>process.stdout.write(`${e}\n`));await(e.codexLogin??(e=>loginWithCodex(e,n)))(e.signal),await assertChatGptAuthReady(t,`Codex login completed without a usable ChatGPT session.`);return}catch(e){if(!isErrnoCode(e,`ENOENT`))throw e;let n=await t.refreshState();if(t.credentialOwner()!==`eve`)throw e;if(n.kind===`ready`)return;if(n.kind===`unavailable`)throw Error(n.reason)}}try{await n.read()}catch(e){if(!(e instanceof ChatGptInvalidStoredSessionError))throw e}await signInWithOwnedCredentials(e,t,n)}async function signInWithOwnedCredentials(e,t,n){let r=new AbortController,cancel=()=>r.abort(new WizardCancelledError);process.once(`SIGINT`,cancel);let i=setTimeout(()=>r.abort(Error(`ChatGPT sign-in timed out. Retry from /model.`)),3e5),a=AbortSignal.any([r.signal,...e.signal?[e.signal]:[]]),o=e.log??(e=>process.stdout.write(`${e}\n`)),s=e.open??openUrl;try{let r=e.headless??!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)?await deviceLogin({...e,signal:a,log:o,open:s}):await browserLogin({...e,signal:a,log:o,open:s});a.throwIfAborted(),await n.update(async()=>(a.throwIfAborted(),r),{replace:!0}),await assertChatGptAuthReady(t,`ChatGPT sign-in could not be verified. Retry from /model.`),o(`ChatGPT subscription connected.`)}catch(e){throw a.throwIfAborted(),e}finally{clearTimeout(i),process.removeListener(`SIGINT`,cancel)}}async function assertChatGptAuthReady(e,t){if((await e.refreshState()).kind!==`ready`)throw Error(t)}async function loginWithCodex(e,t){let n=spawn(`codex`,[`login`],{stdio:[`ignore`,`pipe`,`pipe`],...e!==void 0&&{signal:e}}),r=createProcessOutputBuffer(({text:e})=>t(e));n.stdout.on(`data`,e=>r.write(`stdout`,e)),n.stderr.on(`data`,e=>r.write(`stderr`,e));try{await new Promise((e,t)=>{n.once(`error`,t),n.once(`close`,(n,r)=>{n===0?e():t(Error(`codex login failed (${r??n??`unknown`}).`))})})}finally{r.flush()}}async function browserLogin(e){let t=randomBytes(32).toString(`base64url`),n=randomBytes(32).toString(`base64url`),r=new URL(`${CHATGPT_ISSUER}/oauth/authorize`);r.search=new URLSearchParams({response_type:`code`,client_id:CHATGPT_CLIENT_ID,redirect_uri:REDIRECT_URI,scope:`openid profile email offline_access`,code_challenge:createHash(`sha256`).update(t).digest(`base64url`),code_challenge_method:`S256`,id_token_add_organizations:`true`,codex_cli_simplified_flow:`true`,state:n,originator:`eve`}).toString();let i=Promise.withResolvers();i.promise.catch(()=>{});let a=createServer({requestTimeout:1e4,headersTimeout:1e4,maxHeaderSize:8192},(e,t)=>{let r=URL.parse(e.url??``,REDIRECT_URI);if(t.setHeader(`content-type`,`text/plain; charset=utf-8`),t.setHeader(`cache-control`,`no-store`),e.method!==`GET`||r?.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found.`);return}if(r.searchParams.get(`state`)!==n){t.writeHead(400).end(`This sign-in belongs to another attempt. Return to eve and use its sign-in link.`);return}if(r.searchParams.has(`error`)){t.writeHead(400).end(`ChatGPT sign-in was declined. Return to eve to retry.`),i.reject(Error(`ChatGPT sign-in was declined. Retry from /model.`));return}let a=r.searchParams.get(`code`);if(!a){t.writeHead(400).end(`Missing authorization code.`);return}t.end(`Authorization received. Return to eve to finish connecting your ChatGPT subscription.`),i.resolve(a)});a.maxConnections=10;let abort=()=>i.reject(e.signal.reason);e.signal.addEventListener(`abort`,abort,{once:!0});try{e.signal.throwIfAborted();try{await new Promise((e,t)=>{a.once(`error`,t),a.listen(1455,`127.0.0.1`,e)})}catch(t){if(!isErrnoCode(t,`EADDRINUSE`))throw Error(`Could not start ChatGPT sign-in on localhost:1455. Free the port and retry from /model.`);return e.log(`Local sign-in port is in use. Continuing with a device code.`),await deviceLogin(e)}e.signal.throwIfAborted(),e.log(`Sign in to ChatGPT in your browser:\n${r.href}\nWaiting for sign-in. Press Ctrl+C to cancel.`),e.open(r.href);let n=await i.promise;return await requestChatGptTokens({grant_type:`authorization_code`,code:n,code_verifier:t,redirect_uri:REDIRECT_URI},e)}finally{e.signal.removeEventListener(`abort`,abort),a.closeAllConnections(),await new Promise(e=>a.close(()=>e()))}}async function deviceLogin(e){let t=await deviceRequest(`usercode`,{client_id:CHATGPT_CLIENT_ID},e);if(!t.ok)throw Error(`ChatGPT device sign-in is unavailable (HTTP ${t.status}). Enable device code authorization in ChatGPT Settings > Security, then retry from /model.`);let n=await readChatGptAuthResponse(t);if(!isObject(n)||typeof n.device_auth_id!=`string`||!n.device_auth_id||typeof n.user_code!=`string`||!/^[A-Z0-9-]{4,32}$/iu.test(n.user_code))throw Error(`ChatGPT returned an invalid device code. Retry from /model.`);let r=Math.min(30,Math.max(1,Number(n.interval)||5))*1e3,i=`${CHATGPT_ISSUER}/codex/device`;for(e.log(`Open ${i} and enter code: ${n.user_code}\nIf prompted, enable device code authorization in ChatGPT Settings > Security.\nWaiting for sign-in. Press Ctrl+C to cancel.`),e.open(i);;){await setTimeout$1(r+1e3,void 0,{signal:e.signal});let t=await deviceRequest(`token`,{device_auth_id:n.device_auth_id,user_code:n.user_code},e);if(t.status===403||t.status===404)continue;if(!t.ok)throw Error(`ChatGPT device sign-in failed (HTTP ${t.status}). Retry from /model.`);let i=await readChatGptAuthResponse(t);if(!isObject(i)||typeof i.authorization_code!=`string`||!i.authorization_code||typeof i.code_verifier!=`string`||!i.code_verifier)throw Error(`ChatGPT returned an invalid device authorization. Retry from /model.`);return requestChatGptTokens({grant_type:`authorization_code`,code:i.authorization_code,code_verifier:i.code_verifier,redirect_uri:`${CHATGPT_ISSUER}/deviceauth/callback`},e)}}async function deviceRequest(e,t,n){try{return await(n.fetch??fetch)(`${CHATGPT_ISSUER}/api/accounts/deviceauth/${e}`,{method:`POST`,headers:{"content-type":`application/json`,"user-agent":`eve`},body:JSON.stringify(t),redirect:`error`,signal:AbortSignal.any([n.signal,AbortSignal.timeout(3e4)])})}catch{throw n.signal.throwIfAborted(),Error(`Could not reach ChatGPT device sign-in. Check your connection and retry from /model.`)}}export{ensureChatGptAuth};
@@ -1,2 +1,2 @@
1
- import{createRegistrySession}from"./registry-session.js";import{PlannerNavigationError}from"#setup/prompter.js";import{WizardCancelledError}from"#setup/step.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{withSpinner}from"#setup/with-spinner.js";const PLANNER_STEPS=[`Channels`,`Integrations`,`Review`];var RegistryFlowFailedError=class extends Error{completed;constructor(e,t){super(e instanceof Error?e.message:String(e),{cause:e}),this.name=`RegistryFlowFailedError`,this.completed=t}};const SECTIONS={channels:{title:`Where should people reach your agent?`,description:`You can add more later with /add.`,featured:[`channel/web`,`channel/slack`,`channel/github`,`channel/linear-agent`,`channel/photon-imessage`],includes:e=>e.name.startsWith(`channel/`)},integrations:{title:`What should your agent be able to work with?`,featured:[`extension/github-tools`,`connection/linear`,`connection/notion`,`connection/vercel`,`extension/agent-browser`,`experimental/self-modification`],includes:e=>!e.name.startsWith(`channel/`)}};function label(e){return e.title??e.name.split(`/`).at(-1)??e.name}function isPlannerItem(e,t){return t.name.includes(`/`)&&SECTIONS[e].includes(t)}function orderedSectionItems(e,t){let n=t.filter(t=>isPlannerItem(e,t)),r=SECTIONS[e].featured.map(e=>n.find(t=>t.name===e)).filter(e=>e!==void 0),i=new Set(r.map(e=>e.address));return[...r,...n.filter(e=>!i.has(e.address))]}function plannerLabel(e){return e.name===`connection/linear`?`Linear MCP`:label(e)}function sectionRows(e,t){return orderedSectionItems(e,t).map(e=>({value:e.address,label:plannerLabel(e),hint:e.description}))}function selectedInSection(e,t,n){return t.filter(t=>isPlannerItem(e,t)&&n.has(t.address)).map(e=>e.address)}function plannerNavigation(e,t){let n=(t.plannerContext?.prefixSteps??[]).map(e=>({label:e.label,complete:e.complete}));return{kind:`planner`,activeStep:n.length+e,firstNavigableStep:n.length,steps:[...n,...PLANNER_STEPS.map((e,n)=>{if(n===2)return{label:e};let r=selectedInSection(n===0?`channels`:`integrations`,t.catalog,t.selected).length;return r===0?{label:e}:{label:e,count:r}})]}}function replaceSectionSelection(e){for(let t of e.catalog)isPlannerItem(e.section,t)&&e.selected.delete(t.address);for(let t of e.addresses)e.selected.add(t)}async function editSection(e){let{section:t,catalog:n,prompter:r,selected:i}=e,a={message:SECTIONS[t].title,multiple:!0,search:!0,placeholder:t===`channels`?`Search channels`:`Search integrations`,navigation:plannerNavigation(t===`channels`?0:1,e),initialValues:selectedInSection(t,n,i),options:sectionRows(t,n)};t===`channels`&&(a.description=SECTIONS.channels.description),e.notices!==void 0&&(a.notices=e.notices);try{return replaceSectionSelection({section:t,catalog:n,selected:i,addresses:await r.select(a)}),`forward`}catch(e){if(!(e instanceof PlannerNavigationError))throw e;return replaceSectionSelection({section:t,catalog:n,selected:i,addresses:e.values.map(e=>{if(typeof e!=`string`)throw Error(`Registry planner returned a non-string item.`);return e})}),e.direction}}async function editPlan(e){let t=`channels`,n=e.notices;for(;;){if(t!==`review`){e.onScreen?.({screen:t===`channels`?`registry_channels`:`registry_integrations`});try{let r=await editSection({...e,section:t,notices:n});n=void 0,r===`back`?t===`integrations`&&(t=`channels`):t=t===`channels`?`integrations`:`review`}catch(e){if(!(e instanceof WizardCancelledError))throw e;return`cancelled`}continue}try{e.onScreen?.({screen:`registry_review`,registrySelectedCount:e.selected.size});let t=e.selected.size>0,r=[...e.selected].map(t=>{let n=e.itemsByAddress.get(t);if(n===void 0)throw Error(`Registry item "${t}" is no longer available.`);return n}),i=r.filter(e=>e.name.startsWith(`channel/`)),a=r.filter(e=>!e.name.startsWith(`channel/`)),o=[...i.length===0?[]:[{label:`Channels`,value:i.map(label).join(`, `)}],...a.length===0?[]:[{label:`Integrations`,value:a.map(label).join(`, `)}]],s={message:e.plannerContext?.reviewMessage??`Review additions`,metadata:[...e.plannerContext?.reviewMetadata??[],...o],navigation:plannerNavigation(2,e),options:[{value:`install`,label:t?e.plannerContext?.primaryActionLabel??`Install and set up`:e.plannerContext?.emptyActionLabel??`Finish without adding`},{value:`back`,label:`Back`}]};t||(s.description=`No channels or integrations selected.`),n!==void 0&&(s.notices=n);let c=await e.prompter.select(s);if(n=void 0,c===`install`)return`install`}catch(e){if(e instanceof PlannerNavigationError&&e.direction===`back`){t=`integrations`;continue}if(!(e instanceof WizardCancelledError))throw e;return`cancelled`}t=`integrations`}}function hasSettledOutcomes(e){return e!==void 0&&(e.items.length>0||e.failures.length>0||e.outcomes!==void 0)}async function runRegistryFlow(e){let t;try{let n=e.initialAddress?.trim(),r;if(n!==void 0&&n!==``){if(await e.prompter.select({message:`Add ${n}?`,options:[{value:`install`,label:`Install and set up`},{value:`cancel`,label:`Cancel`}]})===`cancel`)return{kind:`cancelled`};r=[{address:n,name:n,source:`Registry`}]}else{let t=e.deps?.browseRegistryCatalog??(await import(`#cli/commands/registry.js`)).browseRegistryCatalog,n=await withSpinner(e.prompter,`Loading registry…`,()=>t(e.appRoot)),i=[...n.items],a=new Set,o=n.errors.map(e=>({tone:`warning`,text:`${e.registry}: ${e.message}`})),s=new Map(i.map(e=>[e.address,e]));if(await editPlan({prompter:e.prompter,catalog:i,itemsByAddress:s,selected:a,notices:o,plannerContext:e.plannerContext,onScreen:e.onScreen})!==`install`)return{kind:`cancelled`};r=[...a].map(e=>{let t=s.get(e);if(t===void 0)throw Error(`Registry item "${e}" is no longer available.`);return t})}let i=e.deps?.installRegistryItem??(await import(`#cli/commands/registry.js`)).installRegistryItem,a=e.deps?.detectDeployment??(await import(`#setup/project-resolution.js`)).detectDeployment,o=e.deps?.runDeployFlow??(await import(`./deploy.js`)).runDeployFlow;t=createRegistrySession({detectDeployment:a,runDeployFlow:o}),e.onScreen?.({screen:`registry_install`});let s=t;for(let[t,n]of r.entries()){e.signal?.throwIfAborted(),e.onItemStart?.(n,t,r.length);try{let install=(t=e.signal)=>i(e.appRoot,n.address,{silent:!0,prompter:e.prompter,signal:t}),run=()=>e.runItem===void 0?install():e.runItem(install),t=await(e.prompter.withExclusiveTerminal?.(run)??run());s.add(label(n),t.output,t.setup)}catch(t){if(e.signal?.throwIfAborted(),t instanceof WizardCancelledError){s.addCancellation(label(n));continue}if(t instanceof HumanActionRequiredError)throw t;let r=(t instanceof Error?t.message:String(t)).trim()||`Installation failed.`,i=r.split(`
1
+ import{createRegistrySession}from"./registry-session.js";import{PlannerNavigationError}from"#setup/prompter.js";import{WizardCancelledError}from"#setup/step.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{withSpinner}from"#setup/with-spinner.js";const PLANNER_STEPS=[`Channels`,`Integrations`,`Review`];var RegistryFlowFailedError=class extends Error{completed;constructor(e,t){super(e instanceof Error?e.message:String(e),{cause:e}),this.name=`RegistryFlowFailedError`,this.completed=t}};const SECTIONS={channels:{title:`Where should people reach your agent?`,description:`You can add more later with /add.`,featured:[`channel/web`,`channel/slack`,`channel/github`,`channel/linear`,`channel/photon-imessage`],includes:e=>e.name.startsWith(`channel/`)},integrations:{title:`What should your agent be able to work with?`,featured:[`extension/github-tools`,`connection/linear`,`connection/notion`,`connection/vercel`,`extension/agent-browser`,`eve/self-modification`],includes:e=>!e.name.startsWith(`channel/`)}};function label(e){return e.title??e.name.split(`/`).at(-1)??e.name}function isPlannerItem(e,t){return t.name.includes(`/`)&&SECTIONS[e].includes(t)}function orderedSectionItems(e,t){let n=t.filter(t=>isPlannerItem(e,t)),r=SECTIONS[e].featured.map(e=>n.find(t=>t.name===e)).filter(e=>e!==void 0),i=new Set(r.map(e=>e.address));return[...r,...n.filter(e=>!i.has(e.address))]}function plannerLabel(e){return e.name===`connection/linear`?`Linear MCP`:label(e)}function sectionRows(e,t){return orderedSectionItems(e,t).map(e=>({value:e.address,label:plannerLabel(e),hint:e.description}))}function selectedInSection(e,t,n){return t.filter(t=>isPlannerItem(e,t)&&n.has(t.address)).map(e=>e.address)}function plannerNavigation(e,t){let n=(t.plannerContext?.prefixSteps??[]).map(e=>({label:e.label,complete:e.complete}));return{kind:`planner`,activeStep:n.length+e,firstNavigableStep:n.length,steps:[...n,...PLANNER_STEPS.map((e,n)=>{if(n===2)return{label:e};let r=selectedInSection(n===0?`channels`:`integrations`,t.catalog,t.selected).length;return r===0?{label:e}:{label:e,count:r}})]}}function replaceSectionSelection(e){for(let t of e.catalog)isPlannerItem(e.section,t)&&e.selected.delete(t.address);for(let t of e.addresses)e.selected.add(t)}async function editSection(e){let{section:t,catalog:n,prompter:r,selected:i}=e,a={message:SECTIONS[t].title,multiple:!0,search:!0,placeholder:t===`channels`?`Search channels`:`Search integrations`,navigation:plannerNavigation(t===`channels`?0:1,e),initialValues:selectedInSection(t,n,i),options:sectionRows(t,n)};t===`channels`&&(a.description=SECTIONS.channels.description),e.notices!==void 0&&(a.notices=e.notices);try{return replaceSectionSelection({section:t,catalog:n,selected:i,addresses:await r.select(a)}),`forward`}catch(e){if(!(e instanceof PlannerNavigationError))throw e;return replaceSectionSelection({section:t,catalog:n,selected:i,addresses:e.values.map(e=>{if(typeof e!=`string`)throw Error(`Registry planner returned a non-string item.`);return e})}),e.direction}}async function editPlan(e){let t=`channels`,n=e.notices;for(;;){if(t!==`review`){e.onScreen?.({screen:t===`channels`?`registry_channels`:`registry_integrations`});try{let r=await editSection({...e,section:t,notices:n});n=void 0,r===`back`?t===`integrations`&&(t=`channels`):t=t===`channels`?`integrations`:`review`}catch(e){if(!(e instanceof WizardCancelledError))throw e;return`cancelled`}continue}try{e.onScreen?.({screen:`registry_review`,registrySelectedCount:e.selected.size});let t=e.selected.size>0,r=[...e.selected].map(t=>{let n=e.itemsByAddress.get(t);if(n===void 0)throw Error(`Registry item "${t}" is no longer available.`);return n}),i=r.filter(e=>e.name.startsWith(`channel/`)),a=r.filter(e=>!e.name.startsWith(`channel/`)),o=[...i.length===0?[]:[{label:`Channels`,value:i.map(label).join(`, `)}],...a.length===0?[]:[{label:`Integrations`,value:a.map(label).join(`, `)}]],s={message:e.plannerContext?.reviewMessage??`Review additions`,metadata:[...e.plannerContext?.reviewMetadata??[],...o],navigation:plannerNavigation(2,e),options:[{value:`install`,label:t?e.plannerContext?.primaryActionLabel??`Install and set up`:e.plannerContext?.emptyActionLabel??`Finish without adding`},{value:`back`,label:`Back`}]};t||(s.description=`No channels or integrations selected.`),n!==void 0&&(s.notices=n);let c=await e.prompter.select(s);if(n=void 0,c===`install`)return`install`}catch(e){if(e instanceof PlannerNavigationError&&e.direction===`back`){t=`integrations`;continue}if(!(e instanceof WizardCancelledError))throw e;return`cancelled`}t=`integrations`}}function hasSettledOutcomes(e){return e!==void 0&&(e.items.length>0||e.failures.length>0||e.outcomes!==void 0)}async function runRegistryFlow(e){let t;try{let n=e.initialAddress?.trim(),r;if(n!==void 0&&n!==``){if(await e.prompter.select({message:`Add ${n}?`,options:[{value:`install`,label:`Install and set up`},{value:`cancel`,label:`Cancel`}]})===`cancel`)return{kind:`cancelled`};r=[{address:n,name:n,source:`Registry`}]}else{let t=e.deps?.browseRegistryCatalog??(await import(`#cli/commands/registry.js`)).browseRegistryCatalog,n=await withSpinner(e.prompter,`Loading registry…`,()=>t(e.appRoot)),i=[...n.items],a=new Set,o=n.errors.map(e=>({tone:`warning`,text:`${e.registry}: ${e.message}`})),s=new Map(i.map(e=>[e.address,e]));if(await editPlan({prompter:e.prompter,catalog:i,itemsByAddress:s,selected:a,notices:o,plannerContext:e.plannerContext,onScreen:e.onScreen})!==`install`)return{kind:`cancelled`};r=[...a].map(e=>{let t=s.get(e);if(t===void 0)throw Error(`Registry item "${e}" is no longer available.`);return t})}let i=e.deps?.installRegistryItem??(await import(`#cli/commands/registry.js`)).installRegistryItem,a=e.deps?.detectDeployment??(await import(`#setup/project-resolution.js`)).detectDeployment,o=e.deps?.runDeployFlow??(await import(`./deploy.js`)).runDeployFlow;t=createRegistrySession({detectDeployment:a,runDeployFlow:o}),e.onScreen?.({screen:`registry_install`});let s=t;for(let[t,n]of r.entries()){e.signal?.throwIfAborted(),e.onItemStart?.(n,t,r.length);try{let install=(t=e.signal)=>i(e.appRoot,n.address,{silent:!0,prompter:e.prompter,signal:t}),run=()=>e.runItem===void 0?install():e.runItem(install),t=await(e.prompter.withExclusiveTerminal?.(run)??run());s.add(label(n),t.output,t.setup)}catch(t){if(e.signal?.throwIfAborted(),t instanceof WizardCancelledError){s.addCancellation(label(n));continue}if(t instanceof HumanActionRequiredError)throw t;let r=(t instanceof Error?t.message:String(t)).trim()||`Installation failed.`,i=r.split(`
2
2
  `).find(e=>e.trim()!==``);s.addFailure(label(n),r);let a={message:`Couldn't add ${label(n)}`,options:[{value:`skip`,label:`Skip ${label(n)}`},{value:`cancel`,label:`Cancel setup`}]};if(i!==void 0&&(a.description=i),await e.prompter.select(a)===`cancel`)return{kind:`done`,result:{...s.result(),cancelled:!0}}}}return{kind:`done`,result:await s.continueAfterInstall({appRoot:e.appRoot,prompter:e.prompter,signal:e.signal})}}catch(e){if(e instanceof WizardCancelledError){let e=t?.result();return hasSettledOutcomes(e)?{kind:`done`,result:{...e,cancelled:!0}}:{kind:`cancelled`}}let n=t?.result();throw hasSettledOutcomes(n)?new RegistryFlowFailedError(e,n):e}}export{RegistryFlowFailedError,runRegistryFlow};