eve 0.24.5 → 0.25.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 (161) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/channel/cancel.d.ts +8 -0
  3. package/dist/src/channel/cancel.js +1 -0
  4. package/dist/src/channel/routes.d.ts +25 -4
  5. package/dist/src/channel/session.d.ts +10 -1
  6. package/dist/src/channel/session.js +1 -1
  7. package/dist/src/channel/types.d.ts +8 -0
  8. package/dist/src/chunks/{use-eve-agent-8rerxDHY.js → use-eve-agent-CQIeqmKc.js} +73 -66
  9. package/dist/src/chunks/{use-eve-agent-DhgdHzDG.js → use-eve-agent-Cy73lgA6.js} +73 -66
  10. package/dist/src/cli/commands/agent-instructions.js +1 -1
  11. package/dist/src/cli/commands/channels.js +1 -1
  12. package/dist/src/cli/commands/extension-build.d.ts +1 -1
  13. package/dist/src/cli/commands/extension-build.js +1 -1
  14. package/dist/src/client/output-schema.d.ts +0 -7
  15. package/dist/src/client/output-schema.js +1 -1
  16. package/dist/src/client/session.d.ts +6 -2
  17. package/dist/src/client/session.js +1 -1
  18. package/dist/src/compiler/extension-compatibility.d.ts +56 -0
  19. package/dist/src/compiler/extension-compatibility.js +1 -0
  20. package/dist/src/compiler/normalize-agent-config.js +1 -1
  21. package/dist/src/compiler/normalize-subagent.js +1 -1
  22. package/dist/src/context/build-dynamic-tools.js +1 -1
  23. package/dist/src/context/dynamic-tool-lifecycle.d.ts +1 -1
  24. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  25. package/dist/src/discover/discover-agent.d.ts +29 -7
  26. package/dist/src/discover/discover-agent.js +1 -1
  27. package/dist/src/discover/extensions.d.ts +43 -8
  28. package/dist/src/discover/extensions.js +1 -1
  29. package/dist/src/discover/filesystem.d.ts +3 -1
  30. package/dist/src/discover/filesystem.js +1 -1
  31. package/dist/src/discover/named-source-directory.js +1 -1
  32. package/dist/src/discover/skills.js +1 -1
  33. package/dist/src/evals/autoevals-client.js +2 -2
  34. package/dist/src/execution/node-step.js +1 -1
  35. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  36. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +1 -1
  37. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  38. package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
  39. package/dist/src/execution/sandbox/development-cleanup.d.ts +1 -1
  40. package/dist/src/execution/sandbox/development-cleanup.js +1 -1
  41. package/dist/src/execution/sandbox/development-run.d.ts +0 -3
  42. package/dist/src/execution/sandbox/development-run.js +1 -1
  43. package/dist/src/execution/sandbox/ensure.js +1 -1
  44. package/dist/src/execution/subagent-tool.js +1 -1
  45. package/dist/src/execution/workflow-runtime.js +1 -1
  46. package/dist/src/harness/emission.js +1 -1
  47. package/dist/src/harness/input-extraction.d.ts +10 -1
  48. package/dist/src/harness/input-extraction.js +1 -1
  49. package/dist/src/harness/input-requests.d.ts +12 -2
  50. package/dist/src/harness/input-requests.js +1 -1
  51. package/dist/src/harness/messages.d.ts +8 -1
  52. package/dist/src/harness/messages.js +1 -1
  53. package/dist/src/harness/stale-input-responses.d.ts +26 -0
  54. package/dist/src/harness/stale-input-responses.js +3 -0
  55. package/dist/src/harness/step-hooks.d.ts +1 -12
  56. package/dist/src/harness/step-hooks.js +1 -1
  57. package/dist/src/harness/tool-call-input-errors.d.ts +11 -0
  58. package/dist/src/harness/tool-call-input-errors.js +1 -1
  59. package/dist/src/harness/tool-loop.js +2 -2
  60. package/dist/src/harness/workflow-sandbox.d.ts +1 -1
  61. package/dist/src/harness/workflow-sandbox.js +1 -1
  62. package/dist/src/internal/application/optional-package-install.d.ts +5 -0
  63. package/dist/src/internal/application/optional-package-install.js +1 -1
  64. package/dist/src/internal/application/package.js +1 -1
  65. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  66. package/dist/src/internal/authored-module-loader.d.ts +17 -0
  67. package/dist/src/internal/authored-module-loader.js +2 -2
  68. package/dist/src/internal/authored-module-map-loader.js +1 -1
  69. package/dist/src/internal/authored-package-boundary.d.ts +8 -0
  70. package/dist/src/internal/authored-package-boundary.js +1 -1
  71. package/dist/src/internal/nitro/dev-runtime-source-snapshot.d.ts +4 -0
  72. package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
  73. package/dist/src/internal/nitro/host/build-extension.d.ts +6 -21
  74. package/dist/src/internal/nitro/host/build-extension.js +2 -4
  75. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
  76. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  77. package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +18 -0
  78. package/dist/src/internal/nitro/host/dev-workspace-extensions.js +1 -0
  79. package/dist/src/internal/nitro/host/extension-build-config.d.ts +18 -0
  80. package/dist/src/internal/nitro/host/extension-build-config.js +1 -0
  81. package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +10 -0
  82. package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -0
  83. package/dist/src/internal/nitro/host/extension-declarations.d.ts +10 -0
  84. package/dist/src/internal/nitro/host/extension-declarations.js +2 -0
  85. package/dist/src/internal/nitro/host/extension-distribution.d.ts +32 -0
  86. package/dist/src/internal/nitro/host/extension-distribution.js +3 -0
  87. package/dist/src/internal/nitro/host/extension-state-usage.d.ts +7 -0
  88. package/dist/src/internal/nitro/host/extension-state-usage.js +1 -0
  89. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -1
  90. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  91. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  92. package/dist/src/internal/nitro/host/types.d.ts +2 -0
  93. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  94. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  95. package/dist/src/public/channels/index.d.ts +1 -1
  96. package/dist/src/public/definitions/channel.d.ts +1 -1
  97. package/dist/src/public/definitions/tool.d.ts +2 -2
  98. package/dist/src/public/tools/internal.js +1 -1
  99. package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
  100. package/dist/src/runtime/connections/openapi-client.js +1 -1
  101. package/dist/src/runtime/framework-tools/ask-question.d.ts +23 -9
  102. package/dist/src/runtime/framework-tools/ask-question.js +1 -1
  103. package/dist/src/runtime/framework-tools/bash.d.ts +10 -3
  104. package/dist/src/runtime/framework-tools/bash.js +1 -1
  105. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
  106. package/dist/src/runtime/framework-tools/final-output.d.ts +1 -1
  107. package/dist/src/runtime/framework-tools/final-output.js +1 -1
  108. package/dist/src/runtime/framework-tools/glob.d.ts +12 -3
  109. package/dist/src/runtime/framework-tools/glob.js +1 -1
  110. package/dist/src/runtime/framework-tools/grep.d.ts +16 -3
  111. package/dist/src/runtime/framework-tools/grep.js +1 -1
  112. package/dist/src/runtime/framework-tools/read-file.d.ts +13 -3
  113. package/dist/src/runtime/framework-tools/read-file.js +1 -1
  114. package/dist/src/runtime/framework-tools/skill.d.ts +5 -2
  115. package/dist/src/runtime/framework-tools/skill.js +1 -1
  116. package/dist/src/runtime/framework-tools/todo.d.ts +57 -10
  117. package/dist/src/runtime/framework-tools/todo.js +3 -3
  118. package/dist/src/runtime/framework-tools/web-fetch.d.ts +16 -3
  119. package/dist/src/runtime/framework-tools/web-fetch.js +1 -1
  120. package/dist/src/runtime/framework-tools/write-file.d.ts +9 -3
  121. package/dist/src/runtime/framework-tools/write-file.js +1 -1
  122. package/dist/src/runtime/loaders/compile-metadata.js +1 -1
  123. package/dist/src/runtime/loaders/manifest.js +1 -1
  124. package/dist/src/runtime/loaders/module-map.js +1 -1
  125. package/dist/src/runtime/resolve-tool.d.ts +4 -5
  126. package/dist/src/runtime/resolve-tool.js +1 -1
  127. package/dist/src/runtime/subagents/registry.d.ts +6 -3
  128. package/dist/src/runtime/subagents/registry.js +1 -1
  129. package/dist/src/runtime/tools/registry.js +1 -1
  130. package/dist/src/runtime/types.d.ts +7 -9
  131. package/dist/src/setup/boxes/deploy-project.d.ts +11 -1
  132. package/dist/src/setup/boxes/deploy-project.js +1 -1
  133. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  134. package/dist/src/setup/scaffold/create/extension.js +2 -2
  135. package/dist/src/setup/scaffold/create/project.js +2 -2
  136. package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
  137. package/dist/src/setup/scaffold/create/web-template.js +1 -0
  138. package/dist/src/setup/scaffold/update/channels.js +2 -2
  139. package/dist/src/setup/scaffold/update/connections.js +1 -1
  140. package/dist/src/setup/vercel-project-framework.d.ts +4 -2
  141. package/dist/src/shared/extension-package-contract.d.ts +11 -0
  142. package/dist/src/shared/extension-package-contract.js +1 -0
  143. package/dist/src/shared/json.d.ts +4 -0
  144. package/dist/src/shared/json.js +1 -1
  145. package/dist/src/shared/tool-schema.d.ts +52 -0
  146. package/dist/src/shared/tool-schema.js +1 -0
  147. package/dist/src/svelte/index.js +1 -1
  148. package/dist/src/svelte/use-eve-agent.js +1 -1
  149. package/dist/src/vue/index.js +1 -1
  150. package/dist/src/vue/use-eve-agent.js +1 -1
  151. package/docs/channels/custom.mdx +32 -2
  152. package/docs/concepts/sessions-runs-and-streaming.md +8 -0
  153. package/docs/extensions.md +22 -6
  154. package/docs/reference/cli.md +2 -2
  155. package/package.json +2 -2
  156. package/dist/src/internal/json-schema.d.ts +0 -1
  157. package/dist/src/internal/json-schema.js +0 -1
  158. package/dist/src/setup/boxes/reconcile-host-framework-preset.d.ts +0 -26
  159. package/dist/src/setup/boxes/reconcile-host-framework-preset.js +0 -1
  160. package/dist/src/shared/json-schema.d.ts +0 -9
  161. package/dist/src/shared/json-schema.js +0 -1
@@ -0,0 +1,18 @@
1
+ /** Resolved producer inputs for an extension package. */
2
+ export interface ExtensionBuildConfig {
3
+ /** Absolute authoring root from `eve.extension.source`. */
4
+ readonly sourceRoot: string;
5
+ /** Absolute agent-shaped distribution root from `eve.extension.dist`. */
6
+ readonly distRoot: string;
7
+ /** Directory containing the dist root and generated package entrypoints. */
8
+ readonly outDir: string;
9
+ readonly packageName: string;
10
+ /** Short package name used for the generated named mount export. */
11
+ readonly shortName: string;
12
+ /** Packages allowed to remain as imports in the published distribution. */
13
+ readonly runtimeDependencies: readonly string[];
14
+ }
15
+ /** Reads and validates the extension producer contract from `package.json`. */
16
+ export declare function tryReadExtensionBuildConfig(rootDir: string): Promise<ExtensionBuildConfig | null>;
17
+ /** Ensures package exports point at the build output's generated entrypoints. */
18
+ export declare function ensureExtensionExports(appRoot: string, outDir: string): Promise<void>;
@@ -0,0 +1 @@
1
+ import{dirname,join,relative,resolve,sep}from"node:path";import{readFile,writeFile}from"node:fs/promises";import{parseExtensionPackageRoots}from"#shared/extension-package-contract.js";async function tryReadExtensionBuildConfig(n){let o=resolve(n),c;try{c=JSON.parse(await readFile(join(o,`package.json`),`utf8`))}catch{return null}let l=parseExtensionPackageRoots(c.eve?.extension);if(l===null)return null;if(l.source===void 0)throw Error("`eve.extension.dist` is declared without `eve.extension.source`. Building an extension requires the authoring root; add `eve.extension.source` to package.json.");let u=resolve(o,l.source),d=resolve(o,l.dist),f=dirname(d);if(assertManagedPackagePath(o,u,`eve.extension.source`),assertManagedPackagePath(o,d,`eve.extension.dist`),assertManagedPackagePath(o,f,`eve.extension.dist output directory`),u===d)throw Error("`eve.extension.source` and `eve.extension.dist` must be different paths.");if(u===f||u.startsWith(`${f}${sep}`)||f.startsWith(`${u}${sep}`))throw Error("`eve.extension.source` and the managed dist output cannot overlap.");let p=typeof c.name==`string`&&c.name.length>0?c.name:`extension`;return{sourceRoot:u,distRoot:d,outDir:f,packageName:p,shortName:safeJsIdentifier(p.slice(p.lastIndexOf(`/`)+1)),runtimeDependencies:[...new Set([...Object.keys(c.dependencies??{}),...Object.keys(c.optionalDependencies??{}),...Object.keys(c.peerDependencies??{})])].sort()}}async function ensureExtensionExports(e,r){let i=join(e,`package.json`),s=await readFile(i,`utf8`),c=JSON.parse(s),l=relative(e,r).replaceAll(`\\`,`/`),u=l.startsWith(`.`)?l:`./${l}`,d={".":{types:`${u}/index.d.ts`,default:`${u}/index.mjs`},"./tools":{types:`${u}/tools/index.d.ts`,default:`${u}/tools/index.mjs`}},f=typeof c.exports==`object`&&c.exports!==null&&!Array.isArray(c.exports)?c.exports:{},p=!1;for(let[e,t]of Object.entries(d)){let n=f[e];typeof n==`object`&&n&&n.types===t.types&&n.default===t.default||(f[e]=t,p=!0)}p&&(c.exports=f,await writeFile(i,`${JSON.stringify(c,null,2)}\n`,`utf8`))}function assertManagedPackagePath(e,t,r){let a=relative(e,t);if(a===``||a===`..`||a.startsWith(`..${sep}`))throw Error(`\`${r}\` must point to a directory inside the extension package.`)}function safeJsIdentifier(e){let t=e.replace(/[^A-Za-z0-9_$]/g,`_`);return/^[A-Za-z_$]/.test(t)?t:`_${t}`}export{ensureExtensionExports,tryReadExtensionBuildConfig};
@@ -0,0 +1,10 @@
1
+ import { type ExtensionCapabilityRequirements } from "#compiler/extension-compatibility.js";
2
+ import type { AgentSourceManifest } from "#discover/manifest.js";
3
+ import type { ModuleSourceRef } from "#shared/source-ref.js";
4
+ /** Derives only the extension-facing contracts used by one authored tree. */
5
+ export declare function deriveExtensionCapabilityRequirements(input: {
6
+ readonly declarationModule: ModuleSourceRef;
7
+ readonly manifest: AgentSourceManifest;
8
+ readonly runtimeDependencies: readonly string[];
9
+ readonly sourceRoot: string;
10
+ }): Promise<ExtensionCapabilityRequirements>;
@@ -0,0 +1 @@
1
+ import{join}from"node:path";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";import{EXTENSION_CAPABILITY_VERSIONS}from"#compiler/extension-compatibility.js";import{extensionUsesState}from"#internal/nitro/host/extension-state-usage.js";async function deriveExtensionCapabilityRequirements(t){let n=new Set([`extension`]),r={externalDependencies:t.runtimeDependencies},[i,a,o,s,c]=await Promise.all([Promise.all(t.manifest.tools.map(e=>compileToolEntry(t.sourceRoot,e,r))),Promise.all(t.manifest.skills.map(e=>compileSkillSource(t.sourceRoot,e,r))),Promise.all(t.manifest.instructions.map(e=>compileInstructionsEntry(t.sourceRoot,e,r))),loadAuthoredModuleNamespace(join(t.sourceRoot,t.declarationModule.logicalPath),{externalDependencies:t.runtimeDependencies}),extensionUsesState(t.sourceRoot)]);i.length>0&&n.add(`tool`),i.some(e=>e.kind===`dynamic-tool`)&&n.add(`dynamicTool`),t.manifest.connections.length>0&&n.add(`connection`),t.manifest.hooks.length>0&&n.add(`hook`),a.length>0&&n.add(`skill`),a.some(e=>e.kind===`dynamic-skill`)&&n.add(`dynamicSkill`),o.length>0&&n.add(`instructions`),o.some(e=>e.kind===`dynamic-instructions`)&&n.add(`dynamicInstructions`);let l=s[t.declarationModule.exportName??`default`];return(typeof l==`function`||typeof l==`object`&&l)&&`schema`in l&&l.schema!==void 0&&n.add(`config`),c&&n.add(`state`),Object.fromEntries(Object.keys(EXTENSION_CAPABILITY_VERSIONS).filter(e=>n.has(e)).map(e=>[e,EXTENSION_CAPABILITY_VERSIONS[e]]))}export{deriveExtensionCapabilityRequirements};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Emits declarations for an extension source tree using the extension's own
3
+ * TypeScript installation and authored tsconfig when available.
4
+ */
5
+ export declare function emitExtensionDeclarations(input: {
6
+ readonly appRoot: string;
7
+ readonly declarationsRoot: string;
8
+ readonly moduleLogicalPaths: readonly string[];
9
+ readonly sourceRoot: string;
10
+ }): Promise<void>;
@@ -0,0 +1,2 @@
1
+ import{createRequire}from"node:module";import{dirname,join,relative}from"node:path";import{readFile,readdir,stat}from"node:fs/promises";import{execFile}from"node:child_process";import{promisify}from"node:util";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";async function emitExtensionDeclarations(e){let t=await resolveTypeScriptBinary(e.appRoot),n=join(e.appRoot,`tsconfig.json`),r=await stat(n).then(e=>e.isFile()).catch(()=>!1),i=[`--declaration`,`--emitDeclarationOnly`,`--noEmit`,`false`,`--noEmitOnError`,`true`,`--rootDir`,e.appRoot,`--outDir`,e.declarationsRoot,`--pretty`,`false`],s=r?[`--project`,n,...i]:[...i,`--allowJs`,`--checkJs`,`false`,`--module`,`esnext`,`--moduleResolution`,`bundler`,`--target`,`ES2022`,`--skipLibCheck`,`true`,...await collectDeclarationInputs(e.sourceRoot)];try{await promisify(execFile)(process.execPath,[t,...s],{cwd:e.appRoot,maxBuffer:10*1024*1024})}catch(e){let t=declarationEmitOutput(e);throw Error(`Cannot emit extension declarations${t.length>0?`:\n${t}`:`.`}`,{cause:e})}await assertModuleDeclarationsEmitted(e)}async function assertModuleDeclarationsEmitted(e){let t=relative(e.appRoot,e.sourceRoot),r=(await Promise.all(e.moduleLogicalPaths.map(async n=>await stat(join(e.declarationsRoot,t,declarationLogicalPath(n))).then(e=>e.isFile()).catch(()=>!1)?void 0:n))).filter(e=>e!==void 0);if(r.length===0)return;if(r.length===e.moduleLogicalPaths.length)throw Error(`TypeScript emitted no declarations for "${t}". Ensure the package tsconfig.json \`include\` covers every module under \`eve.extension.source\`.`);let i=r.length===1?`module`:`modules`;throw Error(`TypeScript emitted no declaration for extension ${i} ${r.map(e=>JSON.stringify(e)).join(`, `)}. Include ${r.length===1?`it`:`them`} in the package tsconfig.json before publishing the extension.`)}function declarationLogicalPath(e){if(e.endsWith(`.mts`)||e.endsWith(`.mjs`))return`${e.slice(0,-4)}.d.mts`;if(e.endsWith(`.cts`)||e.endsWith(`.cjs`))return`${e.slice(0,-4)}.d.cts`;if(e.endsWith(`.ts`)||e.endsWith(`.js`))return`${e.slice(0,-3)}.d.ts`;throw Error(`Unsupported extension module path "${e}".`)}async function collectDeclarationInputs(e){let t=[];for(let n of await readdir(e,{withFileTypes:!0})){let r=join(e,n.name);n.isDirectory()?t.push(...await collectDeclarationInputs(r)):n.isFile()&&SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS.some(e=>n.name.endsWith(e))&&t.push(r)}return t.sort()}function declarationEmitOutput(e){if(!(e instanceof Error))return String(e);let t=e;return[t.stdout,t.stderr,t.message].filter(e=>typeof e==`string`&&e.trim().length>0).join(`
2
+ `).trim()}async function resolveTypeScriptBinary(n){for(let i of[join(n,`package.json`),import.meta.url]){let n;try{n=createRequire(i).resolve(`typescript/package.json`)}catch{continue}let a=JSON.parse(await readFile(n,`utf8`)),o=typeof a.bin==`string`?a.bin:a.bin?.tsc;if(o!==void 0)return join(dirname(n),o)}throw Error("Cannot build an eve extension without TypeScript. Add `typescript` to the package's devDependencies.")}export{emitExtensionDeclarations};
@@ -0,0 +1,32 @@
1
+ import type { AgentSourceManifest } from "#discover/manifest.js";
2
+ import type { ModuleSourceRef } from "#shared/source-ref.js";
3
+ /** Emits the runnable, agent-shaped tree and its package entrypoints into staging. */
4
+ export declare function emitExtensionDistribution(input: {
5
+ readonly appRoot: string;
6
+ readonly declarationModule: ModuleSourceRef;
7
+ readonly declarationsRoot: string;
8
+ readonly manifest: AgentSourceManifest;
9
+ readonly runtimeDependencies: readonly string[];
10
+ readonly shortName: string;
11
+ readonly sourceRoot: string;
12
+ readonly stagedDistRoot: string;
13
+ readonly stagedOutDir: string;
14
+ readonly transactionRoot: string;
15
+ }): Promise<void>;
16
+ /**
17
+ * Thrown when publishing failed and the prior output could not be moved back.
18
+ * The prior output survives at {@link preservedOutputPath}; callers must not
19
+ * delete the transaction directory that contains it.
20
+ */
21
+ export declare class ExtensionOutputRestoreError extends Error {
22
+ readonly preservedOutputPath: string;
23
+ constructor(preservedOutputPath: string, options: {
24
+ cause: unknown;
25
+ });
26
+ }
27
+ /** Atomically publishes a staged extension output, restoring the prior tree on failure. */
28
+ export declare function replaceExtensionBuildOutput(input: {
29
+ readonly outDir: string;
30
+ readonly stagedOutDir: string;
31
+ readonly transactionRoot: string;
32
+ }): Promise<void>;
@@ -0,0 +1,3 @@
1
+ import{dirname,join,relative}from"node:path";import{cp,mkdir,readdir,rename,writeFile}from"node:fs/promises";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{bundleExtensionDistributionGraph}from"#internal/authored-module-loader.js";import{EXTENSION_COMPATIBILITY_MANIFEST_FILENAME}from"#compiler/extension-compatibility.js";import{emitExtensionDeclarations}from"#internal/nitro/host/extension-declarations.js";async function emitExtensionDistribution(a){let o=await collectExtensionSourceFiles(a.sourceRoot),s=a.manifest.skills.filter(e=>e.sourceKind===`skill-package`).map(e=>relative(a.sourceRoot,e.rootPath).replaceAll(`\\`,`/`)),c=o.filter(e=>isAuthoredModule(e.logicalPath)&&!s.some(t=>e.logicalPath.startsWith(`${t}/`)));await copyDistributionDataFiles({files:o,moduleLogicalPaths:new Set(c.map(e=>e.logicalPath)),stagedDistRoot:a.stagedDistRoot});let l=await bundleExtensionDistributionGraph({entries:await createDistributionEntries({...a,moduleFiles:c}),packageRoot:a.appRoot,runtimeDependencies:a.runtimeDependencies});for(let[n,r]of l){let o=join(a.stagedOutDir,n);await mkdir(dirname(o),{recursive:!0}),await writeFile(o,r,`utf8`)}await emitExtensionDeclarations({appRoot:a.appRoot,declarationsRoot:a.declarationsRoot,moduleLogicalPaths:c.map(e=>e.logicalPath),sourceRoot:a.sourceRoot});let u=relative(a.appRoot,a.sourceRoot);try{await cp(join(a.declarationsRoot,u),a.stagedDistRoot,{recursive:!0})}catch(e){throw isFileSystemError(e,`ENOENT`)?Error(`TypeScript emitted no declarations for "${u}". Ensure the package tsconfig.json \`include\` covers every module under \`eve.extension.source\`.`,{cause:e}):e}await emitDeclarationBarrels(a)}var ExtensionOutputRestoreError=class extends Error{preservedOutputPath;constructor(e,t){super(`Publishing the extension build output failed, and the previous output could not be restored. It is preserved at "${e}".`,t),this.name=`ExtensionOutputRestoreError`,this.preservedOutputPath=e}};async function replaceExtensionBuildOutput(n){await mkdir(dirname(n.outDir),{recursive:!0});let r=join(n.transactionRoot,`previous-output`),a=!1;try{await rename(n.outDir,r),a=!0}catch(e){if(!isFileSystemError(e,`ENOENT`))throw e}try{await rename(n.stagedOutDir,n.outDir)}catch(e){if(a)try{await rename(r,n.outDir)}catch{throw new ExtensionOutputRestoreError(r,{cause:e})}throw e}}async function collectExtensionSourceFiles(e,r=e){let i=[];for(let o of await readdir(r,{withFileTypes:!0})){let a=join(r,o.name);if(o.isDirectory())i.push(...await collectExtensionSourceFiles(e,a));else if(o.isFile()){let t=relative(e,a).replaceAll(`\\`,`/`);if(t===EXTENSION_COMPATIBILITY_MANIFEST_FILENAME)throw Error(`The extension source cannot contain "${EXTENSION_COMPATIBILITY_MANIFEST_FILENAME}"; eve reserves it for generated compatibility metadata.`);i.push({absolutePath:a,logicalPath:t})}else throw Error(`Extension source entry "${a}" must be a regular file or directory.`)}return i.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath))}function isAuthoredModule(e){return!/\.d\.[cm]?ts$/.test(e)&&SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS.some(t=>e.endsWith(t))}async function copyDistributionDataFiles(n){await Promise.all(n.files.filter(e=>!n.moduleLogicalPaths.has(e.logicalPath)).map(async a=>{let o=join(n.stagedDistRoot,a.logicalPath);await mkdir(dirname(o),{recursive:!0}),await cp(a.absolutePath,o)}))}async function createDistributionEntries(e){let r=relative(e.stagedOutDir,e.stagedDistRoot).replaceAll(`\\`,`/`),i=e.moduleFiles.map(e=>({name:`${r}/${stripAuthoredModuleExtension(e.logicalPath)}`,path:e.absolutePath})),a=new Set;for(let e of i){if(a.has(e.name))throw Error(`Multiple extension modules emit the same path "${e.name}.mjs".`);a.add(e.name)}let o=join(e.transactionRoot,`barrels`);return i.push(await stageRuntimeBarrel({barrelPath:join(o,`index.mjs`),name:`index`,reexports:[{name:`default`,path:join(e.sourceRoot,e.declarationModule.logicalPath)},{name:e.shortName,path:join(e.sourceRoot,e.declarationModule.logicalPath)}]}),await stageRuntimeBarrel({barrelPath:join(o,`tools.mjs`),name:`tools/index`,reexports:e.manifest.tools.map(n=>({name:toolExportName(n.logicalPath),path:join(e.sourceRoot,n.logicalPath)}))})),i}async function stageRuntimeBarrel(t){await mkdir(dirname(t.barrelPath),{recursive:!0});let n=t.reexports.map(n=>reexportLine(n.name,relativeImport(dirname(t.barrelPath),n.path)));return await writeFile(t.barrelPath,`${n.join(`
2
+ `)}\n`,`utf8`),{name:t.name,path:t.barrelPath}}async function emitDeclarationBarrels(e){await mkdir(join(e.stagedOutDir,`tools`),{recursive:!0});let n=relativeImport(e.stagedOutDir,join(e.stagedDistRoot,e.declarationModule.logicalPath));await writeDeclarationBarrel({path:join(e.stagedOutDir,`index.d.ts`),reexports:[{name:`default`,specifier:n},{name:e.shortName,specifier:n}]}),await writeDeclarationBarrel({path:join(e.stagedOutDir,`tools`,`index.d.ts`),reexports:e.manifest.tools.map(n=>({name:toolExportName(n.logicalPath),specifier:relativeImport(join(e.stagedOutDir,`tools`),join(e.stagedDistRoot,n.logicalPath))}))})}async function writeDeclarationBarrel(e){let t=e.reexports.map(e=>reexportLine(e.name,toDeclarationSpecifier(e.specifier)));await writeFile(e.path,[`// Generated by eve. Do not edit by hand.`,``,...t,``].join(`
3
+ `),`utf8`)}function stripAuthoredModuleExtension(e){for(let t of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(t))return e.slice(0,e.length-t.length);return e}function toolExportName(e){let t=stripAuthoredModuleExtension(e).replace(/^tools\//,``).replace(/[^A-Za-z0-9_$]/g,`_`);return/^[A-Za-z_$]/.test(t)?t:`_${t}`}function relativeImport(e,t){let r=relative(e,t).replaceAll(`\\`,`/`);return r.startsWith(`.`)?r:`./${r}`}function reexportLine(e,t){return e==="default"?`export { default } from ${JSON.stringify(t)};`:`export { default as ${e} } from ${JSON.stringify(t)};`}function toDeclarationSpecifier(e){return e.replace(/\.mts$/,`.mjs`).replace(/\.cts$/,`.cjs`).replace(/\.tsx?$/,`.js`)}function isFileSystemError(e,t){return e instanceof Error&&`code`in e&&e.code===t}export{ExtensionOutputRestoreError,emitExtensionDistribution,replaceExtensionBuildOutput};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Detects whether an authored extension tree calls `defineState` from
3
+ * `eve/context`. Usage is followed through local re-export barrels — aliased
4
+ * re-exports, `export *`, and import-then-re-export chains — so indirect
5
+ * usage still stamps the `state` capability requirement.
6
+ */
7
+ export declare function extensionUsesState(sourceRoot: string): Promise<boolean>;
@@ -0,0 +1 @@
1
+ import{dirname,join,resolve}from"node:path";import{readFile,readdir}from"node:fs/promises";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";const STATE_MODULE=`eve/context`,STATE_EXPORT=`defineState`;async function extensionUsesState(e){let t=await collectAuthoredModules(e),n=new Map;for(let e of t)n.set(e,await readFile(e,`utf8`));if(![...n.values()].some(e=>e.includes(STATE_EXPORT)))return!1;let i=new Set(t),a=new Map;for(let[e,t]of n){let n=await parseWithNitroRolldownAst(e,t);a.set(e,analyzeModule(n))}let l=computeStateExports(a,i);for(let[e,t]of a){for(let[n,r]of t.imports)if(t.calledIdentifiers.has(n)&&specifierExportsState({...r,fromModulePath:e,stateExports:l,moduleSet:i}))return!0;for(let[n,r]of t.namespaceImports){let a=t.calledMembers.get(n);if(a===void 0)continue;if(r===STATE_MODULE){if(a.has(STATE_EXPORT))return!0;continue}let o=resolveLocalSpecifier(e,r,i),u=o===null?void 0:l.get(o);if(u!==void 0&&[...a].some(e=>u.has(e)))return!0}}return!1}async function collectAuthoredModules(e){let n=[];for(let r of await readdir(e,{withFileTypes:!0})){let i=join(e,r.name);r.isDirectory()?n.push(...await collectAuthoredModules(i)):r.isFile()&&!/\.d\.[cm]?ts$/.test(r.name)&&SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS.some(e=>r.name.endsWith(e))&&n.push(i)}return n.sort()}function analyzeModule(e){let t={imports:new Map,namespaceImports:new Map,reexports:new Map,starReexportSpecifiers:[],localReexports:new Map,calledIdentifiers:new Set,calledMembers:new Map};return walkAst(e,e=>{if(e.type===`ImportDeclaration`){let n=stringValue(e.source);if(n===null)return;for(let r of e.specifiers??[]){let e=moduleName(r.local);if(e!==null){if(r.type===`ImportNamespaceSpecifier`)t.namespaceImports.set(e,n);else if(r.type===`ImportSpecifier`){let i=moduleName(r.imported);i!==null&&t.imports.set(e,{specifier:n,importedName:i})}}}}else if(e.type===`ExportNamedDeclaration`){let n=stringValue(e.source);for(let r of e.specifiers??[]){if(r.type!==`ExportSpecifier`)continue;let e=moduleName(r.local),i=moduleName(r.exported)??e;e===null||i===null||(n===null?t.localReexports.set(i,e):t.reexports.set(i,{specifier:n,importedName:e}))}}else if(e.type===`ExportAllDeclaration`){let n=stringValue(e.source);n!==null&&e.exported==null&&t.starReexportSpecifiers.push(n)}else if(e.type===`CallExpression`){let n=e.callee;if(n?.type===`Identifier`){let e=moduleName(n);e!==null&&t.calledIdentifiers.add(e)}else if(n?.type===`MemberExpression`&&n.object?.type===`Identifier`){let e=moduleName(n.object),r=moduleName(n.property);if(e!==null&&r!==null){let n=t.calledMembers.get(e)??new Set;n.add(r),t.calledMembers.set(e,n)}}}}),t}function computeStateExports(e,t){let n=new Map;for(let t of e.keys())n.set(t,new Set);let r=!0;for(;r;){r=!1;for(let[i,a]of e){let e=n.get(i),add=t=>{e.has(t)||(e.add(t),r=!0)};for(let[e,r]of a.reexports)specifierExportsState({...r,fromModulePath:i,stateExports:n,moduleSet:t})&&add(e);for(let e of a.starReexportSpecifiers){if(e===STATE_MODULE){add(STATE_EXPORT);continue}let r=resolveLocalSpecifier(i,e,t);if(r!==null)for(let e of n.get(r)??[])add(e)}for(let[e,r]of a.localReexports){let o=a.imports.get(r);o!==void 0&&specifierExportsState({...o,fromModulePath:i,stateExports:n,moduleSet:t})&&add(e)}}}return n}function specifierExportsState(e){if(e.specifier===STATE_MODULE)return e.importedName===STATE_EXPORT;let t=resolveLocalSpecifier(e.fromModulePath,e.specifier,e.moduleSet);return t!==null&&(e.stateExports.get(t)?.has(e.importedName)??!1)}function resolveLocalSpecifier(r,i,o){if(!i.startsWith(`.`))return null;let s=resolve(dirname(r),i),c=[s,...emittedExtensionVariants(s)];for(let e of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)c.push(`${s}${e}`,join(s,`index${e}`));return c.find(e=>o.has(e))??null}function emittedExtensionVariants(e){return[[`.js`,`.ts`],[`.jsx`,`.tsx`],[`.mjs`,`.mts`],[`.cjs`,`.cts`]].filter(([t])=>e.endsWith(t)).map(([t,n])=>e.slice(0,-t.length)+n)}function moduleName(e){return e==null?null:typeof e.name==`string`?e.name:typeof e.value==`string`?e.value:null}function stringValue(e){return typeof e?.value==`string`?e.value:null}function walkAst(e,t){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)typeof e==`object`&&e&&`type`in e&&walkAst(e,t);else typeof n==`object`&&n&&`type`in n&&walkAst(n,t)}export{extensionUsesState};
@@ -1,10 +1,14 @@
1
1
  import type { ApplicationBuildWorkspace } from "#internal/application/build-workspace.js";
2
+ import { type DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";
2
3
  import type { PreparedApplicationHost, PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";
3
4
  /**
4
5
  * Compiles one authored app and stages an isolated runtime generation and host
5
6
  * candidate without changing the active development server.
6
7
  */
7
- export declare function prepareDevelopmentApplicationHost(appRoot: string): Promise<PreparedDevelopmentApplicationHost>;
8
+ export declare function prepareDevelopmentApplicationHost(appRoot: string, options?: {
9
+ readonly changedPaths?: readonly string[];
10
+ readonly previousExtensions?: readonly DevelopmentWorkspaceExtension[];
11
+ }): Promise<PreparedDevelopmentApplicationHost>;
8
12
  /**
9
13
  * Compiles one authored app into an invocation-owned build workspace and
10
14
  * stages the package-owned artifacts the production Nitro build needs.
@@ -1 +1 @@
1
- import{join}from"node:path";import{createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgentInWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";async function prepareDevelopmentApplicationHost(a){let o=await createDevelopmentHostWorkspace(a),s;try{let t=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(a,`.eve`),writeRoot:o.compilerArtifactsDir},startPath:a}),n=await resolveSchedules({manifest:t.manifest});return s=await stageDevelopmentGeneration(t),{...createPreparedApplicationHost({compileResult:t,compiledArtifacts:await writeDevelopmentCompiledArtifactsFiles({compileResult:t,outDir:o.artifactsDir,runtimeAppRoot:s.runtimeAppRoot}),schedules:n,workflowBuildDir:o.workflowBuildDir}),generation:s,workspace:o}}catch(e){let t=[removeDevelopmentHostWorkspace(o)];s!==void 0&&t.push(discardDevelopmentGeneration(s));let i=(await Promise.allSettled(t)).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw i.length>0?AggregateError([e,...i],`Failed to prepare and discard a development host candidate.`,{cause:e}):e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
1
+ import{join}from"node:path";import{createDevelopmentHostWorkspace,removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{discardDevelopmentGeneration,stageDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{createScheduleRegistrations}from"#runtime/schedules/register.js";import{resolveSchedules}from"#runtime/schedules/resolve-schedule.js";import{compileAgentInWorkspace}from"#compiler/compile-agent.js";import{writeCompiledArtifactsFiles,writeDevelopmentCompiledArtifactsFiles}from"#internal/application/compiled-artifacts.js";import{prepareDevelopmentWorkspaceExtensions}from"#internal/nitro/host/dev-workspace-extensions.js";async function prepareDevelopmentApplicationHost(a,o={}){let s={appRoot:a};o.changedPaths!==void 0&&(s.changedPaths=o.changedPaths),o.previousExtensions!==void 0&&(s.previousExtensions=o.previousExtensions);let c=await prepareDevelopmentWorkspaceExtensions(s),l=await createDevelopmentHostWorkspace(a),u;try{let t=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(a,`.eve`),writeRoot:l.compilerArtifactsDir},startPath:a}),n=await resolveSchedules({manifest:t.manifest});return u=await stageDevelopmentGeneration(t),{...createPreparedApplicationHost({compileResult:t,compiledArtifacts:await writeDevelopmentCompiledArtifactsFiles({compileResult:t,outDir:l.artifactsDir,runtimeAppRoot:u.runtimeAppRoot}),schedules:n,workflowBuildDir:l.workflowBuildDir}),generation:u,workspaceExtensions:c,workspace:l}}catch(e){let t=[removeDevelopmentHostWorkspace(l)];u!==void 0&&t.push(discardDevelopmentGeneration(u));let i=(await Promise.allSettled(t)).flatMap(e=>e.status===`rejected`?[e.reason]:[]);throw i.length>0?AggregateError([e,...i],`Failed to prepare and discard a development host candidate.`,{cause:e}):e}}async function prepareProductionApplicationHost(t){let n=await compileAgentInWorkspace({artifactLocations:{publishedRoot:join(t.publication.output.finalDir,`.eve`),writeRoot:t.compiler.artifactsDir},startPath:t.appRoot}),r=await resolveSchedules({manifest:n.manifest});return createPreparedApplicationHost({compileResult:n,compiledArtifacts:await writeCompiledArtifactsFiles({compileResult:n,defaultWorkflowWorld:resolveProductionWorkflowWorldTarget(),outDir:t.host.artifactsDir}),schedules:r,workflowBuildDir:t.workflow.buildDir})}function createPreparedApplicationHost(e){return{appRoot:e.compileResult.project.appRoot,compileResult:e.compileResult,compiledArtifacts:e.compiledArtifacts,scheduleRegistrations:createScheduleRegistrations(e.schedules),schedules:e.schedules,workflowBuildDir:e.workflowBuildDir}}function resolveProductionWorkflowWorldTarget(){return process.env.VERCEL?`vercel`:`local`}export{prepareDevelopmentApplicationHost,prepareProductionApplicationHost};
@@ -1,2 +1,2 @@
1
- import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{randomBytes}from"node:crypto";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,clearInitializedDevelopmentSandboxBackendNames,createDevelopmentSandboxRunId,getInitializedDevelopmentSandboxBackendNames}from"#execution/sandbox/development-run.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{DrainedNitroDevServer}from"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createDevelopmentAuthoredRebuildCoordinator}from"#internal/nitro/host/dev-authored-rebuild-coordinator.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";import{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment}from"#internal/nitro/host/dev-workflow-world-setup.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,PORT_ENV=`PORT`;async function isActiveDevelopmentServerForApp(e){try{let t=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return t===void 0||!isLoopbackServerUrl(t)||!await isEveServerHealthy(t)?!1:new URL(t).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
- `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(n){n.devServer.setControlHandler(async r=>{let i=await n.workflowWorld?.handleRequest(r);if(i!==void 0)return i;let a=new URL(r.url);if(a.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&r.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:n.appRoot});if(a.pathname!==EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH||r.method!==`GET`)return;let o=n.getWatcher();return o===void 0?Response.json({error:`The development server is still starting.`},{status:503}):(a.searchParams.get(`force`)===`1`?await o.rebuild():await o.flush(),handleDevRuntimeArtifactsRequest({appRoot:n.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.workflowWorld;a!==void 0&&await attempt(()=>a.close());let o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({backendNames:getInitializedDevelopmentSandboxBackendNames(e.developmentSandboxRunId),devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),a=t.port??i,d=t.host!==void 0||t.port!==void 0||i!==void 0,h=new DevelopmentServerState(r),g=await h.read();if(g!==void 0&&isLoopbackServerUrl(g)&&await isEveServerHealthy(g)){if(t.existing===`attach-if-unconfigured`&&!d)return{handle:{kind:`existing`,appRoot:r.appRoot,url:g},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,g)}let _=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],v=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=v;let y,b,x,S,C,w,T,E=!1,D=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),t.onBootProgress);T=e;let n=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),t.onBootProgress);y=i,b=new DrainedNitroDevServer(i.logger);let o=b,s=randomBytes(32).toString(`base64url`);o.setClientAddressSecret(s),S=installWorkflowTransportEnvironment(r.appRoot,s),C=createDevelopmentWorkflowWorld({appRoot:r.appRoot,preparedHost:e,transportSecret:s}),addDevelopmentControlHandler({appRoot:r.appRoot,devServer:o,getWatcher:()=>w,workflowWorld:C});let c=t.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,l=a===void 0,u=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:o,host:c,port:a,retryOnAddressInUse:l}),t.onBootProgress);if(!u.url)throw Error(`Nitro dev server did not expose a URL.`);let d=normalizeDevelopmentServerClientUrl(u.url);x=installWorkflowLocalQueueEnvironment(d),await devBootPhase(`building dev bundle`,async()=>{let t=await buildDevelopmentHostCandidate({host:e,nitro:i});y=void 0;let n=e.workspace;D=!0,await o.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(n),entry:t.entry,workerData:t.workerData}),await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),E=!0},t.onBootProgress),await C?.start(),startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:n});let f=await createDevelopmentAuthoredRebuildCoordinator({devServer:o,initialHost:e});w=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({coordinator:f,preparedHost:e})},t.onBootProgress),await h.write(d);let p=x;if(p===void 0)throw Error(`Workflow local queue environment was not initialized.`);let m=w,g=b,O=C,k=S,A;return{handle:{kind:`started`,appRoot:r.appRoot,url:d},close:()=>(A??=(async()=>{let e=await closeDevelopmentServerResources({authoredSourceWatcher:m,devServer:g,developmentSandboxRunId:v,nitro:void 0,workflowWorld:O});e.listenerClosed&&await h.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{clearInitializedDevelopmentSandboxBackendNames(v),p(),k?.(),restoreDevelopmentSandboxRunId(_)}})(),A)}}catch(e){let t=await closeDevelopmentServerResources({authoredSourceWatcher:w,devServer:b,developmentSandboxRunId:v,nitro:y,workflowWorld:C}),n=[...t.errors];throw T!==void 0&&!E&&await discardDevelopmentGeneration(T.generation).catch(e=>{n.push(e)}),T!==void 0&&!D&&await removeDevelopmentHostWorkspace(T.workspace).catch(e=>{n.push(e)}),x?.(),S?.(),clearInitializedDevelopmentSandboxBackendNames(v),t.listenerClosed&&await h.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(_),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
1
+ import{EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}from"#protocol/routes.js";import{isLoopbackServerUrl}from"#shared/network-address.js";import{detectPackageManager}from"#setup/package-manager.js";import{eveDevArguments}from"#setup/primitives/index.js";import{toErrorMessage}from"#shared/errors.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{randomBytes}from"node:crypto";import{resolveDiscoveryProject}from"#discover/project.js";import{EVE_DEV_ENV_FLAG}from"#internal/application/optional-package-install.js";import{EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,createDevelopmentSandboxRunId}from"#execution/sandbox/development-run.js";import{createDevelopmentApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{prepareDevelopmentApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createDevelopmentNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{buildDevelopmentHostCandidate}from"#internal/nitro/host/dev-host-candidate.js";import{removeDevelopmentHostWorkspace}from"#internal/nitro/host/dev-host-workspace.js";import{DrainedNitroDevServer}from"#internal/nitro/host/drained-nitro-dev-server.js";import{activateDevelopmentGeneration,discardDevelopmentGeneration}from"#internal/nitro/development-generation.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";import{DEFAULT_DEVELOPMENT_SERVER_HOST,normalizeDevelopmentServerClientUrl}from"#internal/nitro/host/dev-server-url.js";import{createDevelopmentAuthoredRebuildCoordinator}from"#internal/nitro/host/dev-authored-rebuild-coordinator.js";import{DevelopmentServerState}from"#internal/nitro/host/dev-server-state.js";import{isEveServerHealthy}from"#shared/eve-server-health.js";import{handleDevRuntimeArtifactsRequest}from"#internal/nitro/routes/dev-runtime-artifacts.js";import{pruneLocalSandboxTemplatesInBackground,stopDevelopmentSandboxResources}from"#execution/sandbox/bindings/local.js";import{DEFAULT_DEVELOPMENT_SERVER_PORT,MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS}from"#internal/nitro/host/ports.js";import{createDevelopmentWorkflowWorld,installWorkflowLocalQueueEnvironment,installWorkflowTransportEnvironment}from"#internal/nitro/host/dev-workflow-world-setup.js";const MAX_ALLOWED_DEVELOPMENT_SERVER_PORT=65535,PORT_ENV=`PORT`;async function isActiveDevelopmentServerForApp(e){try{let t=await new DevelopmentServerState(await resolveDiscoveryProject(e.appRoot)).read();return t===void 0||!isLoopbackServerUrl(t)||!await isEveServerHealthy(t)?!1:new URL(t).origin===new URL(normalizeDevelopmentServerClientUrl(e.serverUrl)).origin}catch{return!1}}function isAddressInUseError(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function resolveDevelopmentServerPort(e){let t=typeof e==`string`?Number(e):e??DEFAULT_DEVELOPMENT_SERVER_PORT;if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}function readEnvironmentPort(){let e=process.env[PORT_ENV];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>MAX_ALLOWED_DEVELOPMENT_SERVER_PORT)throw Error(`Invalid ${PORT_ENV} environment variable "${e}". Expected an integer between 0 and ${MAX_ALLOWED_DEVELOPMENT_SERVER_PORT}.`);return t}async function detectDevelopmentCommandPackageManager(e){try{return(await detectPackageManager(e)).kind}catch{return`pnpm`}}async function formatDevelopmentServerConnectCommand(e,t){let n=await detectDevelopmentCommandPackageManager(e);return[n,...eveDevArguments(n),t].join(` `)}async function createDevelopmentServerAlreadyRunningError(e,t){let n=await formatDevelopmentServerConnectCommand(e,t);return Error([`A dev server is already running for this eve agent.`,`To connect to the existing instance, run: ${n}`].join(`
2
+ `))}function resolveDevelopmentServerPorts(e){let t=resolveDevelopmentServerPort(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<MAX_DEVELOPMENT_SERVER_PORT_ATTEMPTS;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function addDevelopmentControlHandler(n){n.devServer.setControlHandler(async r=>{let i=await n.workflowWorld?.handleRequest(r);if(i!==void 0)return i;let a=new URL(r.url);if(a.pathname===EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH&&r.method===`GET`)return handleDevRuntimeArtifactsRequest({appRoot:n.appRoot});if(a.pathname!==EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH||r.method!==`GET`)return;let o=n.getWatcher();return o===void 0?Response.json({error:`The development server is still starting.`},{status:503}):(a.searchParams.get(`force`)===`1`?await o.rebuild():await o.flush(),handleDevRuntimeArtifactsRequest({appRoot:n.appRoot}))})}async function closeDevelopmentServerResources(e){let t=[],attempt=async e=>{try{return await e(),!0}catch(e){return t.push(e),!1}},n=e.authoredSourceWatcher;n!==void 0&&await attempt(()=>n.close());let r=e.devServer,i=r===void 0?!0:await attempt(()=>r.close()),a=e.workflowWorld;a!==void 0&&await attempt(()=>a.close());let o=e.nitro;return o!==void 0&&await attempt(()=>o.close()),await attempt(()=>stopDevelopmentSandboxResources({appRoot:e.appRoot,devRunId:e.developmentSandboxRunId,log:e=>console.warn(`[eve:dev] ${e}`)})),{errors:t,listenerClosed:i}}function createDevelopmentServerCleanupError(e){if(e.length!==0){if(e.length===1){let t=e[0];return t instanceof Error?t:Error(`Failed to close the development server: ${toErrorMessage(t)}`,{cause:t})}return AggregateError(e,`Multiple development-server resources failed to close.`)}}function createDevelopmentServerStartupCleanupError(e,t){return AggregateError([e,...t],`${toErrorMessage(e)} Cleanup also failed.`,{cause:e})}async function listenForDevelopmentServer(e){let t=resolveDevelopmentServerPorts({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!isAddressInUseError(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function startNitroDevelopmentServer(e,t){process.env[EVE_DEV_ENV_FLAG]??=`1`;let r=await resolveDiscoveryProject(e);loadDevelopmentEnvironmentFiles(r.appRoot);let i=readEnvironmentPort(),a=t.port??i,m=t.host!==void 0||t.port!==void 0||i!==void 0,h=new DevelopmentServerState(r),g=await h.read();if(g!==void 0&&isLoopbackServerUrl(g)&&await isEveServerHealthy(g)){if(t.existing===`attach-if-unconfigured`&&!m)return{handle:{kind:`existing`,appRoot:r.appRoot,url:g},close:void 0};throw await createDevelopmentServerAlreadyRunningError(r.appRoot,g)}let _=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV],v=createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=v;let y,b,x,S,C,w,T,E=!1,D=!1;try{let e=await devBootPhase(`compiling agent`,()=>prepareDevelopmentApplicationHost(r.appRoot),t.onBootProgress);T=e;let n=resolveNitroCompiledArtifactsSource(createDevelopmentNitroArtifactsConfig({appRoot:e.appRoot,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world}));pruneLocalSandboxTemplatesInBackground(e.appRoot);let i=await devBootPhase(`creating dev server`,()=>createDevelopmentApplicationNitro(e),t.onBootProgress);y=i,b=new DrainedNitroDevServer(i.logger);let o=b,s=randomBytes(32).toString(`base64url`);o.setClientAddressSecret(s),S=installWorkflowTransportEnvironment(r.appRoot,s),C=createDevelopmentWorkflowWorld({appRoot:r.appRoot,preparedHost:e,transportSecret:s}),addDevelopmentControlHandler({appRoot:r.appRoot,devServer:o,getWatcher:()=>w,workflowWorld:C});let c=t.host??i.options.devServer.hostname??DEFAULT_DEVELOPMENT_SERVER_HOST,l=a===void 0,u=await devBootPhase(`binding port`,()=>listenForDevelopmentServer({devServer:o,host:c,port:a,retryOnAddressInUse:l}),t.onBootProgress);if(!u.url)throw Error(`Nitro dev server did not expose a URL.`);let d=normalizeDevelopmentServerClientUrl(u.url);x=installWorkflowLocalQueueEnvironment(d),await devBootPhase(`building dev bundle`,async()=>{let t=await buildDevelopmentHostCandidate({host:e,nitro:i});y=void 0;let n=e.workspace;D=!0,await o.replaceWorker({dispose:async()=>await removeDevelopmentHostWorkspace(n),entry:t.entry,workerData:t.workerData}),await activateDevelopmentGeneration({appRoot:e.appRoot,generation:e.generation}),E=!0},t.onBootProgress),await C?.start(),startDevelopmentSandboxPrewarmInBackground({appRoot:e.appRoot,compiledArtifactsSource:n});let f=await createDevelopmentAuthoredRebuildCoordinator({devServer:o,initialHost:e});w=await devBootPhase(`starting file watcher`,async()=>{let{startAuthoredSourceWatcher:t}=await import(`#internal/nitro/host/dev-authored-source-watcher.js`);return t({coordinator:f,preparedHost:e})},t.onBootProgress),await h.write(d);let p=x;if(p===void 0)throw Error(`Workflow local queue environment was not initialized.`);let m=w,g=b,O=C,k=S,A;return{handle:{kind:`started`,appRoot:r.appRoot,url:d},close:()=>(A??=(async()=>{let e=await closeDevelopmentServerResources({appRoot:r.appRoot,authoredSourceWatcher:m,devServer:g,developmentSandboxRunId:v,nitro:void 0,workflowWorld:O});e.listenerClosed&&await h.remove().catch(()=>{});try{let t=createDevelopmentServerCleanupError(e.errors);if(t!==void 0)throw t}finally{p(),k?.(),restoreDevelopmentSandboxRunId(_)}})(),A)}}catch(e){let t=await closeDevelopmentServerResources({appRoot:r.appRoot,authoredSourceWatcher:w,devServer:b,developmentSandboxRunId:v,nitro:y,workflowWorld:C}),n=[...t.errors];throw T!==void 0&&!E&&await discardDevelopmentGeneration(T.generation).catch(e=>{n.push(e)}),T!==void 0&&!D&&await removeDevelopmentHostWorkspace(T.workspace).catch(e=>{n.push(e)}),x?.(),S?.(),t.listenerClosed&&await h.remove().catch(()=>{}),restoreDevelopmentSandboxRunId(_),n.length>0?createDevelopmentServerStartupCleanupError(e,n):e}}function createDevelopmentServer(e,t={}){let n,r;return{start(){if(n!==void 0)throw Error(`DevelopmentServer.start() was already called.`);return n=startNitroDevelopmentServer(e,t).then(({handle:e,close:t})=>(r=t,e)),n},async close(){n!==void 0&&(await n.catch(()=>void 0),await r?.())}}}function restoreDevelopmentSandboxRunId(e){if(e===void 0){delete process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return}process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV]=e}export{createDevelopmentServer,isActiveDevelopmentServerForApp,normalizeDevelopmentServerClientUrl};
@@ -5,6 +5,7 @@ import type { GeneratedCompiledArtifactsFiles } from "#internal/application/comp
5
5
  import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
6
6
  import type { DevelopmentGeneration } from "#internal/nitro/development-generation.js";
7
7
  import type { DevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";
8
+ import type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";
8
9
  /**
9
10
  * Route surface included in one programmatic Nitro host build.
10
11
  */
@@ -71,5 +72,6 @@ export interface PreparedApplicationHost {
71
72
  }
72
73
  export interface PreparedDevelopmentApplicationHost extends PreparedApplicationHost {
73
74
  generation: DevelopmentGeneration;
75
+ workspaceExtensions: readonly DevelopmentWorkspaceExtension[];
74
76
  workspace: DevelopmentHostWorkspace;
75
77
  }
@@ -1 +1 @@
1
- import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolDefinitions,getAllFrameworkToolNames}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";function buildAgentInfoResponse(e,t){let r=e.agent,i=buildToolInfo(r,getRootDelegationToolNames(e.manifest));return{agent:{agentRoot:r.metadata.agentRoot,appRoot:r.metadata.appRoot,configSource:r.config.source?toSource(r.config.source):void 0,description:r.config.description,model:{contextWindowTokens:r.config.model.contextWindowTokens,id:r.config.model.id,providerOptions:r.config.model.providerOptions,source:r.config.model.source?toSource(r.config.model.source):void 0},name:r.config.name,outputSchema:r.config.outputSchema},capabilities:{devRoutes:t.mode===`development`},channels:buildChannelInfo(r),connections:r.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:e.approval!==void 0,hasAuthorization:e.authorization!==void 0,hasHeaders:e.headers!==void 0,protocol:e.protocol,toolFilter:e.tools,url:e.url})),diagnostics:{discoveryErrors:r.metadata.diagnosticsSummary.errors,discoveryWarnings:r.metadata.diagnosticsSummary.warnings},hooks:r.hooks.map(e=>({...toSource(e),eventNames:Object.keys(e.events).sort(),slug:e.slug})),instructions:{dynamic:r.dynamicInstructionsResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:r.instructions?{...toSource(r.instructions),markdown:r.instructions.markdown,name:r.instructions.name}:null},kind:`eve-agent-info`,mode:t.mode,sandbox:renderSandbox(r.sandbox),schedules:e.schedules.map(renderSchedule),skills:{static:r.skills.map(renderSkill),dynamic:r.dynamicSkillResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:e.manifest.subagents.map(renderSubagent),total:e.manifest.subagents.length},tools:i,version:1,workflow:{enabled:r.workflowTool!==void 0,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:r.workspaceResourceRoot,rootEntries:[...r.workspaceSpec.rootEntries]}}}function buildChannelInfo(e){let t=new Set(e.channels.map(e=>e.name)),n=new Set(e.disabledFrameworkChannels),a=getAllFrameworkChannelNames(),o=getFrameworkChannelDefinitions(),s=o.filter(e=>!t.has(e.name)&&!n.has(e.name)),c=e.channels.map(e=>renderChannel(e,{origin:`authored`})),l=o.map(e=>{let r=t.has(e.name),i=n.has(e.name),a=i?`disabled`:r?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:i,replacedByAuthoredChannel:r,status:a}});return{authored:c,available:[...s.map(e=>renderChannel(e,{origin:`framework`})),...c],disabledFramework:[...e.disabledFrameworkChannels],framework:l.filter(e=>a.has(e.name))}}function buildToolInfo(e,r){let i=new Set(e.tools.map(e=>e.name)),a=new Set(e.disabledFrameworkTools),c=getAllFrameworkToolNames(),l=e.connections.length>0?[createConnectionSearchResolver()]:[],u=e.tools.map(e=>renderTool(e,{origin:`authored`,replacesFrameworkTool:c.has(e.name)})),d=buildFrameworkToolInfo({authoredToolNames:i,delegationToolNames:r,disabledFrameworkToolNames:a});return{available:[...d.available,...u],authored:u,disabledFramework:[...e.disabledFrameworkTools],dynamic:[...l.map(e=>renderDynamicResolver(e,{origin:`framework`})),...e.dynamicToolResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:d.framework,reserved:[WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]}}function buildFrameworkToolInfo(e){let t=new Set([...e.authoredToolNames,...e.delegationToolNames]),n=[],r=[];for(let i of getAllFrameworkToolDefinitions()){let a=e.disabledFrameworkToolNames.has(i.name),o=e.authoredToolNames.has(i.name),s=a?`disabled`:t.has(i.name)?`replaced`:`active`,c=renderTool(i,{origin:`framework`,replacesFrameworkTool:!1});s===`active`&&n.push(c),r.push({...c,disabledByAuthor:a,replacedByAuthoredTool:o,status:s})}return{available:n,framework:r}}function getRootDelegationToolNames(t){let n=new Set(t.subagentEdges.filter(t=>t.parentNodeId===ROOT_COMPILED_AGENT_NODE_ID).map(e=>e.childNodeId));return new Set([...t.subagents.filter(e=>n.has(e.nodeId)).map(e=>e.name),...t.remoteAgents.map(e=>e.name)])}function renderChannel(e,t){return{...toSource(e),adapterKind:e.adapter?.kind,method:e.method,name:e.name,origin:t.origin,urlPath:e.urlPath}}function renderTool(e,t){return{...toSource(e),description:e.description,hasAuth:!1,hasExecute:e.execute!==void 0,hasModelOutputProjection:e.toModelOutput!==void 0,hasOutputSchema:e.outputSchema!==void 0&&e.outputSchema!==null,inputSchema:e.inputSchema,name:e.name,origin:t.origin,outputSchema:e.outputSchema,replacesFrameworkTool:t.replacesFrameworkTool,requiresApproval:e.approval!==void 0}}function renderSkill(e){return{...toSource(e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}}function renderSchedule(e){return{...toSource(e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name}}function renderSandbox(e){return e===null?null:{...toSource(e),backendKind:resolveBackendKind(e.backend),description:e.description,hasBootstrap:e.bootstrap!==void 0,hasOnSession:e.onSession!==void 0,revalidationKey:e.revalidationKey,sourceHash:e.sourceHash}}function renderSubagent(e){return{...toSource(e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,rootPath:e.rootPath,summary:{channels:e.agent.channels.length,connections:e.agent.connections.length,hooks:e.agent.hooks.length,instructions:e.agent.instructions!==void 0,schedules:e.agent.schedules.length,skills:e.agent.skills.length,tools:e.agent.tools.length}}}function renderDynamicResolver(e,t){return{...toSource(e),eventNames:[...e.eventNames],origin:t.origin,slug:e.slug}}function toSource(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:e.sourceKind}}function resolveBackendKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`?t:void 0}export{buildAgentInfoResponse,buildFrameworkToolInfo,getRootDelegationToolNames,renderChannel,renderDynamicResolver,renderSchedule,renderSubagent,renderTool,toSource};
1
+ import{serializeInputSchema,serializeOutputSchema}from"#shared/tool-schema.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{WORKFLOW_TOOL_NAME}from"#shared/workflow-sandbox.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";import{getAllFrameworkToolDefinitions,getAllFrameworkToolNames}from"#runtime/framework-tools/index.js";import{createConnectionSearchResolver}from"#runtime/framework-tools/connection-search-dynamic.js";function buildAgentInfoResponse(e,t){let n=e.agent,r=buildToolInfo(n,getRootDelegationToolNames(e.manifest));return{agent:{agentRoot:n.metadata.agentRoot,appRoot:n.metadata.appRoot,configSource:n.config.source?toSource(n.config.source):void 0,description:n.config.description,model:{contextWindowTokens:n.config.model.contextWindowTokens,id:n.config.model.id,providerOptions:n.config.model.providerOptions,source:n.config.model.source?toSource(n.config.model.source):void 0},name:n.config.name,outputSchema:n.config.outputSchema},capabilities:{devRoutes:t.mode===`development`},channels:buildChannelInfo(n),connections:n.connections.map(e=>({...toSource(e),connectionName:e.connectionName,description:e.description,hasApproval:e.approval!==void 0,hasAuthorization:e.authorization!==void 0,hasHeaders:e.headers!==void 0,protocol:e.protocol,toolFilter:e.tools,url:e.url})),diagnostics:{discoveryErrors:n.metadata.diagnosticsSummary.errors,discoveryWarnings:n.metadata.diagnosticsSummary.warnings},hooks:n.hooks.map(e=>({...toSource(e),eventNames:Object.keys(e.events).sort(),slug:e.slug})),instructions:{dynamic:n.dynamicInstructionsResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`})),static:n.instructions?{...toSource(n.instructions),markdown:n.instructions.markdown,name:n.instructions.name}:null},kind:`eve-agent-info`,mode:t.mode,sandbox:renderSandbox(n.sandbox),schedules:e.schedules.map(renderSchedule),skills:{static:n.skills.map(renderSkill),dynamic:n.dynamicSkillResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))},subagents:{local:e.manifest.subagents.map(renderSubagent),total:e.manifest.subagents.length},tools:r,version:1,workflow:{enabled:n.workflowTool!==void 0,toolName:WORKFLOW_TOOL_NAME},workspace:{resourceRoot:n.workspaceResourceRoot,rootEntries:[...n.workspaceSpec.rootEntries]}}}function buildChannelInfo(e){let t=new Set(e.channels.map(e=>e.name)),n=new Set(e.disabledFrameworkChannels),r=getAllFrameworkChannelNames(),i=getFrameworkChannelDefinitions(),s=i.filter(e=>!t.has(e.name)&&!n.has(e.name)),c=e.channels.map(e=>renderChannel(e,{origin:`authored`})),l=i.map(e=>{let r=t.has(e.name),i=n.has(e.name),a=i?`disabled`:r?`replaced`:`active`;return{...renderChannel(e,{origin:`framework`}),disabledByAuthor:i,replacedByAuthoredChannel:r,status:a}});return{authored:c,available:[...s.map(e=>renderChannel(e,{origin:`framework`})),...c],disabledFramework:[...e.disabledFrameworkChannels],framework:l.filter(e=>r.has(e.name))}}function buildToolInfo(e,t){let n=new Set(e.tools.map(e=>e.name)),a=new Set(e.disabledFrameworkTools),o=getAllFrameworkToolNames(),s=e.connections.length>0?[createConnectionSearchResolver()]:[],u=e.tools.map(e=>renderTool(e,{origin:`authored`,replacesFrameworkTool:o.has(e.name)})),d=buildFrameworkToolInfo({authoredToolNames:n,delegationToolNames:t,disabledFrameworkToolNames:a});return{available:[...d.available,...u],authored:u,disabledFramework:[...e.disabledFrameworkTools],dynamic:[...s.map(e=>renderDynamicResolver(e,{origin:`framework`})),...e.dynamicToolResolvers.map(e=>renderDynamicResolver(e,{origin:`authored`}))],framework:d.framework,reserved:[WORKFLOW_TOOL_NAME,LOAD_SKILL_TOOL_NAME]}}function buildFrameworkToolInfo(e){let t=new Set([...e.authoredToolNames,...e.delegationToolNames]),n=[],r=[];for(let i of getAllFrameworkToolDefinitions()){let a=e.disabledFrameworkToolNames.has(i.name),o=e.authoredToolNames.has(i.name),s=a?`disabled`:t.has(i.name)?`replaced`:`active`,c=renderTool(i,{origin:`framework`,replacesFrameworkTool:!1});s===`active`&&n.push(c),r.push({...c,disabledByAuthor:a,replacedByAuthoredTool:o,status:s})}return{available:n,framework:r}}function getRootDelegationToolNames(e){let t=new Set(e.subagentEdges.filter(e=>e.parentNodeId===ROOT_COMPILED_AGENT_NODE_ID).map(e=>e.childNodeId));return new Set([...e.subagents.filter(e=>t.has(e.nodeId)).map(e=>e.name),...e.remoteAgents.map(e=>e.name)])}function renderChannel(e,t){return{...toSource(e),adapterKind:e.adapter?.kind,method:e.method,name:e.name,origin:t.origin,urlPath:e.urlPath}}function renderTool(n,r){let i=serializeInputSchema(n.inputSchema),a=serializeOutputSchema(n.outputSchema);return{...toSource(n),description:n.description,hasAuth:!1,hasExecute:n.execute!==void 0,hasModelOutputProjection:n.toModelOutput!==void 0,hasOutputSchema:a!==void 0,inputSchema:i,name:n.name,origin:r.origin,outputSchema:a,replacesFrameworkTool:r.replacesFrameworkTool,requiresApproval:n.approval!==void 0}}function renderSkill(e){return{...toSource(e),description:e.description,license:e.license,markdown:e.markdown,metadata:e.metadata,name:e.name}}function renderSchedule(e){return{...toSource(e),cron:e.cron,hasRun:e.hasRun,markdown:e.markdown,name:e.name}}function renderSandbox(e){return e===null?null:{...toSource(e),backendKind:resolveBackendKind(e.backend),description:e.description,hasBootstrap:e.bootstrap!==void 0,hasOnSession:e.onSession!==void 0,revalidationKey:e.revalidationKey,sourceHash:e.sourceHash}}function renderSubagent(e){return{...toSource(e),description:e.description,entryPath:e.entryPath,name:e.name,nodeId:e.nodeId,rootPath:e.rootPath,summary:{channels:e.agent.channels.length,connections:e.agent.connections.length,hooks:e.agent.hooks.length,instructions:e.agent.instructions!==void 0,schedules:e.agent.schedules.length,skills:e.agent.skills.length,tools:e.agent.tools.length}}}function renderDynamicResolver(e,t){return{...toSource(e),eventNames:[...e.eventNames],origin:t.origin,slug:e.slug}}function toSource(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:e.sourceKind}}function resolveBackendKind(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`?t:void 0}export{buildAgentInfoResponse,buildFrameworkToolInfo,getRootDelegationToolNames,renderChannel,renderDynamicResolver,renderSchedule,renderSubagent,renderTool,toSource};
@@ -1 +1 @@
1
- import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{attachAgentInfoRouteResponse,attachRouteAgent}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`},m=createRouteAgent(n.runtime,c);return{agent:m,args:attachRouteAgent(attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),m),backgroundTasks:u}}function createRouteAgent(e,t){return{async cancelTurn(t){return await e.cancelTurn(t)},async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
1
+ import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{createCancelFn}from"#channel/cancel.js";import{attachAgentInfoRouteResponse,attachRouteAgent}from"#internal/nitro/routes/channel-route-context.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#runtime/governance/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let o=buildRouteArgs(e,i,a.name,r),s;try{s=await withDevelopmentVercelOidcContext(r,e.req,async()=>{if(a.handler)return await a.handler(e.req,o.args);let t={agent:o.agent,waitUntil:o.args.waitUntil,params:o.args.params,requestIp:o.args.requestIp};return await a.fetch(e.req,t)})}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,o.backgroundTasks,t,a.name),s}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let o=a.websocket,s=buildRouteArgs(e,i,a.name,r);try{let n=await withDevelopmentVercelOidcContext(r,e.req,async()=>await o(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,s.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n):await n()}function buildRouteArgs(t,n,o,s){let c=readVercelRequestId(t.req.headers),l=extractRequestIp(t,s),u=[],d=t.context.params??{},f={};for(let[e,t]of Object.entries(d))f[e]=decodeURIComponent(t);let waitUntil=e=>{u.push(e)},p=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`},m=createRouteAgent(n.runtime,c);return{agent:m,args:attachRouteAgent(attachAgentInfoRouteResponse({send:createSendFn(n.runtime,p,o,{requestId:c}),cancel:createCancelFn(n.runtime,o),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:f,waitUntil,requestIp:l},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(s)}),m),backgroundTasks:u}}function createRouteAgent(e,t){return{async cancelTurn(t){return await e.cancelTurn(t)},async deliver(n){let r={...n,requestId:t};return await e.deliver(r)},async getEventStream(t,n){return await e.getEventStream(t,n)},async run(n){let r={...n,requestId:t};return await e.run(r)}}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
@@ -1,4 +1,4 @@
1
- export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type Channel, type ChannelCors, type ChannelCorsOptions, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/channel.js";
1
+ export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type CancelFn, type CancelOptions, type CancelTurnResult, type Channel, type ChannelCors, type ChannelCorsOptions, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/channel.js";
2
2
  export { createWebSocketUpgradeServer, type WebSocketUpgradeServerBridge, } from "#channel/websocket-upgrade-server.js";
3
3
  import type { Channel, InferChannelMetadata } from "#public/definitions/channel.js";
4
4
  /**
@@ -12,7 +12,7 @@ export type { CancelTurnInput, CancelTurnResult, GetEventStreamOptions } from "#
12
12
  export type { Session, SessionHandle } from "#channel/session.js";
13
13
  export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
14
14
  export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
15
- export type { HttpRouteDefinition, RouteDefinition, RouteHandlerArgs, SendFn, SendOptions, SendPayload, GetSessionFn, WebSocketMessage, WebSocketPeer, WebSocketRouteDefinition, WebSocketRouteHandler, WebSocketRouteHooks, WebSocketUpgradeRequest, WebSocketUpgradeResult, } from "#channel/routes.js";
15
+ export type { CancelFn, CancelOptions, HttpRouteDefinition, RouteDefinition, RouteHandlerArgs, SendFn, SendOptions, SendPayload, GetSessionFn, WebSocketMessage, WebSocketPeer, WebSocketRouteDefinition, WebSocketRouteHandler, WebSocketRouteHooks, WebSocketUpgradeRequest, WebSocketUpgradeResult, } from "#channel/routes.js";
16
16
  /**
17
17
  * HTTP method a route handles. Defaults to `"POST"` — almost every route
18
18
  * is a webhook. Override only when authoring a non-webhook route such as a
@@ -87,7 +87,7 @@ export type ToolContext = SessionContext & {
87
87
  * the extension (`agent/tools/get_weather.ts` registers as `get_weather`).
88
88
  * Authored definitions have no `name` field; identity is path-derived.
89
89
  */
90
- export type ToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefinition<TInput, TOutput> & {
90
+ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends PublicToolDefinition<TInput, TOutput> {
91
91
  execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput;
92
92
  /**
93
93
  * Optional per-tool approval gate. The return value determines whether
@@ -109,7 +109,7 @@ export type ToolDefinition<TInput = unknown, TOutput = unknown> = PublicToolDefi
109
109
  * (`action.result`) always receive the full output regardless.
110
110
  */
111
111
  toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
112
- };
112
+ }
113
113
  /**
114
114
  * Defines a tool configuration, used both for static tools (default export
115
115
  * from `agent/tools/*.ts`) and as the entry wrapper inside `defineDynamic`
@@ -1 +1 @@
1
- function toPublicToolDefinition(e){if(!e.execute)throw Error(`Tool "${e.name}" is client-side and cannot be re-exported publicly.`);let t=e.execute,n=e.inputSchema,r={description:e.description,execute:(e,n)=>t(e,{abortSignal:n.abortSignal,messages:[],toolCallId:n.callId}),inputSchema:n??{},outputSchema:e.outputSchema};return e.approval!==void 0&&(r.approval=e.approval),r}export{toPublicToolDefinition};
1
+ function toPublicToolDefinition(e){if(!e.execute)throw Error(`Tool "${e.name}" is client-side and cannot be re-exported publicly.`);let t=e.execute,n={description:e.description,execute:(e,n)=>t(e,{abortSignal:n.abortSignal,messages:[],toolCallId:n.callId}),inputSchema:e.inputSchema??{},outputSchema:e.outputSchema};return e.approval!==void 0&&(n.approval=e.approval),n}export{toPublicToolDefinition};
@@ -1,3 +1,3 @@
1
- import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{getPromptContentText}from"#runtime/agent/bootstrap-model-utils.js";function createMockAuthoredToolInput(e,t,n){let r=getToolInputPropertyNames(e.inputSchema);if(e.name===`ask_question`||hasProperties(r,[`prompt`,`options`]))return createAskQuestionInput(t);if(r.includes(`command`))return{command:resolveShellCommand(t)};if(r.includes(`topic`)||/\btopic\b/u.test(normalizeText(t)))return{topic:resolveLookupTopic(t)};let i=extractAnchoredInputs(r,t);return Object.keys(i).length>0?i:r.length===1&&r[0]===`message`?{message:t}:{city:n}}function extractAnchoredInputs(e,t){let n={};for(let r of e){let e=RegExp(`\\b${escapeRegExp(r)}\\b\\s*(?:to|=|:)?\\s*(?:\`([^\`]+)\`|"([^"]+)"|'([^']+)')`,`iu`).exec(t),i=e?.[1]??e?.[2]??e?.[3];i!==void 0&&(n[r]=i.trim())}return n}function escapeRegExp(e){return e.replace(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}function resolveMockFixtureToken(e){let n=e.filter(e=>e.role===`system`).map(e=>getPromptContentText(e.content)).join(`
1
+ import{LOAD_SKILL_TOOL_NAME}from"#runtime/skills/fragment-context.js";import{getPromptContentText}from"#runtime/agent/bootstrap-model-utils.js";import{createJsonSchemaSample}from"#runtime/agent/mock-structured-output.js";function createMockAuthoredToolInput(e,t,r){let i=getToolInputPropertyNames(e.inputSchema);if(e.name===`ask_question`||hasProperties(i,[`prompt`,`options`]))return createAskQuestionInput(t);if(i.includes(`command`))return{command:resolveShellCommand(t)};if(i.includes(`topic`)||!hasDeclaredInputProperties(e.inputSchema)&&/\btopic\b/u.test(normalizeText(t)))return{topic:resolveLookupTopic(t)};let a=extractAnchoredInputs(i,t);if(Object.keys(a).length>0)return a;if(i.length===1&&i[0]===`message`)return{message:t};if(i.includes(`city`)||!hasDeclaredInputProperties(e.inputSchema))return{city:r};let o=createJsonSchemaSample(e.inputSchema);return isRecord(o)?o:{}}function extractAnchoredInputs(e,t){let n={};for(let r of e){let e=RegExp(`\\b${escapeRegExp(r)}\\b\\s*(?:to|=|:)?\\s*(?:\`([^\`]+)\`|"([^"]+)"|'([^']+)')`,`iu`).exec(t),i=e?.[1]??e?.[2]??e?.[3];i!==void 0&&(n[r]=i.trim())}return n}function escapeRegExp(e){return e.replace(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}function resolveMockFixtureToken(e){let n=e.filter(e=>e.role===`system`).map(e=>getPromptContentText(e.content)).join(`
2
2
  `),r=[...getLoadedSkillResultTexts(e),n,getTrailingUserText(e)];for(let e of r){let t=resolveExactFixtureReply(e);if(t!==null)return t}return null}function resolveWeatherCity(e){let t=/"city"\s*:\s*"([^"]+)"/u.exec(e);return t?.[1]?t[1].trim():(/\b(?:in|for)\s+([A-Za-z][A-Za-z\s.-]*?)(?:[?.!,]|$)/u.exec(e)??/\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b/u.exec(e))?.[1]?.trim()||`Brooklyn`}function formatToolOutput(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function getTrailingUserText(e){let n=[];for(let r of[...e].reverse())if(r.role!==`system`){if(r.role!==`user`)break;n.unshift(getPromptContentText(r.content))}return n.join(`
3
- `)}function getLoadedSkillResultTexts(t){return t.flatMap(t=>t.role!==`tool`&&t.role!==`assistant`?[]:(typeof t.content==`string`?[t.content]:t.content).flatMap(t=>typeof t==`string`||t.type!==`tool-result`||t.toolName!==LOAD_SKILL_TOOL_NAME||t.output.type===`execution-denied`?[]:[formatToolOutput(t.output.value)]))}function resolveExactFixtureReply(e){let t=matchExactValue(/\breply\s+with\s+the\s+exact\s+string\s+(`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s.]+))\s+and\s+nothing\s+else\b/iu,e);if(t!==null)return t;let n=e.split(/\r?\n/u);for(let e=0;e<n.length;e+=1){let t=n[e]?.trim()??``,r=/\breply\s+with\s+exactly(?:\s+the\s+following\s+text\s+and\s+nothing\s+else)?:\s*(.+)$/iu.exec(t);if(r?.[1])return cleanExactValue(r[1]);if(/\breply\s+with\s+exactly\s+the\s+following\s+text\s+and\s+nothing\s+else:\s*$/iu.test(t)||/\breply\s+with\s+exactly:\s*$/iu.test(t)){let t=n.slice(e+1).map(e=>e.trim()).find(e=>e.length>0);if(t!==void 0)return cleanExactValue(t)}}return matchExactValue(/\binclude\s+the\s+exact\s+token\s+(`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s.]+))\s+verbatim\b/iu,e)}function matchExactValue(e,t){let n=e.exec(t);return n===null?null:cleanExactValue(n[2]??n[3]??n[4]??n[5]??n[1]??``)}function cleanExactValue(e){return e.trim()}function getToolInputPropertyNames(e){return!isRecord(e)||!isRecord(e.properties)?[]:Object.keys(e.properties)}function hasProperties(e,t){return t.every(t=>e.includes(t))}function createAskQuestionInput(e){let t=parseInputOptions(e),n={prompt:resolveQuestionPrompt(e)};return t.length>0&&(n.options=t),/\ballow\s*freeform\s+(?:to\s+)?true\b|\ballowfreeform\s+(?:to\s+)?true\b/iu.test(e)&&(n.allowFreeform=!0),n}function parseInputOptions(e){return[...e.matchAll(/\bid\b\s*:?\s*"([^"]+)"\s*,\s*label\b\s*:?\s*"([^"]+)"/giu)].map(e=>({id:e[1]??``,label:e[2]??``}))}function resolveQuestionPrompt(e){let t=/\b(?:set\s+)?prompt\s+to:\s*'([^']+)'/iu.exec(e)??/\b(?:set\s+)?prompt\s+to:\s*"([^"]+)"/iu.exec(e);return t?.[1]?t[1].trim():/\bask(?:\s+me)?\s+(?:to\s+)?(.+?)(?:\.|$)/iu.exec(e)?.[1]?.trim()||`Please choose an option.`}function resolveShellCommand(e){let t=/`([^`]+)`/u.exec(e);return t?.[1]?t[1].trim():(/\b(?:run|command)\s+["']([^"']+)["']/iu.exec(e)??/\bcommand\s+(.+?)(?:\.|$)/iu.exec(e))?.[1]?.trim()||`pwd`}function resolveLookupTopic(e){return/\btopic\s+['"]?([A-Za-z0-9_.-]+)['"]?/u.exec(e)?.[1]??`demo`}function normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,` `).trim()}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{createMockAuthoredToolInput,formatToolOutput,resolveMockFixtureToken,resolveWeatherCity};
3
+ `)}function getLoadedSkillResultTexts(t){return t.flatMap(t=>t.role!==`tool`&&t.role!==`assistant`?[]:(typeof t.content==`string`?[t.content]:t.content).flatMap(t=>typeof t==`string`||t.type!==`tool-result`||t.toolName!==LOAD_SKILL_TOOL_NAME||t.output.type===`execution-denied`?[]:[formatToolOutput(t.output.value)]))}function resolveExactFixtureReply(e){let t=matchExactValue(/\breply\s+with\s+the\s+exact\s+string\s+(`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s.]+))\s+and\s+nothing\s+else\b/iu,e);if(t!==null)return t;let n=e.split(/\r?\n/u);for(let e=0;e<n.length;e+=1){let t=n[e]?.trim()??``,r=/\breply\s+with\s+exactly(?:\s+the\s+following\s+text\s+and\s+nothing\s+else)?:\s*(.+)$/iu.exec(t);if(r?.[1])return cleanExactValue(r[1]);if(/\breply\s+with\s+exactly\s+the\s+following\s+text\s+and\s+nothing\s+else:\s*$/iu.test(t)||/\breply\s+with\s+exactly:\s*$/iu.test(t)){let t=n.slice(e+1).map(e=>e.trim()).find(e=>e.length>0);if(t!==void 0)return cleanExactValue(t)}}return matchExactValue(/\binclude\s+the\s+exact\s+token\s+(`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s.]+))\s+verbatim\b/iu,e)}function matchExactValue(e,t){let n=e.exec(t);return n===null?null:cleanExactValue(n[2]??n[3]??n[4]??n[5]??n[1]??``)}function cleanExactValue(e){return e.trim()}function getToolInputPropertyNames(e){return!isRecord(e)||!isRecord(e.properties)?[]:Object.keys(e.properties)}function hasDeclaredInputProperties(e){return isRecord(e)&&isRecord(e.properties)}function hasProperties(e,t){return t.every(t=>e.includes(t))}function createAskQuestionInput(e){let t=parseInputOptions(e),n={prompt:resolveQuestionPrompt(e)};return t.length>0&&(n.options=t),/\ballow\s*freeform\s+(?:to\s+)?true\b|\ballowfreeform\s+(?:to\s+)?true\b/iu.test(e)&&(n.allowFreeform=!0),n}function parseInputOptions(e){return[...e.matchAll(/\bid\b\s*:?\s*"([^"]+)"\s*,\s*label\b\s*:?\s*"([^"]+)"/giu)].map(e=>({id:e[1]??``,label:e[2]??``}))}function resolveQuestionPrompt(e){let t=/\b(?:set\s+)?prompt\s+to:\s*'([^']+)'/iu.exec(e)??/\b(?:set\s+)?prompt\s+to:\s*"([^"]+)"/iu.exec(e);return t?.[1]?t[1].trim():/\bask(?:\s+me)?\s+(?:to\s+)?(.+?)(?:\.|$)/iu.exec(e)?.[1]?.trim()||`Please choose an option.`}function resolveShellCommand(e){let t=/`([^`]+)`/u.exec(e);return t?.[1]?t[1].trim():(/\b(?:run|command)\s+["']([^"']+)["']/iu.exec(e)??/\bcommand\s+(.+?)(?:\.|$)/iu.exec(e))?.[1]?.trim()||`pwd`}function resolveLookupTopic(e){return/\btopic\s+['"]?([A-Za-z0-9_.-]+)['"]?/u.exec(e)?.[1]??`demo`}function normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,` `).trim()}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{createMockAuthoredToolInput,formatToolOutput,resolveMockFixtureToken,resolveWeatherCity};
@@ -1 +1 @@
1
- import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{jsonSchema,tool}from"ai";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,n,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(n)?n:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),a=this.#a(e),o=this.#s(e),s=this.#n.tools,c=s===void 0?o:o.filter(e=>passesToolFilter(e.toolName,s)),l=[],u=new Map,d={};for(let e of c)u.set(e.toolName,e),l.push({description:e.description,inputSchema:e.inputSchema,name:e.toolName}),d[e.toolName]=tool({description:e.description,inputSchema:jsonSchema(e.inputSchema),execute:async(n,r)=>this.#f(e,a,isObject(n)?n:{},{abortSignal:r?.abortSignal})});return{metadata:l,operations:u,tools:d,baseUrl:a}}#a(e){let t=this.#n.url,n=typeof t==`string`&&t.trim().length>0?t:extractServerUrl(e,this.#n.spec);if(n===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" has no base URL: set "baseUrl" or ensure the document declares an absolute "servers" entry or Swagger "host".`);return assertSecureUrl(n,this.#n.connectionName,`base`),n}async#o(){let e=this.#n.spec;if(e===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" is missing its "spec" source.`);if(typeof e!=`string`)return e;assertSecureUrl(e,this.#n.connectionName,`spec`);let n;try{n=await fetch(e,{headers:{accept:`application/json, application/yaml, text/yaml, */*`}})}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": ${String(t)}`)}if(n.redirected&&assertSecureUrl(n.url,this.#n.connectionName,`spec`),!n.ok)throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": HTTP ${n.status}.`);let r=await n.text(),i;try{i=parseSpecDocument(r)}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" could not be parsed as JSON or YAML: ${String(t)}`)}if(!isObject(i))throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" is not an OpenAPI document object.`);return i}#s(e){let n=e.paths;if(!isObject(n))return[];let r=[],i=new Set;for(let[a,d]of Object.entries(n)){if(!isObject(d))continue;let n=isArray(d.parameters)?d.parameters:[];for(let f of HTTP_METHODS){let o=d[f];if(!isObject(o))continue;let p=uniqueName(operationName(o,f,a),i),m=isArray(o.parameters)?o.parameters:[],h=[...n,...m],g=this.#c(e,h),_=this.#l(e,o.requestBody,h);r.push({toolName:p,method:f,pathTemplate:a,description:operationDescription(o),parameters:g,requestBody:_,inputSchema:buildInputSchema(g,_),security:resolveSecurity(e,o)})}}return r}#c(e,n){let r=[];for(let i of n){let n=isObject(i)?deref(e,i):i;if(!isObject(n))continue;let a=n.in;if(a!==`path`&&a!==`query`&&a!==`header`&&a!==`cookie`||typeof n.name!=`string`)continue;let o=this.#u(e,n);r.push({name:n.name,location:a,required:n.required===!0||a===`path`,schema:o,description:typeof n.description==`string`?n.description:void 0})}return r}#l(e,n,r=[]){if(isObject(n)){let r=deref(e,n);if(isObject(r)&&isObject(r.content)){let n=r.content,i=`application/json`in n?`application/json`:Object.keys(n)[0];if(i!==void 0){let a=n[i],o=isObject(a)&&isObject(a.schema)?derefSchema(e,a.schema):{};return{required:r.required===!0,contentType:i,schema:o}}}}return this.#d(e,r)}#u(e,n){if(isObject(n.schema))return derefSchema(e,n.schema);let r={};for(let e of SWAGGER_PARAMETER_SCHEMA_KEYS)n[e]!==void 0&&(r[e]=n[e]);return derefSchema(e,r)}#d(e,n){for(let r of n){let n=isObject(r)?deref(e,r):r;if(!isObject(n)||n.in!==`body`)continue;let i=isObject(n.schema)?derefSchema(e,n.schema):{};return{required:n.required===!0,contentType:`application/json`,schema:i}}}async#f(e,t,n,r){let i=await resolveHeaders(this.#n),o=e.pathTemplate,s=new URLSearchParams,c=[];for(let t of e.parameters){let e=n[t.name];e!=null&&(t.location===`path`?o=o.replace(`{${t.name}}`,encodeURIComponent(String(e))):t.location===`query`?appendQuery(s,t.name,e):t.location===`cookie`?c.push(`${t.name}=${encodeURIComponent(String(e))}`):i[t.name]=String(e))}if(applySecurity(e.security,this.#n,i,s,c),c.length>0){let e=i.cookie??i.Cookie;delete i.Cookie,i.cookie=[e,...c].filter(e=>!!e).join(`; `)}let l=new URL(joinPath(t,o));l.search=s.toString();let u;e.requestBody!==void 0&&n.body!==void 0&&(u=JSON.stringify(n.body),i[`content-type`]=e.requestBody.contentType);let d=await fetch(l,{method:e.method.toUpperCase(),headers:i,body:u,signal:r?.abortSignal});return{status:d.status,statusText:d.statusText,body:await readResponseBody(d)}}};function appendQuery(e,t,n){if(isArray(n)){for(let r of n)e.append(t,String(r));return}e.append(t,String(n))}function joinPath(e,t){return`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`}function assertSecureUrl(t,n,r){let i;try{i=new URL(t)}catch{throw Error(`OpenAPI connection "${n}" has an invalid ${r} URL "${t}".`)}if(i.protocol!==`https:`&&!(i.protocol===`http:`&&isLoopbackHostname(i.hostname)))throw Error(`OpenAPI connection "${n}" must use https for its ${r} (got "${i.protocol}//${i.host}").`)}async function readResponseBody(e){let t=await e.text();if(t.length===0)return null;if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return JSON.parse(t)}catch{return t}return t}export{OpenApiConnectionClient};
1
+ import{createLogger}from"#internal/logging.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isObject}from"#shared/guards.js";import{toInputSchema}from"#shared/tool-schema.js";import{tool}from"ai";import{passesToolFilter,resolveHeaders}from"#runtime/connections/mcp-client.js";import{HTTP_METHODS,operationDescription,operationName,uniqueName}from"#runtime/connections/openapi-operations.js";import{buildInputSchema,deref,derefSchema,isArray}from"#runtime/connections/openapi-schema.js";import{applySecurity,resolveSecurity}from"#runtime/connections/openapi-security.js";import{extractServerUrl,parseSpecDocument}from"#runtime/connections/openapi-spec.js";const log=createLogger(`runtime.connections.openapi-client`),SWAGGER_PARAMETER_SCHEMA_KEYS=[`default`,`enum`,`exclusiveMaximum`,`exclusiveMinimum`,`format`,`items`,`maximum`,`maxItems`,`maxLength`,`minimum`,`minItems`,`minLength`,`multipleOf`,`pattern`,`type`,`uniqueItems`];var OpenApiConnectionClient=class{#e;#t;#n;constructor(e){this.#n=e}async connect(){return this.#r()}async getToolMetadata(){return(await this.#r()).metadata}async getTools(){return(await this.#r()).tools}async executeTool(e,t,r){let i=await this.#r(),a=i.operations.get(e);if(a===void 0)throw Error(`Tool "${e}" not found in connection "${this.#n.connectionName}".`);return this.#f(a,i.baseUrl,isObject(t)?t:{},{abortSignal:r?.abortSignal})}async close(){this.#e=void 0,this.#t=void 0}async#r(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#i();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#i(){let e=await this.#o(),t=this.#a(e),o=this.#s(e),s=this.#n.tools,c=s===void 0?o:o.filter(e=>passesToolFilter(e.toolName,s)),l=[],u=new Map,d={};for(let e of c){let a;try{a=toInputSchema(e.inputSchema)}catch(t){log.warn(`omitting OpenAPI operation with an invalid input schema`,{connectionName:this.#n.connectionName,error:t,toolName:e.toolName});continue}u.set(e.toolName,e),l.push({description:e.description,inputSchema:e.inputSchema,name:e.toolName}),d[e.toolName]=tool({description:e.description,inputSchema:a,execute:async(r,i)=>this.#f(e,t,isObject(r)?r:{},{abortSignal:i?.abortSignal})})}return{metadata:l,operations:u,tools:d,baseUrl:t}}#a(e){let t=this.#n.url,n=typeof t==`string`&&t.trim().length>0?t:extractServerUrl(e,this.#n.spec);if(n===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" has no base URL: set "baseUrl" or ensure the document declares an absolute "servers" entry or Swagger "host".`);return assertSecureUrl(n,this.#n.connectionName,`base`),n}async#o(){let e=this.#n.spec;if(e===void 0)throw Error(`OpenAPI connection "${this.#n.connectionName}" is missing its "spec" source.`);if(typeof e!=`string`)return e;assertSecureUrl(e,this.#n.connectionName,`spec`);let t;try{t=await fetch(e,{headers:{accept:`application/json, application/yaml, text/yaml, */*`}})}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": ${String(t)}`)}if(t.redirected&&assertSecureUrl(t.url,this.#n.connectionName,`spec`),!t.ok)throw Error(`OpenAPI connection "${this.#n.connectionName}" failed to fetch its spec from "${e}": HTTP ${t.status}.`);let r=await t.text(),i;try{i=parseSpecDocument(r)}catch(t){throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" could not be parsed as JSON or YAML: ${String(t)}`)}if(!isObject(i))throw Error(`OpenAPI connection "${this.#n.connectionName}" spec at "${e}" is not an OpenAPI document object.`);return i}#s(e){let t=e.paths;if(!isObject(t))return[];let r=[],i=new Set;for(let[a,o]of Object.entries(t)){if(!isObject(o))continue;let t=isArray(o.parameters)?o.parameters:[];for(let f of HTTP_METHODS){let s=o[f];if(!isObject(s))continue;let p=uniqueName(operationName(s,f,a),i),m=isArray(s.parameters)?s.parameters:[],h=[...t,...m],g=this.#c(e,h),_=this.#l(e,s.requestBody,h);r.push({toolName:p,method:f,pathTemplate:a,description:operationDescription(s),parameters:g,requestBody:_,inputSchema:buildInputSchema(g,_),security:resolveSecurity(e,s)})}}return r}#c(e,t){let r=[];for(let i of t){let t=isObject(i)?deref(e,i):i;if(!isObject(t))continue;let a=t.in;if(a!==`path`&&a!==`query`&&a!==`header`&&a!==`cookie`||typeof t.name!=`string`)continue;let o=this.#u(e,t);r.push({name:t.name,location:a,required:t.required===!0||a===`path`,schema:o,description:typeof t.description==`string`?t.description:void 0})}return r}#l(e,t,r=[]){if(isObject(t)){let r=deref(e,t);if(isObject(r)&&isObject(r.content)){let t=r.content,i=`application/json`in t?`application/json`:Object.keys(t)[0];if(i!==void 0){let a=t[i],o=isObject(a)&&isObject(a.schema)?derefSchema(e,a.schema):{};return{required:r.required===!0,contentType:i,schema:o}}}}return this.#d(e,r)}#u(e,t){if(isObject(t.schema))return derefSchema(e,t.schema);let r={};for(let e of SWAGGER_PARAMETER_SCHEMA_KEYS)t[e]!==void 0&&(r[e]=t[e]);return derefSchema(e,r)}#d(e,t){for(let r of t){let t=isObject(r)?deref(e,r):r;if(!isObject(t)||t.in!==`body`)continue;let i=isObject(t.schema)?derefSchema(e,t.schema):{};return{required:t.required===!0,contentType:`application/json`,schema:i}}}async#f(e,t,n,r){let i=await resolveHeaders(this.#n),a=e.pathTemplate,s=new URLSearchParams,c=[];for(let t of e.parameters){let e=n[t.name];e!=null&&(t.location===`path`?a=a.replace(`{${t.name}}`,encodeURIComponent(String(e))):t.location===`query`?appendQuery(s,t.name,e):t.location===`cookie`?c.push(`${t.name}=${encodeURIComponent(String(e))}`):i[t.name]=String(e))}if(applySecurity(e.security,this.#n,i,s,c),c.length>0){let e=i.cookie??i.Cookie;delete i.Cookie,i.cookie=[e,...c].filter(e=>!!e).join(`; `)}let l=new URL(joinPath(t,a));l.search=s.toString();let u;e.requestBody!==void 0&&n.body!==void 0&&(u=JSON.stringify(n.body),i[`content-type`]=e.requestBody.contentType);let d=await fetch(l,{method:e.method.toUpperCase(),headers:i,body:u,signal:r?.abortSignal});return{status:d.status,statusText:d.statusText,body:await readResponseBody(d)}}};function appendQuery(e,t,n){if(isArray(n)){for(let r of n)e.append(t,String(r));return}e.append(t,String(n))}function joinPath(e,t){return`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`}function assertSecureUrl(e,n,r){let i;try{i=new URL(e)}catch{throw Error(`OpenAPI connection "${n}" has an invalid ${r} URL "${e}".`)}if(i.protocol!==`https:`&&!(i.protocol===`http:`&&isLoopbackHostname(i.hostname)))throw Error(`OpenAPI connection "${n}" must use https for its ${r} (got "${i.protocol}//${i.host}").`)}async function readResponseBody(e){let t=await e.text();if(t.length===0)return null;if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return JSON.parse(t)}catch{return t}return t}export{OpenApiConnectionClient};
@@ -1,17 +1,31 @@
1
- import type { JsonObject } from "#shared/json.js";
1
+ import { z } from "#compiled/zod/index.js";
2
2
  import type { ResolvedToolDefinition } from "#runtime/types.js";
3
3
  /**
4
4
  * Stable model-visible name for the framework question tool.
5
5
  */
6
6
  export declare const ASK_QUESTION_TOOL_NAME = "ask_question";
7
- /**
8
- * Shared input schema used by the framework `ask_question` tool.
9
- */
10
- export declare const ASK_QUESTION_INPUT_SCHEMA: JsonObject;
11
- /**
12
- * Shared output schema used by the framework `ask_question` tool.
13
- */
14
- export declare const ASK_QUESTION_OUTPUT_SCHEMA: JsonObject;
7
+ export declare const ASK_QUESTION_INPUT_SCHEMA: z.ZodObject<{
8
+ allowFreeform: z.ZodOptional<z.ZodBoolean>;
9
+ options: z.ZodOptional<z.ZodArray<z.ZodObject<{
10
+ description: z.ZodOptional<z.ZodString>;
11
+ id: z.ZodString;
12
+ label: z.ZodString;
13
+ style: z.ZodOptional<z.ZodEnum<{
14
+ danger: "danger";
15
+ default: "default";
16
+ primary: "primary";
17
+ }>>;
18
+ }, z.core.$strict>>>;
19
+ prompt: z.ZodString;
20
+ }, z.core.$strict>;
21
+ export declare const ASK_QUESTION_OUTPUT_SCHEMA: z.ZodObject<{
22
+ optionId: z.ZodOptional<z.ZodString>;
23
+ status: z.ZodEnum<{
24
+ answered: "answered";
25
+ ignored: "ignored";
26
+ }>;
27
+ text: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strict>;
15
29
  /**
16
30
  * Root-only framework tool that lets the agent request structured user input.
17
31
  *
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{inputRequestSchema}from"#runtime/input/types.js";const ASK_QUESTION_TOOL_NAME=`ask_question`,askQuestionToolInputSchema=inputRequestSchema.omit({action:!0,display:!0,requestId:!0}),{$schema:_jsonSchemaVersion,...askQuestionInputSchema}=z.toJSONSchema(askQuestionToolInputSchema),askQuestionToolOutputSchema=z.object({optionId:z.string().optional(),status:z.enum([`answered`,`ignored`]),text:z.string().optional()}).strict(),{$schema:_outputJsonSchemaVersion,...askQuestionOutputSchema}=z.toJSONSchema(askQuestionToolOutputSchema),ASK_QUESTION_INPUT_SCHEMA=askQuestionInputSchema,ASK_QUESTION_OUTPUT_SCHEMA=askQuestionOutputSchema,ASK_QUESTION_TOOL_DEFINITION={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:ASK_QUESTION_INPUT_SCHEMA,logicalPath:`eve:framework/ask-question`,name:ASK_QUESTION_TOOL_NAME,outputSchema:ASK_QUESTION_OUTPUT_SCHEMA,sourceId:`eve:ask-question-tool`,sourceKind:`module`};export{ASK_QUESTION_INPUT_SCHEMA,ASK_QUESTION_OUTPUT_SCHEMA,ASK_QUESTION_TOOL_DEFINITION,ASK_QUESTION_TOOL_NAME};
1
+ import{z}from"#compiled/zod/index.js";import{inputRequestSchema}from"#runtime/input/types.js";const ASK_QUESTION_TOOL_NAME=`ask_question`,ASK_QUESTION_INPUT_SCHEMA=inputRequestSchema.omit({action:!0,display:!0,requestId:!0}),ASK_QUESTION_OUTPUT_SCHEMA=z.object({optionId:z.string().optional(),status:z.enum([`answered`,`ignored`]),text:z.string().optional()}).strict(),ASK_QUESTION_TOOL_DEFINITION={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:ASK_QUESTION_INPUT_SCHEMA,logicalPath:`eve:framework/ask-question`,name:ASK_QUESTION_TOOL_NAME,outputSchema:ASK_QUESTION_OUTPUT_SCHEMA,sourceId:`eve:ask-question-tool`,sourceKind:`module`};export{ASK_QUESTION_INPUT_SCHEMA,ASK_QUESTION_OUTPUT_SCHEMA,ASK_QUESTION_TOOL_DEFINITION,ASK_QUESTION_TOOL_NAME};
@@ -1,4 +1,4 @@
1
- import type { JsonObject } from "#shared/json.js";
1
+ import { z } from "#compiled/zod/index.js";
2
2
  import type { ResolvedToolDefinition } from "#runtime/types.js";
3
3
  /**
4
4
  * Shared input schema used by the framework `bash` tool and any author tool
@@ -8,10 +8,17 @@ import type { ResolvedToolDefinition } from "#runtime/types.js";
8
8
  * `BASH_TOOL_DEFINITION` use the exact same schema object — keeping model
9
9
  * input contracts in sync without duplication.
10
10
  */
11
- export declare const BASH_INPUT_SCHEMA: JsonObject;
11
+ export declare const BASH_INPUT_SCHEMA: z.ZodObject<{
12
+ command: z.ZodString;
13
+ }, z.core.$strict>;
12
14
  /**
13
15
  * Shared output schema used by the framework `bash` tool and any author tool
14
16
  * constructed via {@link defineBashTool}.
15
17
  */
16
- export declare const BASH_OUTPUT_SCHEMA: JsonObject;
18
+ export declare const BASH_OUTPUT_SCHEMA: z.ZodObject<{
19
+ exitCode: z.ZodNumber;
20
+ stderr: z.ZodString;
21
+ stdout: z.ZodString;
22
+ truncated: z.ZodBoolean;
23
+ }, z.core.$strict>;
17
24
  export declare const BASH_TOOL_DEFINITION: ResolvedToolDefinition;
@@ -1 +1 @@
1
- import{requireSandboxSession}from"#execution/sandbox/require-sandbox.js";import{executeBashOnSandbox}from"#execution/sandbox/bash-tool.js";const BASH_INPUT_SCHEMA={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`},BASH_OUTPUT_SCHEMA={additionalProperties:!1,properties:{exitCode:{type:`number`},stderr:{type:`string`},stdout:{type:`string`},truncated:{type:`boolean`}},required:[`exitCode`,`stderr`,`stdout`,`truncated`],type:`object`};async function executeBash(e,t){return executeBashOnSandbox(await requireSandboxSession(t?.abortSignal),e)}const BASH_TOOL_DEFINITION={description:`Execute a shell command in the shared workspace environment.`,execute:executeBash,inputSchema:BASH_INPUT_SCHEMA,logicalPath:`eve:framework/bash`,name:`bash`,outputSchema:BASH_OUTPUT_SCHEMA,sourceId:`eve:bash-tool`,sourceKind:`module`};export{BASH_INPUT_SCHEMA,BASH_OUTPUT_SCHEMA,BASH_TOOL_DEFINITION};
1
+ import{z}from"#compiled/zod/index.js";import{requireSandboxSession}from"#execution/sandbox/require-sandbox.js";import{executeBashOnSandbox}from"#execution/sandbox/bash-tool.js";const BASH_INPUT_SCHEMA=z.strictObject({command:z.string().describe(`The shell command to execute.`)}),BASH_OUTPUT_SCHEMA=z.strictObject({exitCode:z.number(),stderr:z.string(),stdout:z.string(),truncated:z.boolean()});async function executeBash(e,t){return executeBashOnSandbox(await requireSandboxSession(t?.abortSignal),e)}const BASH_TOOL_DEFINITION={description:`Execute a shell command in the shared workspace environment.`,execute:executeBash,inputSchema:BASH_INPUT_SCHEMA,logicalPath:`eve:framework/bash`,name:`bash`,outputSchema:BASH_OUTPUT_SCHEMA,sourceId:`eve:bash-tool`,sourceKind:`module`};export{BASH_INPUT_SCHEMA,BASH_OUTPUT_SCHEMA,BASH_TOOL_DEFINITION};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_OUTPUT_SCHEMA={items:{additionalProperties:!1,properties:{connection:{type:`string`},description:{type:`string`},error:{type:`string`},inputSchema:{type:`object`},needsAuthorization:{type:`boolean`},outputSchema:{type:`object`},qualifiedName:{type:`string`},tool:{type:`string`}},required:[`connection`,`description`],type:`object`},type:`array`},ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e){let n=loadContext(),r=new Set;for(let t of e.getConnections()){let i=getAuthorizationResult(t.connectionName);if(!i)continue;let a=await resolveInteractiveAuth(e,t.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(t.connectionName,a),c=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:{url:t.url??``},principal:o,resume:i.resume,callback:i.callback});writeCachedToken(n,t.connectionName,principalKey(o),c),r.add(t.connectionName)}return r}async function executeConnectionSearch(e){let n=loadContext(),i=n.get(ConnectionRegistryKey);if(i===void 0)return[];let s=await completePendingAuthorizations(i),l=e.limit??10,u=tokenize(e.keywords),d=[],f=[],m=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections(),g=[];for(let e of m){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(s.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let n=getHookUrl(e.connectionName);if(n){let r=resolveConnectionPrincipal(e.connectionName,t),i=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:n});try{let{challenge:n,resume:a}=await t.startAuthorization({callbackUrl:i,connection:{url:e.url??``},principal:r});g.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:i,resume:a})}catch(t){logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:t instanceof Error?t:Error(String(t))})}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let n=t instanceof Error?t.message:`unknown error`;logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:t instanceof Error?t:Error(n)}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${n}`});continue}for(let n of t){let t=scoreMatch(u,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(g.length>0)return requestAuthorization(g);d.sort((e,t)=>t.score-e.score);let _=d.slice(0,l).map(e=>e.item);if(_.length>0){let e=[..._,...f],t=n.get(ConnectionSearchResultsKey)??[],r=new Map(t.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return n.set(ConnectionSearchResultsKey,[...r.values()]),e}return m.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}function createConnectionSearchEvents(){return{"step.started":async(e,n)=>{let a=loadContext().get(ConnectionRegistryKey);if(!a||a.getConnections().length===0)return null;let l=a.getConnections().map(e=>e.connectionName),u=extractDiscoveredTools(n.messages),p=loadContext().get(ConnectionSearchResultsKey)??[],g=new Map;for(let e of p)e.qualifiedName&&g.set(e.qualifiedName,e);for(let e of u)e.qualifiedName&&g.set(e.qualifiedName,e);let _=[...g.values()],v={};v.connection_search={description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${l.join(`, `)}.`,inputSchema:{type:`object`,additionalProperties:!1,properties:{keywords:{description:`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`,type:`string`},connection:{description:`Optional: limit search to a specific connection name.`,type:`string`},limit:{description:`Max results to return. Default 10.`,type:`number`}},required:[`keywords`]},async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA};for(let e of _){let n=e.connection,l=e.tool,u=a.getConnectionApproval(n);v[qualifiedConnectionToolName(n,l)]={description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:u,outputSchema:e.outputSchema,async execute(e,a){let u=loadContext().get(ConnectionRegistryKey),p=u.getConnections().find(e=>e.connectionName===n),m=await resolveInteractiveAuth(u,n),h=!1;if(m){let e=getAuthorizationResult(n);if(e){h=!0;let r=loadContext(),i=resolveConnectionPrincipal(n,m),a=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:i,resume:e.resume,callback:e.callback});writeCachedToken(r,n,principalKey(i),a)}}try{return await u.getClient(n).executeTool(l,e,{abortSignal:a.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(h)throw new ConnectionAuthorizationFailedError(n,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${n}" rejected the token immediately after authorization.`});let t=getHookUrl(n);if(!t)throw e;let r=resolveConnectionPrincipal(n,m),a=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t}),{challenge:s,resume:l}=await m.startAuthorization({callbackUrl:a,connection:{url:p?.url??``},principal:r});return requestAuthorization([{name:n,challenge:stampChallengeDisplayName(s,m),hookUrl:a,resume:l}])}}}}return v}}}function createConnectionSearchResolver(){let e=createConnectionSearchEvents();return{slug:`connection`,eventNames:Object.keys(e),events:e,sourceId:`eve:connection-search-dynamic`,sourceKind:`module`,logicalPath:`eve:framework/connection-search-dynamic`}}export{createConnectionSearchEvents,createConnectionSearchResolver,extractDiscoveredTools};
1
+ import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{getAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e){let t=loadContext(),r=new Set;for(let n of e.getConnections()){let i=getAuthorizationResult(n.connectionName);if(!i)continue;let a=await resolveInteractiveAuth(e,n.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(n.connectionName,a),s=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:{url:n.url??``},principal:o,resume:i.resume,callback:i.callback});writeCachedToken(t,n.connectionName,principalKey(o),s),r.add(n.connectionName)}return r}async function executeConnectionSearch(e){let t=loadContext(),r=t.get(ConnectionRegistryKey);if(r===void 0)return[];let a=await completePendingAuthorizations(r),c=e.limit??10,l=tokenize(e.keywords),u=[],d=[],f=e.connection!==void 0&&e.connection!==``?r.getConnections().filter(t=>t.connectionName===e.connection):r.getConnections(),m=[];for(let e of f){let t;try{t=await r.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(a.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),d.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(r,e.connectionName);if(t){let n=getHookUrl(e.connectionName);if(n){let r=resolveConnectionPrincipal(e.connectionName,t),i=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:n});try{let{challenge:n,resume:a}=await t.startAuthorization({callbackUrl:i,connection:{url:e.url??``},principal:r});m.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:i,resume:a})}catch(t){logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:t instanceof Error?t:Error(String(t))})}}}d.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),d.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let n=t instanceof Error?t.message:`unknown error`;logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:t instanceof Error?t:Error(n)}),d.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${n}`});continue}for(let n of t){let t=scoreMatch(l,n);t>0&&u.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(m.length>0)return requestAuthorization(m);u.sort((e,t)=>t.score-e.score);let h=u.slice(0,c).map(e=>e.item);if(h.length>0){let e=[...h,...d],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of h)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return f.map(e=>d.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}function createConnectionSearchEvents(){return{"step.started":async(e,t)=>{let r=loadContext().get(ConnectionRegistryKey);if(!r||r.getConnections().length===0)return null;let o=r.getConnections().map(e=>e.connectionName),l=extractDiscoveredTools(t.messages),u=loadContext().get(ConnectionSearchResultsKey)??[],p=new Map;for(let e of u)e.qualifiedName&&p.set(e.qualifiedName,e);for(let e of l)e.qualifiedName&&p.set(e.qualifiedName,e);let h=[...p.values()],g={};g.connection_search={description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${o.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,async execute(e){return executeConnectionSearch(e)},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA};for(let e of h){let t=e.connection,o=e.tool,l=r.getConnectionApproval(t);g[qualifiedConnectionToolName(t,o)]={description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:l,outputSchema:e.outputSchema,async execute(e,r){let l=loadContext().get(ConnectionRegistryKey),u=l.getConnections().find(e=>e.connectionName===t),p=await resolveInteractiveAuth(l,t),m=!1;if(p){let e=getAuthorizationResult(t);if(e){m=!0;let r=loadContext(),i=resolveConnectionPrincipal(t,p),a=await p.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:u?.url??``},principal:i,resume:e.resume,callback:e.callback});writeCachedToken(r,t,principalKey(i),a)}}try{return await l.getClient(t).executeTool(o,e,{abortSignal:r.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!p)throw e;if(m)throw new ConnectionAuthorizationFailedError(t,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${t}" rejected the token immediately after authorization.`});let n=getHookUrl(t);if(!n)throw e;let r=resolveConnectionPrincipal(t,p),i=resolveAuthorizationCallbackUrl({authorization:p,callbackUrl:n}),{challenge:o,resume:c}=await p.startAuthorization({callbackUrl:i,connection:{url:u?.url??``},principal:r});return requestAuthorization([{name:t,challenge:stampChallengeDisplayName(o,p),hookUrl:i,resume:c}])}}}}return g}}}function createConnectionSearchResolver(){let e=createConnectionSearchEvents();return{slug:`connection`,eventNames:Object.keys(e),events:e,sourceId:`eve:connection-search-dynamic`,sourceKind:`module`,logicalPath:`eve:framework/connection-search-dynamic`}}export{createConnectionSearchEvents,createConnectionSearchResolver,extractDiscoveredTools};
@@ -1,4 +1,4 @@
1
- import { type Tool } from "ai";
1
+ import type { Tool } from "ai";
2
2
  import type { JsonObject } from "#shared/json.js";
3
3
  /**
4
4
  * Stable model-visible name for the framework structured-output tool.
@@ -1 +1 @@
1
- import{jsonSchema}from"ai";const FINAL_OUTPUT_TOOL_NAME=`final_output`;function buildFinalOutputTool(e){return{description:`Deliver your final answer in the required structure by calling this tool. Call it exactly once, when you are done; do not answer in prose.`,inputSchema:jsonSchema(e),outputSchema:jsonSchema(e)}}export{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool};
1
+ import{toInputSchema}from"#shared/tool-schema.js";const FINAL_OUTPUT_TOOL_NAME=`final_output`;function buildFinalOutputTool(e){let t=toInputSchema(e);return{description:`Deliver your final answer in the required structure by calling this tool. Call it exactly once, when you are done; do not answer in prose.`,inputSchema:t,outputSchema:t}}export{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool};