eve 0.52.3 → 0.52.4
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.
- package/CHANGELOG.md +13 -0
- package/dist/src/cli/commands/registry-add-command.d.ts +3 -0
- package/dist/src/cli/commands/registry-add-command.js +1 -0
- package/dist/src/cli/commands/registry-metadata.d.ts +4 -1
- package/dist/src/cli/commands/registry-metadata.js +1 -1
- package/dist/src/cli/commands/registry.d.ts +1 -2
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/evals/reporters/index.d.ts +1 -0
- package/dist/src/evals/reporters/index.js +1 -1
- package/dist/src/evals/runner/reporters/datadog.d.ts +137 -0
- package/dist/src/evals/runner/reporters/datadog.js +3 -0
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel-options.d.ts +10 -0
- package/dist/src/execution/sandbox/bindings/vercel-options.js +1 -0
- package/dist/src/execution/sandbox/bindings/vercel.js +2 -1
- package/dist/src/execution/sandbox/shell-quote.d.ts +1 -12
- package/dist/src/execution/sandbox/shell-quote.js +1 -1
- package/dist/src/execution/session-command-inbox.js +1 -1
- package/dist/src/execution/tasks/child/workflow.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tool-auth.d.ts +4 -32
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/tools/connection-search.js +2 -2
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.d.ts +1 -1
- package/dist/src/execution/tools/subagent/accept-event-step.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/workflow/ask.d.ts +3 -2
- package/dist/src/execution/tools/workflow/ask.js +1 -1
- package/dist/src/execution/tools/workflow/authorization-completion.d.ts +3 -0
- package/dist/src/execution/tools/workflow/authorization-completion.js +1 -0
- package/dist/src/execution/tools/workflow/body.d.ts +2 -0
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/step-context.d.ts +31 -0
- package/dist/src/execution/tools/workflow/step-context.js +1 -0
- package/dist/src/execution/tools/workflow/step-execution.d.ts +3 -0
- package/dist/src/execution/tools/workflow/step-execution.js +1 -0
- package/dist/src/execution/tools/workflow/step.d.ts +3 -0
- package/dist/src/execution/tools/workflow/step.js +1 -0
- package/dist/src/execution/turn-workflow-tool-run.js +1 -1
- package/dist/src/execution/wire/session-inbox-contract.d.ts +7 -0
- package/dist/src/execution/wire/session-inbox-contract.js +1 -1
- package/dist/src/execution/wire/session-inbox-resume.d.ts +2 -0
- package/dist/src/execution/wire/session-inbox-resume.js +1 -1
- package/dist/src/harness/authorization.d.ts +5 -2
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/vercel/build-command.d.ts +2 -1
- package/dist/src/internal/vercel/build-command.js +1 -1
- package/dist/src/internal/workflow-bundle/builder-support.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-builders.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.d.ts +3 -5
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +4 -3
- package/dist/src/public/channels/github/checkout.js +1 -1
- package/dist/src/public/channels/slack/activity.js +1 -1
- package/dist/src/runtime/authorization-context.d.ts +14 -0
- package/dist/src/runtime/authorization-context.js +1 -0
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/scoped-authorization.d.ts +18 -2
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/sandbox/keys.js +1 -1
- package/dist/src/sandbox/backends/default.d.ts +2 -0
- package/dist/src/sandbox/backends/default.js +1 -1
- package/dist/src/self-modification/agent.d.ts +5 -2
- package/dist/src/self-modification/agent.js +1 -1
- package/dist/src/self-modification/config.d.ts +52 -0
- package/dist/src/self-modification/config.js +1 -0
- package/dist/src/self-modification/credentials.d.ts +18 -0
- package/dist/src/self-modification/credentials.js +1 -0
- package/dist/src/self-modification/extension/eve-add.d.ts +7 -2
- package/dist/src/self-modification/extension/eve-add.js +1 -1
- package/dist/src/self-modification/extension/extension.d.ts +46 -1
- package/dist/src/self-modification/extension/extension.js +1 -1
- package/dist/src/self-modification/extension/instructions.js +23 -9
- package/dist/src/self-modification/extension/production-registry-add.d.ts +42 -0
- package/dist/src/self-modification/extension/production-registry-add.js +1 -0
- package/dist/src/self-modification/extension/tools/edit_file.js +1 -1
- package/dist/src/self-modification/extension/tools/publish.d.ts +7 -0
- package/dist/src/self-modification/extension/tools/publish.js +1 -0
- package/dist/src/self-modification/extension/tools/registry_add.d.ts +39 -7
- package/dist/src/self-modification/extension/tools/registry_add.js +1 -1
- package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -0
- package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
- package/dist/src/self-modification/filesystem.js +1 -1
- package/dist/src/self-modification/git-workspace.d.ts +31 -0
- package/dist/src/self-modification/git-workspace.js +1 -0
- package/dist/src/self-modification/git.d.ts +6 -0
- package/dist/src/self-modification/git.js +1 -0
- package/dist/src/self-modification/github-publisher.d.ts +27 -0
- package/dist/src/self-modification/github-publisher.js +2 -0
- package/dist/src/self-modification/identifiers.d.ts +4 -0
- package/dist/src/self-modification/identifiers.js +1 -0
- package/dist/src/self-modification/mode.d.ts +4 -0
- package/dist/src/self-modification/mode.js +1 -0
- package/dist/src/self-modification/network-policy.d.ts +1 -0
- package/dist/src/self-modification/network-policy.js +1 -0
- package/dist/src/self-modification/proposal.d.ts +39 -0
- package/dist/src/self-modification/proposal.js +2 -0
- package/dist/src/self-modification/sandbox.d.ts +25 -1
- package/dist/src/self-modification/sandbox.js +1 -1
- package/dist/src/self-modification/setup.d.ts +34 -0
- package/dist/src/self-modification/setup.js +22 -0
- package/dist/src/self-modification/workspace-lock.d.ts +2 -0
- package/dist/src/self-modification/workspace-lock.js +1 -0
- package/dist/src/setup/integrations/registry.js +1 -1
- package/dist/src/setup/integrations/runner.js +1 -1
- package/dist/src/setup/integrations/self-modification/setup.d.ts +29 -0
- package/dist/src/setup/integrations/self-modification/setup.js +1 -0
- package/dist/src/setup/integrations/types.d.ts +2 -0
- package/dist/src/setup/integrations/types.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/empty-delivery.js +1 -1
- package/dist/src/shared/git.d.ts +16 -0
- package/dist/src/shared/git.js +1 -0
- package/dist/src/shared/shell-quote.d.ts +2 -0
- package/dist/src/shared/shell-quote.js +1 -0
- package/dist/src/shared/vercel-services.js +1 -1
- package/dist/src/tasks/session-index.d.ts +1 -1
- package/dist/src/tasks/session-index.js +1 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +10 -0
- package/dist/src/tasks/session-task-cohorts.js +1 -0
- package/dist/src/tools/workflow-definition.d.ts +5 -2
- package/docs/concepts/sessions-runs-and-streaming.md +2 -0
- package/docs/evals/reporters.mdx +20 -1
- package/docs/sandbox.mdx +2 -0
- package/docs/subagents/index.mdx +10 -0
- package/docs/tools/workflows.mdx +61 -2
- package/package.json +17 -1
- package/dist/src/self-modification/extension/source-lock.d.ts +0 -2
- package/dist/src/self-modification/extension/source-lock.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{parseJsonValue}from"#shared/json.js";import{
|
|
1
|
+
import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{parseJsonValue}from"#shared/json.js";import{normalizeApproval}from"#internal/authored-definition/approval.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";const KNOWN_TOP_LEVEL_KEYS=[`approval`,`auth`,`description`,`headers`,`instanceKey`,`toolCall`,`tools`,`url`],KNOWN_OPENAPI_TOP_LEVEL_KEYS=[`approval`,`auth`,`baseUrl`,`description`,`headers`,`instanceKey`,`operations`,`spec`,`toolCall`],KNOWN_AUTHORIZATION_KEYS=[`completeAuthorization`,`evict`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`],KNOWN_TOOL_CALL_KEYS=[`providedArguments`];function normalizeMcpClientConnectionDefinition(e,t){let n=expectObjectRecord(e,t);expectOnlyKnownKeys(n,KNOWN_TOP_LEVEL_KEYS,t),validateUrl(n,t),validateDescription(n,t),validateInstanceKey(n,t);let r=normalizeAuthorization(n,t),i=normalizeHeaders(n,t),a=normalizeConnectionToolCall(n,t),o=normalizeToolFilter(n,t);if(r!==void 0&&i!==void 0&&typeof i!=`function`&&Object.keys(i).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let s={description:n.description,url:n.url};return n.instanceKey!==void 0&&(s.instanceKey=n.instanceKey),r!==void 0&&(s.auth=r),i!==void 0&&(s.headers=i),a!==void 0&&(s.toolCall=a),o!==void 0&&(s.tools=o),n.approval!==void 0&&(s.approval=normalizeApproval(n.approval,t)),s}function normalizeConnectionToolCall(e,t){if(e.toolCall===void 0)return;let n=expectObjectRecord(e.toolCall,`${t} The "toolCall" field must be a plain object.`);if(expectOnlyKnownKeys(n,KNOWN_TOOL_CALL_KEYS,`${t} The "toolCall" field`),n.providedArguments===void 0)return{};let r=expectObjectRecord(n.providedArguments,`${t} The "toolCall.providedArguments" field must be a plain object.`);for(let[e,n]of Object.entries(r))if(typeof n!=`function`&&!(typeof n==`object`&&n&&typeof n.then==`function`))try{parseJsonValue(n)}catch{throw Error(`${t} The "toolCall.providedArguments.${e}" value must be JSON-serializable, a Promise, or a function.`)}return{providedArguments:r}}function normalizeOpenApiConnectionDefinition(e,t){let n=expectObjectRecord(e,t);expectOnlyKnownKeys(n,KNOWN_OPENAPI_TOP_LEVEL_KEYS,t),validateSpec(n,t),validateBaseUrl(n,t),validateDescription(n,t),validateInstanceKey(n,t);let r=normalizeAuthorization(n,t),i=normalizeHeaders(n,t),a=normalizeFilterField(n,`operations`,t),o=normalizeConnectionToolCall(n,t);if(r!==void 0&&i!==void 0&&typeof i!=`function`&&Object.keys(i).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let s={description:n.description,spec:n.spec};return n.baseUrl!==void 0&&(s.baseUrl=n.baseUrl),n.instanceKey!==void 0&&(s.instanceKey=n.instanceKey),r!==void 0&&(s.auth=r),i!==void 0&&(s.headers=i),o!==void 0&&(s.toolCall=o),a!==void 0&&(s.operations=a),n.approval!==void 0&&(s.approval=normalizeApproval(n.approval,t)),s}function validateSpec(e,t){let n=e.spec;if(typeof n==`string`){if(!URL.canParse(n))throw Error(`${t} The "spec" field must be a valid URL when provided as a string.`);let e=new URL(n);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`${t} The "spec" URL must use the http or https protocol, got "${e.protocol}".`);return}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`${t} The "spec" field must be a URL string or an inline OpenAPI document object.`)}function validateBaseUrl(e,t){if(e.baseUrl===void 0)return;if(typeof e.baseUrl!=`string`||!URL.canParse(e.baseUrl))throw Error(`${t} The "baseUrl" field must be a valid URL when provided.`);let n=new URL(e.baseUrl);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "baseUrl" field must use the http or https protocol, got "${n.protocol}".`)}function validateUrl(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function validateDescription(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function validateInstanceKey(e,t){if(e.instanceKey!==void 0&&(typeof e.instanceKey!=`string`||e.instanceKey.length===0))throw Error(`${t} The "instanceKey" field must be a non-empty string.`)}function normalizeAuthorization(e,t){if(e.auth===void 0)return;if(typeof e.auth==`function`)return e.auth;let n=expectObjectRecord(e.auth,`${t} The "auth" field must be an object with a "getToken" method or a function.`);return expectOnlyKnownKeys(n,KNOWN_AUTHORIZATION_KEYS,`${t} The "auth" field`),normalizeAuthorizationSpec(n,t)}function normalizeHeaders(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function normalizeToolFilter(e,t){return normalizeFilterField(e,`tools`,t)}function normalizeFilterField(e,t,n){let r=e[t];if(r===void 0)return;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);let i=r,a=`allow`in i,o=`block`in i;if(a&&o)throw Error(`${n} The "${t}" field must specify either "allow" or "block", not both.`);if(!a&&!o)throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);return a?(validateStringArray(i.allow,`${n} The "${t}.allow"`),{allow:i.allow}):(validateStringArray(i.block,`${n} The "${t}.block"`),{block:i.block})}function validateStringArray(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}export{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isBuiltin}from"node:module";import{dirname,join,resolve,sep}from"node:path";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync,readFileSync,realpathSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const CACHED_CHANNEL_PREFIX=`eve-cached-channel:`,RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(isPackageImport(t)){if(isFrameworkRuntimeImport(t,n))return{external:!0,id:resolveFrameworkRuntimeImport(t)};if(await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t})!==void 0)return{external:!0,id:t}}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:resolveFrameworkRuntimeImport(n)};let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:normalizeEsmImportSpecifier(e)}}let o=r===void 0||r.startsWith(`\0`)||r.startsWith(`eve-cached-channel:`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=
|
|
1
|
+
import{createRequire,isBuiltin}from"node:module";import{dirname,join,resolve,sep}from"node:path";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync,readFileSync,realpathSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const CACHED_CHANNEL_PREFIX=`eve-cached-channel:`,RESOLVE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`];function createGenerationPackageBoundaryPlugin(e){return{name:`eve-generation-package-boundary`,async resolveId(t,n,r){if(isPackageImport(t)){if(isFrameworkRuntimeImport(t,n))return{external:!0,id:resolveFrameworkRuntimeImport(t)};if(t.startsWith(`#`)){let r=resolvePackageImport(t,n,e.packageRoot);if(r!==void 0)return{id:r}}if(await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:n,kind:r.kind,packageRoot:e.packageRoot,source:t})!==void 0)return{external:!0,id:t}}}}}function createRuntimeLoaderPackageBoundaryPlugin(e){let t=toCanonicalPath(e.packageRoot);return{name:`eve-runtime-loader-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(isFrameworkRuntimeImport(n,r))return{external:!0,id:resolveFrameworkRuntimeImport(n)};if(n.startsWith(`#`)){let t=resolvePackageImport(n,r,e.packageRoot);if(t!==void 0)return{id:t}}let a=await resolveConfiguredExternalModule.call(this,{externalDependencies:e.externalDependencies,importer:r,kind:i.kind,packageRoot:e.packageRoot,source:n});if(a!==void 0){let e=resolveExistingExternalFilePath(a.resolvedId)??a.resolvedId;return{external:!0,id:normalizeEsmImportSpecifier(e)}}let o=r===void 0||r.startsWith(`\0`)||r.startsWith(`eve-cached-channel:`)?void 0:resolve(r);if(o!==void 0&&isPathInsideOrEqual(toCanonicalPath(o),t)){let e=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(e===null||typeof e.id!=`string`)throw Error(`Cannot resolve package "${n}" imported from "${o}". Install it with your package manager (e.g. \`pnpm install\`); a running \`eve dev\` retries on the next rebuild.`);if(isNodeModulesPath(e.id))return{external:!0,id:n}}}}}function createDistributionPackageBoundaryPlugin(e){let t=new Set(e.runtimeDependencies);return{name:`eve-extension-distribution-package-boundary`,async resolveId(n,r,i){if(!isPackageImport(n))return;if(n.startsWith(`#`)){let a=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(a!==null&&typeof a.id==`string`&&!isPathInsideOrEqual(toCanonicalPath(a.id),toCanonicalPath(e.packageRoot))){let e=nearestPackageName(a.id);if(e!==void 0&&!t.has(e))throw Error(`Package import "${n}" resolves to undeclared package "${e}". Add "${e}" to dependencies, optionalDependencies, or peerDependencies.`)}return}if(isBuiltin(n))return{external:!0,id:n};let a=packageImportName(n);if(!t.has(a))throw Error(`Package "${n}" is not declared by the extension. Add "${a}" to dependencies, optionalDependencies, or peerDependencies.`);let o=await this.resolve(n,r,{kind:i.kind,skipSelf:!0});if(o===null&&(o=await this.resolve(n,join(e.packageRoot,`package.json`),{kind:i.kind,skipSelf:!0})),o===null||typeof o.id!=`string`)throw Error(`Cannot resolve declared package "${n}". Install the extension's dependencies before building.`);return{external:!0,id:n}}}}async function resolveConfiguredExternalModule(e){let t=resolveConfiguredExternalDependency(e.source,e.externalDependencies);if(t===void 0)return;let n=await this.resolve(e.source,e.importer,{kind:e.kind,skipSelf:!0});if(n===null&&(n=await this.resolve(e.source,join(e.packageRoot,`package.json`),{kind:e.kind,skipSelf:!0})),n===null||typeof n.id!=`string`)throw Error(`Cannot resolve external package "${e.source}".`);return{packageName:t,resolvedId:n.id}}function normalizeExternalDependencies(e=[]){return[...new Set(e)].sort()}function resolveConfiguredExternalDependency(e,t){return t.find(t=>e===t||e.startsWith(`${t}/`))}function packageImportName(e){return e.startsWith(`@`)?e.split(`/`,2).join(`/`):e.split(`/`,1)[0]}function nearestPackageName(e){let t=nearestPackageRoot(e);if(t!==void 0)try{let e=JSON.parse(readFileSync(join(t,`package.json`),`utf8`));return typeof e.name==`string`&&e.name.length>0?e.name:void 0}catch{return}}function nearestPackageRoot(e){let t=dirname(toCanonicalPath(e));for(;;){if(existsSync(join(t,`package.json`)))return t;let e=dirname(t);if(e===t)return;t=e}}function resolvePackageImport(e,t,n){let r=t===void 0||t.startsWith(`\0`)?n:nearestPackageRoot(t)??n;try{let t=createRequire(join(r,`package.json`)).resolve(e);return isPathInsideOrEqual(toCanonicalPath(t),toCanonicalPath(r))?t:void 0}catch{return}}function resolveExistingExternalFilePath(e){if(existsSync(e))return e;for(let t of RESOLVE_EXTENSIONS){let n=`${e}${t}`;if(existsSync(n))return n}}function isPackageImport(e){return isPathImport(e)||/^(?:node|data|file):/.test(e)||e.startsWith(`@/`)?!1:!e.startsWith(CACHED_CHANNEL_PREFIX)}function isPathImport(e){return e.startsWith(`.`)||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function isFrameworkRuntimeImport(e,t){return e===`eve`||e.startsWith(`eve/`)?!0:e===`workflow`||e.startsWith(`workflow/`)||e.startsWith(`@workflow/`)?t===void 0||!isNodeModulesPath(t):!1}function resolveFrameworkRuntimeImport(e){return e===`eve`||e.startsWith(`eve/`)?e:normalizeEsmImportSpecifier(resolveWorkflowModulePath(e))}function isNodeModulesPath(e){return e.replaceAll(`\\`,`/`).includes(`/node_modules/`)}function toCanonicalPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{CACHED_CHANNEL_PREFIX,RESOLVE_EXTENSIONS,createDistributionPackageBoundaryPlugin,createGenerationPackageBoundaryPlugin,createRuntimeLoaderPackageBoundaryPlugin,isNodeModulesPath,isPathImport,normalizeExternalDependencies};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { shellQuote } from "#shared/shell-quote.js";
|
|
1
2
|
/** Quote one argument for Vercel's POSIX build-command shell. */
|
|
2
|
-
export declare
|
|
3
|
+
export declare const quoteVercelShellArgument: typeof shellQuote;
|
|
3
4
|
/** Return a portable relative path for a generated Vercel configuration. */
|
|
4
5
|
export declare function toVercelRelativePath(from: string, to: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{relative}from"node:path";
|
|
1
|
+
import{relative}from"node:path";import{shellQuote}from"#shared/shell-quote.js";const quoteVercelShellArgument=shellQuote;function toVercelRelativePath(e,t){return relative(e,t).replaceAll(`\\`,`/`)||`.`}export{quoteVercelShellArgument,toVercelRelativePath};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{builtinModules}from"node:module";import{mkdir,readFile,readdir}from"node:fs/promises";import{dirname,extname,join,relative,resolve}from"node:path";import{resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_SOURCE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`];function isWorkflowSourceFile(e){return WORKFLOW_SOURCE_EXTENSIONS.includes(extname(e))}const IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}r.isFile()&&isWorkflowSourceFile(r.name)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(e===`workflow`||e.startsWith(`workflow/`))return resolveWorkflowModulePath(e)}}}function createWorkflowDriverAliasPlugin(e){return{name:`eve-workflow-driver-aliases`,resolveId(t,n){if(t===`workflow/errors`)return resolveWorkflowModulePath(t);if(t===`workflow/api`||t===`workflow/runtime`){let e=n?` (imported by "${n}")`:``;throw Error(`Workflow bundle cannot import "${t}"${e}: the runtime API is not available inside a workflow body. Call it from a "use step" function and await that step from the body.`)}if(t===`workflow`)return resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)])}}}function createEvePackageImportsPlugin(e,t={}){return{name:`eve-package-imports`,resolveId(
|
|
1
|
+
import{builtinModules}from"node:module";import{mkdir,readFile,readdir}from"node:fs/promises";import{dirname,extname,join,relative,resolve}from"node:path";import{resolvePackageRoot,resolveWorkflowModulePath}from"#internal/application/package.js";import{existsSync}from"node:fs";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{atomicWriteFile}from"#shared/atomic-write-file.js";import{buildSingleRolldownChunk}from"#internal/bundler/nitro-rolldown.js";import{applyWorkflowTransform,getImportPath}from"#internal/workflow-bundle/workflow-builders.js";import{WORKFLOW_STEP_EXTERNAL_PACKAGES}from"#internal/workflow-bundle/vercel-workflow-output.js";const WORKFLOW_VIRTUAL_ENTRY_ID=`\0eve-workflow-entry`,PSEUDO_PACKAGES=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]),NODE_BUILTIN_MODULES=new Set([...builtinModules,...builtinModules.map(e=>`node:${e}`)]),WORKFLOW_SOURCE_EXTENSIONS=[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`];function isWorkflowSourceFile(e){return WORKFLOW_SOURCE_EXTENSIONS.includes(extname(e))}const IGNORED_INPUT_DIRECTORIES=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function collectWorkflowInputFiles(e){let t=[];async function visit(e){let n;try{n=await readdir(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let r of n){if(r.isDirectory()){IGNORED_INPUT_DIRECTORIES.has(r.name)||await visit(join(e,r.name));continue}r.isFile()&&isWorkflowSourceFile(r.name)&&t.push(join(e,r.name))}}return await visit(e),t}function createWorkflowImport(e,t){let{importPath:n,isPackage:r}=getImportPath(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(toRelativeImportSpecifier(t,e))};`}function createWorkflowVirtualEntryPlugin(e){return{name:`eve-workflow-virtual-entry`,resolveId(e){if(e===`\0eve-workflow-entry`)return{id:e}},load(t){if(t===`\0eve-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function createWorkflowPseudoPackagePlugin(){return{name:`eve-workflow-pseudo-packages`,resolveId(e){if(PSEUDO_PACKAGES.has(e))return{id:`\0eve-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0eve-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function createWorkflowRuntimeAliasPlugin(){return{name:`eve-workflow-runtime-aliases`,resolveId(e){if(e===`workflow`||e.startsWith(`workflow/`))return resolveWorkflowModulePath(e)}}}function createWorkflowDriverAliasPlugin(e){return{name:`eve-workflow-driver-aliases`,resolveId(t,n){if(t===`workflow/errors`)return resolveWorkflowModulePath(t);if(t===`workflow/api`||t===`workflow/runtime`){let e=n?` (imported by "${n}")`:``;throw Error(`Workflow bundle cannot import "${t}"${e}: the runtime API is not available inside a workflow body. Call it from a "use step" function and await that step from the body.`)}if(t===`workflow`)return resolveFirstExistingPath([join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)])}}}function createEvePackageImportsPlugin(e,t={}){let n=[...new Set([e,resolvePackageRoot()])];return{name:`eve-package-imports`,resolveId(e){let r=e.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?resolveFirstExistingPath(n.flatMap(e=>[join(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),join(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)])):resolveFirstExistingPath(n.flatMap(e=>[join(e,`.generated`,`compiled`,r),join(e,`dist`,`src`,`compiled`,r)]));let i=e.match(/^#(.+)\.js$/)?.[1];if(i!==void 0)return resolveFirstExistingPath(n.flatMap(e=>WORKFLOW_SOURCE_EXTENSIONS.flatMap(t=>[join(e,`src`,`${i}${t}`),join(e,`dist`,`src`,`${i}${t}`)])))}}}function createWorkflowTransformPlugin(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`eve-workflow-transform`,async load(n){if(!isJavaScriptLikePath(n))return;let r=await readFile(n,`utf8`),i=createManifestRelativeFilepath(e.workingDir,n),a=await applyWorkflowTransform(i,r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return mergeWorkflowManifest(e.manifest,a.workflowManifest),{code:a.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function bundleWorkflowStepRegistrations(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i={},a=[createWorkflowImport(e.builtinsPath,e.workingDir),...t.map(t=>createWorkflowImport(t,e.workingDir)),...r.map(t=>createWorkflowImport(t,e.workingDir)),`export const __steps_registered = true;`].join(`
|
|
2
2
|
`),o=await buildSingleRolldownChunk(`step registrations bundle for "${e.outfile}"`,{cwd:e.workingDir,input:WORKFLOW_VIRTUAL_ENTRY_ID,external:isWorkflowStepExternalPackage,platform:`node`,plugins:[createWorkflowVirtualEntryPlugin(a),createWorkflowPseudoPackagePlugin(),createWorkflowRuntimeAliasPlugin(),createEvePackageImportsPlugin(e.workingDir),createWorkflowTransformPlugin({manifest:i,mode:`step`,projectRoot:e.projectRoot,sideEffectFiles:[...t,...r],workingDir:e.workingDir})],resolve:{conditionNames:[`eve-source`],extensions:WORKFLOW_SOURCE_EXTENSIONS,mainFields:[`module`,`main`]},tsconfig:e.tsconfigPath??!1,output:{comments:!1,format:`esm`,sourcemap:`inline`}});await writeWorkflowBundleAtomically(e.outfile,o.code)}function isWorkflowStepExternalPackage(e){return WORKFLOW_STEP_EXTERNAL_PACKAGES.some(t=>e===t||e.startsWith(`${t}/`))}function createWorkflowNodeBuiltinGuardPlugin(){return{name:`eve-workflow-node-builtins`,resolveId(e,t){let n=e.startsWith(`node:`)?e.slice(5):e;if(!NODE_BUILTIN_MODULES.has(e)&&!NODE_BUILTIN_MODULES.has(n))return;let r=t?` (imported by "${t}")`:``;throw Error(`Workflow bundle cannot import Node.js builtin "${e}"${r}. Move Node.js APIs behind a "use step" function, or keep the importing module out of the workflow driver body (only reachable through a "use step").`)}}}async function bundleFinalWorkflowOutput(e){let t=createWorkflowEntrypointSource({code:e.code,queueNamespace:e.queueNamespace,stepRegistrationsImport:e.stepRegistrationsPath===void 0?void 0:toRelativeImportSpecifier(dirname(e.outfile),e.stepRegistrationsPath)});await writeWorkflowBundleAtomically(e.outfile,t)}const WORKFLOW_REGISTRY_BANNER=`globalThis.${WORKFLOW_REGISTRY_GLOBAL} = new Map();`;function composeWorkflowDriverCode(e){let t=e.map(e=>e.trim()).filter(e=>e.length>0).map(e=>`(function () {\n${e}\n})();`);return[WORKFLOW_REGISTRY_BANNER,...t].join(`
|
|
3
3
|
`)}function createWorkflowEntrypointSource(e){let t=normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)),n=Buffer.from(e.code.endsWith(`
|
|
4
4
|
`)?e.code:`${e.code}\n`,`utf8`).toString(`base64`).match(/.{1,16384}/gu)??[``],r=e.stepRegistrationsImport===void 0?``:`import { __steps_registered as __eveWorkflowStepsRegistered } from ${JSON.stringify(e.stepRegistrationsImport)};\nvoid __eveWorkflowStepsRegistered;`;return`// Generated by eve. Do not edit by hand.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{STABLE_WORKFLOW_NAMES}from"#execution/stable-workflow-names.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}from"#runtime/subagents/workflow-reference.js";import{findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives}from"#internal/workflow-bundle/workflow-transformer.js";const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(e,t,n,r,i,a=new Set([...STABLE_WORKFLOW_NAMES,SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME])){let o=i??process.cwd(),
|
|
1
|
+
import{readFile}from"node:fs/promises";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{STABLE_WORKFLOW_NAMES}from"#execution/stable-workflow-names.js";import{prepareAuthoredWorkflowDirectives}from"#internal/workflow-bundle/authored-workflow-directives.js";import{SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}from"#runtime/subagents/workflow-reference.js";import{findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives}from"#internal/workflow-bundle/workflow-transformer.js";const packageJsonCache=new Map,projectDepsCache=new Map;async function applyWorkflowTransform(e,t,n,r,i,a=new Set([...STABLE_WORKFLOW_NAMES,SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME])){let o=i??process.cwd(),s=r===void 0?isAbsolute(e)?e:join(o,e):r,{moduleSpecifier:c,stableModuleSpecifier:l}=resolveModuleSpecifier(s,o,n===`metadata`);if(r!==void 0&&isAuthoredApplicationModule(r,o)){let e=n===!1?void 0:await prepareAuthoredWorkflowDirectives({filePath:r,source:t});return transformWorkflowDirectives({authored:!0,authorizeSteps:!0,filename:authoredRelativePath(r,o),mode:e?.hasDirectives===!0&&n,moduleSpecifier:authoredModuleIdBase(r,o),source:e?.source??t,stableModuleSpecifier:void 0,stableWorkflowNames:a})}return transformWorkflowDirectives({authorizeSteps:isPackageTestFixtureModule(s),filename:e,mode:n,moduleSpecifier:c,source:t,stableModuleSpecifier:l,stableWorkflowNames:a})}function isPackageTestFixtureModule(e){return e.replace(/\\/g,`/`).includes(`/src/internal/testing/`)}function isAuthoredApplicationModule(e,t){let n=toRealPath(t).replace(/\\/g,`/`).replace(/\/$/,``),r=toRealPath(e).replace(/\\/g,`/`);return!r.startsWith(`${n}/`)||isInNodeModules(r)?!1:findPackageJson(r)?.name!==EVE_PACKAGE_NAME}function authoredRelativePath(e,t){return toRelativeImportPath(toRealPath(e),toRealPath(t)).replace(/^\.\//,``)}function authoredModuleIdBase(e,t){return`./${stripJavaScriptExtension(authoredRelativePath(e,t))}`}function toRealPath(e){try{return realpathSync(e)}catch{return resolve(e)}}function isAuthoredApplicationRoot(e){let t=join(e,`package.json`);if(!existsSync(t))return!1;try{return JSON.parse(readFileSync(t,`utf8`)).name!==EVE_PACKAGE_NAME}catch{return!1}}async function findWorkflowPatterns(e,t){let n=await findWorkflowDirectiveFunctions(e,t);return{hasSerde:t.includes(`workflow.serde`)||t.includes(`@serde`)||t.includes(`workflowSerde`)||t.includes(`__workflow_serde`),hasUseStep:n.some(e=>e.directive===`use step`),hasUseWorkflow:n.some(e=>e.directive===`use workflow`)}}function getImportPath(e,t){let n=isInNodeModules(e),r=!n&&isWorkspacePackage(e,t);if(n||r){let n=findPackageJson(e);if(n!==null){let i=getProjectDependencies(t).has(n.name);if(!(r||i))return{importPath:toRelativeImportPath(e,t),isPackage:!1};let a=resolveExportSubpath(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:isRootEntrypointFile(e,n)?{importPath:n.name,isPackage:!0}:{importPath:toRelativeImportPath(e,t),isPackage:!1}}}return{importPath:toRelativeImportPath(e,t),isPackage:!1}}function resolveModuleSpecifier(e,t,n=!1){let r=isInNodeModules(e),i=!r&&isWorkspacePackage(e,t),a=findPackageJson(e);if(n&&a!==null)return{moduleSpecifier:`${a.name}@${a.version}`,stableModuleSpecifier:a.name};if(!r&&!i)return{moduleSpecifier:void 0,stableModuleSpecifier:a?.name===EVE_PACKAGE_NAME?EVE_PACKAGE_NAME:void 0};if(a===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let o=resolveExportSubpath(e,a),s=o?`${a.name}${o}`:a.name;return{moduleSpecifier:`${s}@${a.version}`,stableModuleSpecifier:s}}function findPackageJson(e){let t=dirname(e),n=[];for(;t!==dirname(t);){let e=packageJsonCache.get(t);if(e!==void 0){for(let t of n)packageJsonCache.set(t,e);return e}n.push(t);let r=join(t,`package.json`);if(existsSync(r))try{let e=JSON.parse(readFileSync(r,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let r={dir:t,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};packageJsonCache.set(t,r);for(let e of n)packageJsonCache.set(e,r);return r}}catch{}t=dirname(t)}for(let e of n)packageJsonCache.set(e,null);return null}function resolveExportSubpath(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=resolveExportTarget(n);if(t!==null&&normalizeExportPath(t)===i)return e===`.`?``:e.substring(1)}return``}function resolveExportTarget(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=resolveExportTarget(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=resolveExportTarget(n);if(r!==null)return r}return null}function normalizeExportPath(e){return e.startsWith(`./`)?e:`./${e}`}function isInNodeModules(e){return e.split(sep).join(`/`).includes(`/node_modules/`)}function getProjectDependencies(e){let t=projectDepsCache.get(e);if(t!==void 0)return t;let n=new Set,r=join(e,`package.json`);if(existsSync(r))try{let e=JSON.parse(readFileSync(r,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let r=e[t];if(typeof r==`object`&&r&&!Array.isArray(r))for(let e of Object.keys(r))n.add(e)}}catch{}return projectDepsCache.set(e,n),n}function isWorkspacePackage(e,t){if(isInNodeModules(e))return!1;let n=findPackageJson(e);return n===null||resolve(n.dir)===resolve(t)?!1:getProjectDependencies(t).has(n.name)}function toRelativeImportPath(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),i=r.startsWith(`${n}/`)?r.substring(n.length+1):relative(t,e).replace(/\\/g,`/`);return i.startsWith(`.`)||(i=`./${i}`),i}function hasRootExport(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function normalizePackageTargetPath(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function isRootEntrypointFile(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(hasRootExport(t.exports))e=t.exports;else return!1;let n=resolveExportTarget(e);return n!==null&&normalizePackageTargetPath(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[normalizePackageTargetPath(e)]:[]).includes(i)}async function readSourceFile(e){return await readFile(e,`utf8`)}export{applyWorkflowTransform,findWorkflowPatterns,getImportPath,isAuthoredApplicationModule,isAuthoredApplicationRoot,readSourceFile};
|
|
@@ -7,12 +7,10 @@ export declare function findWorkflowDirectiveFunctions(filename: string, source:
|
|
|
7
7
|
readonly name: string;
|
|
8
8
|
}[]>;
|
|
9
9
|
export declare function transformWorkflowDirectives(input: {
|
|
10
|
-
/**
|
|
11
|
-
* Authored modules keep their body in workflow mode (steps become proxies in
|
|
12
|
-
* place) and lose an eve-definer default export, so the driver never
|
|
13
|
-
* evaluates the tool definition or its schema dependencies.
|
|
14
|
-
*/
|
|
10
|
+
/** Authored modules retain their body but drop the eve-definer default export. */
|
|
15
11
|
authored?: boolean;
|
|
12
|
+
/** Route context-bearing calls through an authorization twin for modules that define tools. */
|
|
13
|
+
authorizeSteps?: boolean;
|
|
16
14
|
filename: string;
|
|
17
15
|
mode: WorkflowDirectiveMode;
|
|
18
16
|
moduleSpecifier: string | undefined;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const BUILTIN_STEP_NAMES=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`,`__builtin_set_attributes`]);async function findWorkflowDirectiveFunctions(e,t){return findDirectiveFunctions(await parseWorkflowSource(e,t)).map(e=>({directive:e.directive,name:e.name}))}async function transformWorkflowDirectives(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await parseWorkflowSource(e.filename,e.source),n=findDirectiveFunctions(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let
|
|
2
|
-
`)
|
|
3
|
-
`)}\n`:``}
|
|
1
|
+
import{WORKFLOW_REGISTRY_GLOBAL}from"#execution/workflow-registry.js";import{parseWithNitroRolldownAst}from"#internal/bundler/nitro-rolldown.js";import{readWorkflowDirective}from"#internal/workflow-bundle/workflow-directive-ast.js";const BUILTIN_STEP_NAMES=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`,`__builtin_set_attributes`]);async function findWorkflowDirectiveFunctions(e,t){return findDirectiveFunctions(await parseWorkflowSource(e,t)).map(e=>({directive:e.directive,name:e.name}))}async function transformWorkflowDirectives(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await parseWorkflowSource(e.filename,e.source),n=findDirectiveFunctions(t),r=e.authorizeSteps===!0,i=r&&n.some(e=>e.directive===`use step`&&!BUILTIN_STEP_NAMES.has(e.name));if(n.length===0)return{code:e.source,workflowManifest:{}};let a=e.moduleSpecifier??`./${stripJavaScriptExtension(e.filename)}`,o=e.stableModuleSpecifier??a,s={},c=[],l=[],u=!1,d=e.authored?`eve/internal/workflow-step-execution`:`#execution/tools/workflow/step-execution.js`;for(let t of n){if(t.directive===`use step`){let n=createStepId(a,t.name);s.steps??={};let i=s.steps[e.filename]??={};i[t.name]={stepId:n};let o=authorizationTwinId(a,t.name,r);if(o!==void 0&&(i[`${t.name}${AUTHORIZATION_STEP_SUFFIX}`]={stepId:o}),e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;c.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = ${createStepProxy(a,t.name,r)};`})}else if(e.mode===`metadata`)continue;else c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(u=!0,l.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`),o!==void 0&&l.push(`registerStepFunction(${JSON.stringify(o)}, withWorkflowStepAuthorization(${t.name}));`)):l.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=createWorkflowId(e.stableWorkflowNames?.has(t.name)===!0?o:a,t.name);s.workflows??={};let i=s.workflows[e.filename]??={};i[t.name]={workflowId:n},e.mode===`workflow`?(c.push({end:t.directiveEnd,start:t.directiveStart,text:``}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),l.push(`globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(n)}, ${t.name});`)):(e.mode===`metadata`||c.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),l.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let f=`/**__internal_workflows${JSON.stringify(s)}*/;`,p=[];u&&p.push(`import { registerStepFunction } from "workflow/internal/private";`),i&&e.mode===`workflow`?p.push(`import { workflowToolStep } from ${JSON.stringify(`#execution/tools/workflow/step.js`)};`):i&&u&&p.push(`import { withWorkflowStepAuthorization } from ${JSON.stringify(d)};`);let m=[...p,f].join(`
|
|
2
|
+
`),h=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!h&&e.authored!==!0)return{code:`${m}\n${createWorkflowStepProxySource(e.source,t,n,a,r)}`,workflowManifest:s};e.mode===`workflow`&&e.authored===!0&&c.push(...removeEveDefinerDefaultExport(t));let g=applySourceReplacements(e.source,c);return{code:`${m}\n${e.mode===`workflow`?await stripUnusedValueImports(e.filename,g):g}${l.length>0?`\n${l.join(`
|
|
3
|
+
`)}\n`:``}`,workflowManifest:s}}async function parseWorkflowSource(e,t){return await parseWithNitroRolldownAst(e,t)}function createWorkflowStepProxySource(e,t,n,r,i){let a=findExportedLiteralValueDeclarations(e,t),o=n.filter(e=>e.directive===`use step`).map(e=>`${e.exported?`export `:``}var ${e.name} = ${createStepProxy(r,e.name,i)};`),s=[...a,...o];return s.length>0?`${s.join(`
|
|
4
|
+
`)}\n`:``}const AUTHORIZATION_STEP_SUFFIX=`:eve-authorization`;function authorizationTwinId(e,t,n){if(n&&!BUILTIN_STEP_NAMES.has(t))return createStepId(e,`${t}${AUTHORIZATION_STEP_SUFFIX}`)}function createStepProxy(e,t,n){let useStep=e=>`globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(e)})`,r=useStep(createStepId(e,t)),i=authorizationTwinId(e,t,n);return i===void 0?r:`workflowToolStep(${r}, ${useStep(i)})`}function findDirectiveFunctions(e){let t=[],n=collectLocalNamesReExportedAtModuleLevel(e);for(let r of e.body??[]){let e=readTopLevelFunctionDeclaration(r);if(e===null)continue;let i=e.fn,a=i.id?.name,o=readBlockStatements(i.body);if(i.async!==!0||a===void 0||o===void 0)continue;let s=readFunctionDirective(o[0]);s!==null&&t.push({directive:s.value,directiveEnd:s.end,directiveStart:s.start,exportPrefix:e.exported?`export `:``,exported:e.exported||n.has(a),name:a,rangeEnd:e.end,rangeStart:e.start})}return t}function collectLocalNamesReExportedAtModuleLevel(e){let t=new Set;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&(n.source===void 0||n.source===null)&&(n.declaration===void 0||n.declaration===null))for(let e of n.specifiers??[]){let n=e.local?.name;n!==void 0&&t.add(n)}return t}function readTopLevelFunctionDeclaration(e){return e.type===`FunctionDeclaration`?readFunctionDeclarationRange(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:readFunctionDeclarationRange(e.declaration,!0,e)}function readFunctionDeclarationRange(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function readBlockStatements(e){return e===void 0||Array.isArray(e)?e:e.body}function readFunctionDirective(e){let t=readWorkflowDirective(e);return t===void 0||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function applySourceReplacements(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}function removeEveDefinerDefaultExport(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source?.value;if(typeof e==`string`&&/^eve(?:\/|$)/.test(e))for(let e of n.specifiers??[]){if(e.importKind===`type`)continue;let n=e.local?.name;n!==void 0&&t.add(n)}}let n=[];for(let r of e.body??[]){if(r.type!==`ExportDefaultDeclaration`||r.start===void 0)continue;let e=r.declaration;if(e?.type!==`CallExpression`||r.end===void 0)continue;let i=e.callee,a=i?.type===`MemberExpression`?i.object:i;a?.type===`Identifier`&&t.has(a.name??``)&&n.push({end:r.end,start:r.start,text:``})}return n}async function stripUnusedValueImports(e,t){let n=await parseWorkflowSource(e,t),r=collectReferencedIdentifiers(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=readValueImportBindings(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:extendRemovalEnd(t,e.end),start:e.start,text:``})}return i.length>0?applySourceReplacements(t,i):t}function findExportedLiteralValueDeclarations(e,t){let n=[],r=collectLocalReExportAliases(t);for(let i of t.body??[]){if(i.type===`ExportNamedDeclaration`&&i.declaration?.type===`VariableDeclaration`&&i.declaration.kind===`const`&&i.start!==void 0&&i.end!==void 0&&(i.declaration.declarations??[]).every(isLiteralValueDeclarator)){n.push(e.slice(i.start,i.end).trim());continue}if(i.type===`VariableDeclaration`&&(i.kind===`const`||i.kind===`var`||i.kind===`let`))for(let t of i.declarations??[]){if(!isLiteralValueDeclarator(t)||t.start===void 0||t.end===void 0)continue;let a=t.id?.name;if(a===void 0)continue;let o=r.get(a);if(o===void 0||o.length===0)continue;let s=e.slice(t.start,t.end).trim(),c=o.map(e=>e===a?a:`${a} as ${e}`);n.push(`${i.kind} ${s};\nexport { ${c.join(`, `)} };`)}}return n}function collectLocalReExportAliases(e){let t=new Map;for(let n of e.body??[])if(n.type===`ExportNamedDeclaration`&&(n.source===void 0||n.source===null)&&(n.declaration===void 0||n.declaration===null))for(let e of n.specifiers??[]){let n=e.local?.name,r=e.exported?.name??n;if(n!==void 0&&r!==void 0){let e=t.get(n)??[];e.push(r),t.set(n,e)}}return t}function isLiteralValueDeclarator(e){return isLiteralValueExpression(e.init)}function isLiteralValueExpression(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TemplateLiteral`&&(e.expressions??[]).length===0?!0:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?isLiteralValueExpression(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`&&typeof e.argument.value==`number`}function readValueImportBindings(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function collectReferencedIdentifiers(e){let t=new Set;return visitAstNode(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function visitAstNode(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)isAstNode(e)&&visitAstNode(e,t);else isAstNode(n)&&visitAstNode(n,t)}}function isAstNode(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function extendRemovalEnd(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
|
|
4
5
|
`?n+2:e[n]===`
|
|
5
6
|
`?n+1:n}function stripJavaScriptExtension(e){return e.replace(/\.(?:[cm]?[jt]sx?)$/,``)}function createWorkflowId(e,t){return`workflow//${e}//${t}`}function createStepId(e,t){return BUILTIN_STEP_NAMES.has(t)?t:`step//${e}//${t}`}export{createWorkflowId,findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveGitHubInstallationToken}from"#public/channels/github/auth.js";import{getGitHubPullRequest,getGitHubRepository}from"#public/channels/github/api.js";async function checkoutGitHubRepository(e,t){let n=await resolveCheckoutDescriptor(t),r=e.resolvePath(t.path??`/workspace`),i=resolveCheckoutRef(t.ref,n);if(
|
|
1
|
+
import{shellQuote}from"#shared/shell-quote.js";import{resolveGitHubInstallationToken}from"#public/channels/github/auth.js";import{getGitHubPullRequest,getGitHubRepository}from"#public/channels/github/api.js";import{gitHubGitBrokerNetworkPolicy,gitHubRemoteUrl,isFullGitSha}from"#shared/git.js";async function checkoutGitHubRepository(e,t){let n=await resolveCheckoutDescriptor(t),r=e.resolvePath(t.path??`/workspace`),i=resolveCheckoutRef(t.ref,n);if(isFullGitSha(i)){let t=await readCheckoutHead(e,r);if(t===i)return{baseRef:n.baseRef,path:r,ref:i,sha:t}}let a=normalizeCheckoutDepth(t.depth),o=t.mode===`full`?``:` --depth ${a}`,s=await resolveGitHubInstallationToken({api:t.api,credentials:t.credentials,installationId:n.installationId}),c=gitHubRemoteUrl({owner:n.owner,repo:n.repo}),l=isFullGitSha(i)?i:`FETCH_HEAD`;await e.setNetworkPolicy(gitHubGitBrokerNetworkPolicy(s)),await runCheckoutCommand({command:`mkdir -p ${shellQuote(r)}`,label:`create checkout directory`,sandbox:e}),await runCheckoutCommand({command:`cd ${shellQuote(r)} && git init`,label:`initialize git repository`,sandbox:e}),await runCheckoutCommand({command:`cd ${shellQuote(r)} && git remote remove origin >/dev/null 2>&1 || true`,label:`reset git remote`,sandbox:e}),await runCheckoutCommand({command:`cd ${shellQuote(r)} && git remote add origin ${shellQuote(c)}`,label:`configure git remote`,sandbox:e}),await runCheckoutCommand({command:`cd ${shellQuote(r)} && GIT_TERMINAL_PROMPT=0 git fetch${o} origin ${shellQuote(i)}`,label:`fetch GitHub ref`,sandbox:e}),await runCheckoutCommand({command:`cd ${shellQuote(r)} && git checkout --detach ${shellQuote(l)}`,label:`checkout GitHub ref`,sandbox:e}),t.includeBase===!0&&n.baseSha!==null&&await runCheckoutCommand({command:`cd ${shellQuote(r)} && GIT_TERMINAL_PROMPT=0 git fetch${o} origin ${shellQuote(n.baseSha)}`,label:`fetch GitHub base ref`,sandbox:e});let u=(await runCheckoutCommand({command:`cd ${shellQuote(r)} && git rev-parse HEAD`,label:`resolve checked out commit`,sandbox:e})).stdout.trim()||n.headSha||i;return{baseRef:n.baseRef,path:r,ref:i,sha:u}}async function resolveCheckoutDescriptor(e){let t=readNonEmptyString(e.owner),n=readNonEmptyString(e.repo);if(t===void 0||n===void 0)throw Error(`GitHub checkout requires a repository owner and name.`);if(e.installationId===void 0||e.installationId===null)throw Error(`GitHub checkout requires a GitHub App installation id.`);let r=e.pullRequestNumber??null,i=readNonEmptyString(e.ref),a=null;r!==null&&(i===void 0&&((e.headSha===void 0||e.headSha===null)&&(e.headRef===void 0||e.headRef===null)||e.defaultBranch===void 0||e.defaultBranch===null)||e.includeBase===!0&&(e.baseSha===void 0||e.baseSha===null)||e.includeBase===!0&&(e.baseRef===void 0||e.baseRef===null))&&(a=await getGitHubPullRequest({api:e.api,credentials:e.credentials,installationId:e.installationId,owner:t,pullRequestNumber:r,repo:n}));let o=readNonEmptyString(e.defaultBranch)??a?.defaultBranch??await resolveRepositoryDefaultBranch(e,{owner:t,pullRequestNumber:r,repo:n});return{baseRef:e.baseRef??a?.base.ref??null,baseSha:e.baseSha??a?.base.sha??null,defaultBranch:o,headRef:e.headRef??a?.head.ref??null,headSha:e.headSha??a?.head.sha??null,installationId:e.installationId,owner:t,pullRequestNumber:r,repo:n}}async function resolveRepositoryDefaultBranch(e,t){return t.pullRequestNumber!==null||readNonEmptyString(e.ref)!==void 0||readNonEmptyString(e.headSha)!==void 0||readNonEmptyString(e.headRef)!==void 0?null:(await getGitHubRepository({api:e.api,credentials:e.credentials,installationId:e.installationId??void 0,owner:t.owner,repo:t.repo})).defaultBranch??null}function resolveCheckoutRef(e,t){if(e!==void 0&&e.trim().length>0)return e.trim();if(t.headSha!==null)return t.headSha;if(t.pullRequestNumber!==null)return`refs/pull/${t.pullRequestNumber}/head`;if(t.headRef!==null)return t.headRef;if(t.defaultBranch!==null)return t.defaultBranch;throw Error(`GitHub checkout could not resolve a ref to fetch.`)}async function readCheckoutHead(e,t){let n=await e.run({command:`cd ${shellQuote(t)} && git rev-parse HEAD 2>/dev/null`});if(n.exitCode!==0)return null;let r=String(n.stdout??``).trim();return isFullGitSha(r)?r:null}async function runCheckoutCommand(e){let t=await e.sandbox.run({command:e.command}),n=String(t.stderr??``),r=String(t.stdout??``);if(t.exitCode===0)return{stderr:n,stdout:r};throw Error([`GitHub checkout failed during ${e.label} (exit ${t.exitCode}).`,n?`stderr: ${n}`:void 0,r?`stdout: ${r}`:void 0,`Verify the GitHub App installation has access to this repository.`].filter(e=>e!==void 0).join(` `))}function normalizeCheckoutDepth(e){if(e===void 0)return 1;if(!Number.isFinite(e)||e<1)throw Error(`GitHub checkout depth must be a positive number.`);return Math.floor(e)}function readNonEmptyString(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}export{checkoutGitHubRepository};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{callSlackApi}from"#public/channels/slack/api.js";import{SLACK_ACTIVITY_PLAN_RENDERER_ID,createSlackPlanRenderer}from"#public/channels/slack/activity-plan.js";import{truncateTypingStatus}from"#public/channels/slack/limits.js";const SLACK_ACTIVITY_STATUS_RENDERER_ID=`slack.status.v1`,SLACK_ACTIVITY_MESSAGE_RENDERER_ID=`slack.experimental.tree.v1`,SLACK_ACTIVITY_RENDERER=Symbol(`eve.slack.activity-renderer`);function experimental_slackActivityStatus(){return{[SLACK_ACTIVITY_RENDERER]:!0,id:SLACK_ACTIVITY_STATUS_RENDERER_ID}}function experimental_slackActivityTree(){return{[SLACK_ACTIVITY_RENDERER]:!0,id:SLACK_ACTIVITY_MESSAGE_RENDERER_ID}}function experimental_slackActivityPlan(){return{[SLACK_ACTIVITY_RENDERER]:!0,id:SLACK_ACTIVITY_PLAN_RENDERER_ID}}function experimental_slackActivityRenderer(e){return validateCustomSlackActivityRenderer(e),{[SLACK_ACTIVITY_RENDERER]:!0,id:e.id,render:e.render,dispose:e.dispose}}function hasSlackActivityStatus(e){return e?.some(e=>e.id===SLACK_ACTIVITY_STATUS_RENDERER_ID)===!0}function buildSlackActivityRenderers(e){let t=new Set;return e.renderers.map(n=>{if(n[SLACK_ACTIVITY_RENDERER]!==!0)throw TypeError(`Slack activity renderers must be created by an eve renderer factory.`);if(t.has(n.id))throw TypeError(`Duplicate Slack activity renderer "${n.id}".`);return t.add(n.id),n.id===SLACK_ACTIVITY_MESSAGE_RENDERER_ID?createSlackActivityRenderer(e.botToken):n.id===SLACK_ACTIVITY_PLAN_RENDERER_ID?createSlackPlanRenderer(e.botToken):n.id===SLACK_ACTIVITY_STATUS_RENDERER_ID?createSlackStatusRenderer(e.botToken):(assertCustomSlackActivityRenderer(n),createCustomSlackActivityRenderer(n))})}function assertCustomSlackActivityRenderer(e){validateCustomSlackActivityRenderer(e)}function validateCustomSlackActivityRenderer(e){if(typeof e!=`object`||!e||!(`id`in e)||typeof e.id!=`string`||e.id.trim()===``)throw TypeError(`Slack activity renderer ids must be non-empty strings.`);if(e.id===SLACK_ACTIVITY_STATUS_RENDERER_ID||e.id===SLACK_ACTIVITY_MESSAGE_RENDERER_ID||e.id===SLACK_ACTIVITY_PLAN_RENDERER_ID)throw TypeError(`Slack activity renderer id "${e.id}" is reserved by eve.`);if(!(`render`in e)||typeof e.render!=`function`)throw TypeError(`Custom Slack activity renderers must define a render function.`);if(`dispose`in e&&e.dispose!==void 0&&typeof e.dispose!=`function`)throw TypeError(`Custom Slack activity renderer dispose must be a function.`)}function createCustomSlackActivityRenderer(e){return{id:e.id,async render({destination:t,snapshot:n,state:r}){return e.render({destination:experimentalSlackActivityDestination(t),snapshot:n,state:r})},async dispose({destination:t,state:n}){await e.dispose?.({destination:experimentalSlackActivityDestination(t),state:n})}}}function experimentalSlackActivityDestination(e){return{channelId:typeof e.channelId==`string`?e.channelId:null,installationTeamId:typeof e.installationTeamId==`string`?e.installationTeamId:null,teamId:typeof e.teamId==`string`?e.teamId:null,threadTs:typeof e.threadTs==`string`?e.threadTs:null,triggeringUserId:typeof e.triggeringUserId==`string`?e.triggeringUserId:null}}function createSlackStatusRenderer(e){return{id:SLACK_ACTIVITY_STATUS_RENDERER_ID,async dispose({destination:t,state:n}){if(!isSlackStatusState(n)||n.status===``)return;let r=t.channelId,i=t.installationTeamId,a=t.threadTs;if(typeof r!=`string`||typeof a!=`string`||a===``)return;let o=await callSlackApi({body:{channel_id:r,status:``,thread_ts:a},botToken:e,context:{teamId:typeof i==`string`?i:void 0},operation:`assistant.threads.setStatus`});if(o.ok!==!0)throw Error(`Slack status disposal failed: ${o.error??`unknown_error`}`)},async render({destination:t,snapshot:n,state:r}){let i=t.channelId,a=t.installationTeamId,o=t.threadTs;if(typeof i!=`string`||typeof o!=`string`||o===``)return r;let s=selectSlackActivityStatus(n);if(isSlackStatusState(r)&&r.status===s)return r;let c={channel_id:i,status:s,thread_ts:o};s!==``&&(c.loading_messages=[s]);let l=await callSlackApi({body:c,botToken:e,context:{teamId:typeof a==`string`?a:void 0},operation:`assistant.threads.setStatus`});if(l.ok!==!0)throw Error(`Slack assistant.threads.setStatus failed: ${l.error??`unknown_error`}`);return{status:s}}}}function createSlackActivityRenderer(e){return{id:SLACK_ACTIVITY_MESSAGE_RENDERER_ID,async dispose(){},async render({destination:t,snapshot:n,state:r}){let i=t.channelId,a=t.installationTeamId,o=t.threadTs;if(typeof i!=`string`||typeof o!=`string`||o===``)return r;let s=isActivityState(r)?r.messages:{},c=activityMessages(n),l=Object.fromEntries(Object.entries(s).filter(([e])=>c.has(e)));for(let[t,n]of c){let r=s[t]??await recoverActivityMessage({botToken:e,channelId:i,installationTeamId:a,rootTurnId:t,threadTs:o});if(r?.text===n){l[t]=r;continue}let c=await writeActivityMessage({botToken:e,channelId:i,current:r,installationTeamId:a,rootTurnId:t,text:n,threadTs:o});if(c.ok!==!0&&r!==void 0&&c.error===`message_not_found`&&(c=await writeActivityMessage({botToken:e,channelId:i,installationTeamId:a,rootTurnId:t,text:n,threadTs:o})),c.ok!==!0)throw Error(`Slack activity message failed: ${c.error??`unknown_error`}`);let u=c.ts??r?.ts;if(typeof u!=`string`||u===``)throw Error(`Slack activity message response did not include ts.`);l[t]={text:n,ts:u}}return{messages:l}}}}async function writeActivityMessage(e){return await callSlackApi({body:e.current===void 0?{channel:e.channelId,metadata:{event_payload:{root_turn_id:e.rootTurnId},event_type:`eve_progress`},text:e.text,thread_ts:e.threadTs}:{channel:e.channelId,text:e.text,ts:e.current.ts},botToken:e.botToken,context:{teamId:typeof e.installationTeamId==`string`?e.installationTeamId:void 0},operation:e.current===void 0?`chat.postMessage`:`chat.update`})}async function recoverActivityMessage(e){let t,n=new Set;for(;;){let r={channel:e.channelId,inclusive:!0,limit:100,ts:e.threadTs};t!==void 0&&(r.cursor=t);let i=await callSlackApi({body:r,botToken:e.botToken,context:{teamId:typeof e.installationTeamId==`string`?e.installationTeamId:void 0},operation:`conversations.replies`});if(i.ok!==!0||!Array.isArray(i.messages))return;for(let t of i.messages){if(typeof t!=`object`||!t)continue;let n=Reflect.get(t,`metadata`),r=typeof n==`object`&&n?Reflect.get(n,`event_payload`):void 0;if(typeof n==`object`&&n&&Reflect.get(n,`event_type`)===`eve_progress`&&typeof r==`object`&&r&&Reflect.get(r,`root_turn_id`)===e.rootTurnId){let e=Reflect.get(t,`ts`),n=Reflect.get(t,`text`);if(typeof e==`string`)return{text:typeof n==`string`?n:``,ts:e}}}let a=Reflect.get(i,`response_metadata`),o=typeof a==`object`&&a?Reflect.get(a,`next_cursor`):void 0;if(typeof o!=`string`||o===``||n.has(o))return;n.add(o),t=o}}function activityMessages(e){let t=new Map;for(let n of Object.values(e.work)){let e=t.get(n.rootTurnId)??[];e.push(n),t.set(n.rootTurnId,e)}return new Map([...t].map(([t,n])=>[t,renderWorkTree(n,Object.values(e.actions).filter(e=>e.rootTurnId===t),Object.values(e.blockers).filter(e=>e.rootTurnId===t))]))}function renderWorkTree(e,t,n){let r=new Map,i=new Set(e.map(e=>e.id));for(let t of e){let e=t.parentId!==void 0&&i.has(t.parentId)?t.parentId:void 0,n=r.get(e)??[];n.push(t),r.set(e,n)}let a=new Set(e.flatMap(e=>e.parentId!==void 0&&e.callId!==void 0?[`action:${e.parentId}:${e.callId}`]:[])),o=new Map;for(let e of t){if(e.kind===`tool`&&a.has(e.id))continue;let t=o.get(e.parentWorkId)??[];t.push(e),o.set(e.parentWorkId,t)}let s=new Map;for(let e of n){let t=s.get(e.parentWorkId)??[];t.push(e),s.set(e.parentWorkId,t)}let c=[],append=e=>{c.length<20&&c.push(e)},visit=(e,t,n)=>{let i=e.kind===`root-turn`?`Working`:e.name??`Agent work`;append(`${t}${n}${phaseIcon(e.phase)} ${escapeSlackText(i)}`);let a=[...(s.get(e.id)??[]).map(e=>({blocker:e})),...(o.get(e.id)??[]).map(e=>({action:e})),...(r.get(e.id)??[]).map(e=>({child:e}))],c=`${t}${n===`├── `?`│ `:n===`└── `?` `:``}`;a.forEach((e,t)=>{let n=t===a.length-1?`└── `:`├── `;`blocker`in e?append(`${c}${n}${blockerIcon(e.blocker.phase)} ${escapeSlackText(e.blocker.label??blockerLabel(e.blocker.kind))}`):`action`in e?append(`${c}${n}${phaseIcon(e.action.phase)} ${escapeSlackText(e.action.label??e.action.name)}`):visit(e.child,c,n)})};for(let e of r.get(void 0)??[])visit(e,``,``);return`\`\`\`\n${c.join(`
|
|
2
|
-
`)}\n\`\`\``}function phaseIcon(e){switch(e){case`completed`:return`✓`;case`failed`:case`rejected`:return`✗`;case`cancelled`:return
|
|
2
|
+
`)}\n\`\`\``}function phaseIcon(e){switch(e){case`completed`:return`✓`;case`failed`:case`rejected`:return`✗`;case`cancelled`:return`⊘`;case`running`:return`•`}}function escapeSlackText(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function isActivityState(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`messages`)==`object`}function selectSlackActivityStatus(e){let t=Object.values(e.work).filter(e=>e.phase===`running`);if(t.length===0)return``;let n=newestBlocker(Object.values(e.blockers).filter(e=>e.phase===`blocked`));if(n!==void 0)return blockerLabel(n.kind);let r=newestAction(Object.values(e.actions).filter(e=>e.phase===`running`));if(r!==void 0)return truncateTypingStatus(r.label??r.name);let i=newestWork(t.filter(e=>e.kind!==`root-turn`));return i===void 0?`Working…`:truncateTypingStatus(i.name??`Working with agent`)}function blockerLabel(e){switch(e){case`approval`:return`Waiting for approval…`;case`authorization`:return`Waiting for sign-in…`;case`input`:return`Waiting for input…`}}function blockerIcon(e){return e===`blocked`?`◌`:e===`completed`?`✓`:e===`failed`?`✗`:`–`}function newestBlocker(e){return e.reduce((e,t)=>e===void 0||t.startedAt>=e.startedAt?t:e,void 0)}function newestAction(e){return e.reduce((e,t)=>e===void 0||t.startedAt>=e.startedAt?t:e,void 0)}function newestWork(e){return e.reduce((e,t)=>e===void 0||t.startedAt>=e.startedAt?t:e,void 0)}function isSlackStatusState(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`status`)==`string`}export{activityMessages,buildSlackActivityRenderers,experimental_slackActivityPlan,experimental_slackActivityRenderer,experimental_slackActivityStatus,experimental_slackActivityTree,hasSlackActivityStatus,selectSlackActivityStatus};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { ToolAuthOptions, ToolAuthProvider } from "#tools/definition.js";
|
|
3
|
+
import type { TokenResult } from "#shared/connection-types.js";
|
|
4
|
+
import { type ScopedAuthorization } from "#runtime/connections/scoped-authorization.js";
|
|
5
|
+
/** Shared getToken/requireAuth capability, independent of the executing tool or workflow. */
|
|
6
|
+
export declare function createAuthorizationContext(input: {
|
|
7
|
+
readonly scope: string;
|
|
8
|
+
readonly boundResponder?: SessionAuthContext;
|
|
9
|
+
readonly completeAuthorization?: (scoped: ScopedAuthorization) => Promise<boolean>;
|
|
10
|
+
}): {
|
|
11
|
+
getToken(provider?: ToolAuthProvider, options?: ToolAuthOptions): Promise<TokenResult>;
|
|
12
|
+
requireAuth(provider?: ToolAuthProvider, options?: ToolAuthOptions): never;
|
|
13
|
+
run: (execute: () => unknown) => Promise<unknown> | AsyncIterable<unknown>;
|
|
14
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAuthorizationExecution}from"#runtime/connections/scoped-authorization.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";function createAuthorizationContext(e){let t=createAuthorizationExecution(e),n={},resolve=(t,r)=>buildInlineScopedAuthorization({...e,inlineAuthState:n,provider:t,options:r});return{async getToken(e,n){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await t.getToken(resolve(e,n))},requireAuth(e,n){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);return t.requireAuth(resolve(e,n))},run:t.run}}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,boundResponder:e.boundResponder,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,scope:e.scope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.scope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.scope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{createAuthorizationContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{evictScopedToken,resolveScopedToken}from"#runtime/connections/scoped-authorization.js";import{ConnectionAuthorizationRequiredError}from"#connections/errors.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{createMCPClient}from"#compiled/@ai-sdk/mcp/index.js";import{omitProvidedArgumentsFromSchema,resolveProvidedArguments}from"#runtime/connections/provided-arguments.js";var McpConnectionClient=class{#e;#t;#n;#r;#i;constructor(e){this.#i=e}async connect(){if(this.#t!==void 0)return this.#t;if(this.#e!==void 0)return this.#e;this.#e=this.#a();try{return this.#t=await this.#e,this.#t}catch(e){throw this.#e=void 0,e}}async#a(){let e=await resolveHeaders(this.#i),t=this.#i.url;try{return await createMCPClient({transport:{type:`http`,url:t,headers:e}})}catch(n){if(!isMcpHttpFallbackRetryableError(n))throw n;return await createMCPClient({transport:{type:`sse`,url:t,headers:e}})}}async getToolMetadata(){return(await this.#o()).metadata}async getTools(){return(await this.#o()).tools}async executeTool(e,t,n){try{let{tools:r}=await this.#o(),i=r[e];if(i?.execute===void 0)throw Error(`Tool "${e}" not found in connection "${this.#i.connectionName}".`);let a=await resolveProvidedArguments({args:t,callId:n.callId,connection:this.#i,toolName:e});return await i.execute(a,{abortSignal:n.abortSignal})}catch(e){return await this.#l(e)}}async#o(){if(this.#r!==void 0)return this.#r;if(this.#n!==void 0)return this.#n;this.#n=this.#s();try{return this.#r=await this.#n,this.#r}catch(e){throw this.#n=void 0,e}}async#s(){try{return await this.#c()}catch(e){return await this.#l(e)}}async#c(){let e=await this.connect(),t=await e.listTools(),n=this.#i.tools,r=n===void 0?t.tools:t.tools.filter(e=>passesToolFilter(e.name,n)),i=Object.keys(this.#i.toolCall?.providedArguments??{}),a=r.map(e=>({...e,inputSchema:omitProvidedArgumentsFromSchema(e.inputSchema,i)})),o=e.toolsFromDefinitions({tools:a});return{metadata:a.map(e=>({annotations:e.annotations,description:e.description??``,inputSchema:e.inputSchema??{},name:e.name,outputSchema:`outputSchema`in e&&e.outputSchema!==void 0?e.outputSchema:void 0})),tools:o}}async close(){this.#t!==void 0&&(await this.#t.close(),this.#t=void 0),this.#e=void 0,this.#n=void 0,this.#r=void 0}async#l(e){throw isMcpAuthRequiredError(e)?(await this.#u(),await this.close(),new ConnectionAuthorizationRequiredError(this.#i.connectionName,{message:`Connection "${this.#i.connectionName}" requires authorization (the server rejected the token).`})):e}async#u(){let e=await resolveConnectionAuthorization(this.#i);e!==void 0&&await evictScopedToken({authorization:e,connection:{url:this.#i.url},instanceId:this.#i.instanceId,scope:this.#i.connectionName})}};function isMcpAuthRequiredError(e){return readHttpStatus(e)===401}function isMcpHttpFallbackRetryableError(e){let t=readHttpStatus(e);return t===400||t===404||t===405}function readHttpStatus(e){for(let t of walkErrorChain(e)){if(!isObject(t))continue;let e=readStatusField(t);if(e!==void 0)return e;let n=t.response;if(isObject(n)){let e=readStatusField(n);if(e!==void 0)return e}if(typeof t.message==`string`){let e=/\bHTTP\s+(\d{3})\b/u.exec(t.message);if(e?.[1]!==void 0)return Number(e[1])}}}function readStatusField(e){if(typeof e.status==`number`)return e.status;if(typeof e.statusCode==`number`)return e.statusCode}function*walkErrorChain(e){let t=e,n=new Set;for(;t!=null&&!n.has(t);){if(n.add(t),yield t,!isObject(t)||!(`cause`in t))return;t=t.cause}}function passesToolFilter(e,t){return t===void 0?!0:`allow`in t?t.allow.includes(e):!t.block.includes(e)}async function resolveHeaders(e){let t={},n,getCallbackContext=()=>n??=buildCallbackContext(),r=await resolveConnectionAuthorization(e,typeof e.authorization==`function`?getCallbackContext():void 0);if(r!==void 0&&(t.Authorization=`Bearer ${(await resolveToken(e,r)).token}`),e.headers!==void 0){let n=await resolveHeadersDefinition(e.headers,getCallbackContext);for(let[i,a]of Object.entries(n)){if(r!==void 0&&i.toLowerCase()===`authorization`)throw Error(`Connection "${e.connectionName}" headers must not include an "Authorization" key when "authorization" is also provided.`);t[i]=a}}return t}async function resolveToken(e,t){return await resolveScopedToken({authorization:t,connection:{url:e.url},instanceId:e.instanceId,scope:e.connectionName})}async function resolveHeadersDefinition(e,t){if(typeof e==`function`)return{...await e(t())};let n={},r=Object.entries(e);for(let[e,i]of r)n[e]=await resolveHeaderValue(i,t);return n}async function resolveHeaderValue(e,t){return typeof e==`function`?await e(t()):await e}export{McpConnectionClient,isMcpAuthRequiredError,passesToolFilter,resolveHeaders};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Scope-parameterized authorization flow shared by MCP connections and
|
|
3
|
-
* authored tools
|
|
3
|
+
* authored tools and workflow steps using inline providers.
|
|
4
4
|
*
|
|
5
5
|
* A *scope* names the framework-owned callback URL — a connection name for
|
|
6
6
|
* an MCP connection, a tool name for tool-hosted auth. Connection-hosted
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* is identical across both, so it lives here once instead of being
|
|
11
11
|
* duplicated per caller.
|
|
12
12
|
*/
|
|
13
|
-
import type
|
|
13
|
+
import { type ConnectionAuthorizationChallenge } from "#connections/errors.js";
|
|
14
14
|
import { type AuthorizationSignal } from "#harness/authorization.js";
|
|
15
15
|
import type { SessionAuthContext } from "#context/keys.js";
|
|
16
16
|
import { type AuthorizationDefinition, type ConnectionAuthorizationContext, type TokenResult } from "#shared/connection-types.js";
|
|
@@ -28,6 +28,21 @@ export interface ScopedAuthorization {
|
|
|
28
28
|
readonly authorization: Readonly<AuthorizationDefinition>;
|
|
29
29
|
readonly connection: ConnectionAuthorizationContext;
|
|
30
30
|
}
|
|
31
|
+
/** One execution's token capability and authorization interruption boundary. */
|
|
32
|
+
export declare function createAuthorizationExecution(options?: {
|
|
33
|
+
readonly completeAuthorization?: typeof completeScopedAuthorization;
|
|
34
|
+
}): {
|
|
35
|
+
complete: (scoped: ScopedAuthorization) => Promise<void>;
|
|
36
|
+
getToken(scoped: ScopedAuthorization): Promise<TokenResult>;
|
|
37
|
+
requireAuth: (scoped: ScopedAuthorization, cause?: unknown) => never;
|
|
38
|
+
handleError(error: unknown, scoped?: ScopedAuthorization): Promise<AuthorizationSignal>;
|
|
39
|
+
run: typeof executeWithAuthorization;
|
|
40
|
+
};
|
|
41
|
+
/** Produces the shared challenge; the caller owns parking and resumption. */
|
|
42
|
+
export declare function handleAuthorizationError(error: unknown, options?: {
|
|
43
|
+
readonly evictToken: boolean;
|
|
44
|
+
}): Promise<AuthorizationSignal>;
|
|
45
|
+
declare function executeWithAuthorization(execute: () => unknown): Promise<unknown> | AsyncIterable<unknown>;
|
|
31
46
|
/**
|
|
32
47
|
* Resolves a bearer token for one scope, consulting the per-step token
|
|
33
48
|
* cache before invoking the authored `getToken`.
|
|
@@ -100,3 +115,4 @@ export declare function resolveAuthorizationCallbackUrl(input: {
|
|
|
100
115
|
* unchanged when the resolved value does not differ.
|
|
101
116
|
*/
|
|
102
117
|
export declare function stampChallengeDisplayName(challenge: ConnectionAuthorizationChallenge, authorization: Readonly<AuthorizationDefinition>): ConnectionAuthorizationChallenge;
|
|
118
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal,resolveConnectionPrincipalFromAuth}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(e){let{scope:t,authorization:n,connection:r}=e,i=e.instanceId??t,a=contextStorage.getStore(),o=resolveScopedPrincipal(e,a);if(a===void 0)return await n.getToken({connection:r,principal:o});let s=principalKey(o),c=readCachedToken(a,i,s);if(c!==void 0)return c;let l=await n.getToken({connection:r,principal:o});return writeCachedToken(a,i,s,l),l}async function evictScopedToken(e){let{scope:t,authorization:n,connection:r}=e,i=e.instanceId??t,a=contextStorage.getStore();if(a===void 0)return;let o;try{o=resolveScopedPrincipal(e,a),evictCachedToken(a,i,principalKey(o))}catch{return}try{await n.evict?.({connection:r,principal:o})}catch{}}async function completeScopedAuthorization(e){let{scope:t,authorization:n,connection:r}=e;if(!supportsInteractiveAuthorization(n))return!1;let i=consumeAuthorizationResult(t,e.instanceId);if(i===void 0)return!1;let a=n,o=loadContext(),s=i.principal??resolveScopedPrincipal(e,o),c=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:r,principal:s,resume:i.resume,callback:i.callback});return writeCachedToken(o,e.instanceId??t,principalKey(s),c),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:r}=e;if(!supportsInteractiveAuthorization(n))return;let i=createAuthorizationAttempt(t);if(i===void 0)return;let a=n,o=resolveScopedPrincipal(e),s=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:i.hookUrl}),{challenge:c,resume:l}=await a.startAuthorization({callbackUrl:s,connection:r,principal:o});return requestAuthorization([{attemptId:i.attemptId,challenge:stampChallengeDisplayName(c,n),hookUrl:s,instanceId:e.instanceId,name:t,principal:o,resume:l}])}function resolveScopedPrincipal(e,t){return e.boundResponder===void 0?resolveConnectionPrincipal(e.scope,e.authorization,t):resolveConnectionPrincipalFromAuth(e.scope,e.authorization,e.boundResponder,t)}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
|
|
1
|
+
import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,createAuthorizationAttempt,requestAuthorization}from"#harness/authorization.js";import{isAsyncIterable}from"#shared/async-iterable.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#connections/errors.js";import{supportsInteractiveAuthorization}from"#shared/connection-types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal,resolveConnectionPrincipalFromAuth}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);function createAuthorizationExecution(e={}){let t=new Set;async function complete(n){let r=n.instanceId??n.scope;!t.has(r)&&await(e.completeAuthorization??completeScopedAuthorization)(n)&&t.add(r)}function requireAuth(e,n){throw new ScopedAuthorizationRequiredError(e,t.has(e.instanceId??e.scope),n)}return{complete,async getToken(e){await complete(e);try{return await resolveScopedToken(e)}catch(t){if(!isConnectionAuthorizationRequiredError(t))throw t;return requireAuth(e,t)}},requireAuth,async handleError(e,n){return n!==void 0&&isConnectionAuthorizationRequiredError(e)?await handleAuthorizationError(new ScopedAuthorizationRequiredError(n,t.has(n.instanceId??n.scope),e),{evictToken:!1}):await handleAuthorizationError(e)},run:executeWithAuthorization}}var ScopedAuthorizationRequiredError=class extends Error{scoped;justAuthorized;constructor(e,t,n){super(`Authorization required.`,{cause:n}),this.name=`ScopedAuthorizationRequiredError`,this.scoped=e,this.justAuthorized=t}};function isScopedAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ScopedAuthorizationRequiredError`}async function handleAuthorizationError(e,t={evictToken:!0}){if(!isScopedAuthorizationRequiredError(e))throw e;let{scoped:n}=e;if(e.justAuthorized)throw new ConnectionAuthorizationFailedError(n.scope,{message:`Authorization for "${n.scope}" failed: the service rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});t.evictToken&&await evictScopedToken(n);let r=await startScopedAuthorization(n);if(r!==void 0)return r;throw supportsInteractiveAuthorization(n.authorization)?new ConnectionAuthorizationFailedError(n.scope,{message:`Authorization for "${n.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1}):e.cause??new ConnectionAuthorizationRequiredError(n.scope)}function executeWithAuthorization(e){try{let t=e();return isAsyncIterable(t)?handleIterable(t):Promise.resolve(t).catch(handleAuthorizationError)}catch(e){return handleAuthorizationError(e)}}async function*handleIterable(e){try{for await(let t of e)yield t}catch(e){yield await handleAuthorizationError(e)}}async function resolveScopedToken(e){let{scope:t,authorization:n,connection:r}=e,i=e.instanceId??t,a=contextStorage.getStore(),o=resolveScopedPrincipal(e,a);if(a===void 0)return await n.getToken({connection:r,principal:o});let s=principalKey(o),c=readCachedToken(a,i,s);if(c!==void 0)return c;let l=await n.getToken({connection:r,principal:o});return writeCachedToken(a,i,s,l),l}async function evictScopedToken(e){let{scope:t,authorization:n,connection:r}=e,i=e.instanceId??t,a=contextStorage.getStore();if(a===void 0)return;let o;try{o=resolveScopedPrincipal(e,a),evictCachedToken(a,i,principalKey(o))}catch{return}try{await n.evict?.({connection:r,principal:o})}catch{}}async function completeScopedAuthorization(e){let{scope:t,authorization:n,connection:r}=e;if(!supportsInteractiveAuthorization(n))return!1;let i=consumeAuthorizationResult(t,e.instanceId);if(i===void 0)return!1;let a=n,o=loadContext(),s=i.principal??resolveScopedPrincipal(e,o),c=await a.completeAuthorization({callbackUrl:i.hookUrl,connection:r,principal:s,resume:i.resume,callback:i.callback});return writeCachedToken(o,e.instanceId??t,principalKey(s),c),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:r}=e;if(!supportsInteractiveAuthorization(n))return;let i=createAuthorizationAttempt(t);if(i===void 0)return;let a=n,o=resolveScopedPrincipal(e),s=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:i.hookUrl}),{challenge:c,resume:l}=await a.startAuthorization({callbackUrl:s,connection:r,principal:o});return requestAuthorization([{attemptId:i.attemptId,challenge:stampChallengeDisplayName(c,n),hookUrl:s,instanceId:e.instanceId,name:t,principal:o,resume:l}])}function resolveScopedPrincipal(e,t){return e.boundResponder===void 0?resolveConnectionPrincipal(e.scope,e.authorization,t):resolveConnectionPrincipalFromAuth(e.scope,e.authorization,e.boundResponder,t)}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,createAuthorizationExecution,evictScopedToken,handleAuthorizationError,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{
|
|
1
|
+
import{expectObjectRecord}from"#internal/authored-module.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readStampedConnectionProtocol}from"#public/definitions/connections/protocol.js";import{registerDefinitionSource,stampDefinitionKey}from"#internal/authored-definition/source-identity.js";import{normalizeAuthorizationSpec}from"#shared/validate-authorization.js";import{ResolveAgentError,loadResolvedModuleExport}from"#runtime/resolve-helpers.js";import{createConnectionInstanceId}from"#runtime/connections/instance-identity.js";async function resolveConnectionDefinition(e,t,n){try{let r=await loadResolvedModuleExport({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),i=expectObjectRecord(r,`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`),a={kind:`connection`,logicalPath:e.logicalPath,name:e.connectionName},o=`connection-source:${e.sourceId}`;stampDefinitionKey(i,o),registerDefinitionSource(o,a),registerDefinitionSource(`connection:${e.url}`,a);let s=i.auth!==void 0,c=i.headers!==void 0,l=e.protocol===`openapi`?i.operations:i.tools,u={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,instanceId:createConnectionInstanceId({connectionName:e.connectionName,instanceKey:typeof i.instanceKey==`string`?i.instanceKey:void 0,protocol:e.protocol,sourceId:e.sourceId,url:e.url}),protocol:e.protocol,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(s){if(typeof i.auth==`function`)u.authorization=i.auth;else try{u.authorization=normalizeAuthorizationSpec(i.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new ResolveAgentError(toErrorMessage(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}}return c&&(u.headers=i.headers),i.toolCall!==void 0&&(u.toolCall=i.toolCall),l!==void 0&&(u.tools=l),e.protocol===`openapi`&&i.spec!==void 0&&(u.spec=i.spec),typeof i.approval==`function`&&(u.approval=i.approval),u}catch(t){throw t instanceof ResolveAgentError?t:new ResolveAgentError(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${toErrorMessage(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function resolveDynamicConnectionValue(e,t){let n=readStampedConnectionProtocol(e),r=`Dynamic connection "${t.connectionName}" from "${t.logicalPath}" must be created by defineMcpClientConnection() or defineOpenAPIConnection().`;if(n===void 0)throw Error(r);let i={kind:`connection`,logicalPath:t.logicalPath,name:t.connectionName},a=`dynamic-connection-source:${t.sourceId}:${t.connectionName}`;if(stampDefinitionKey(e,a),registerDefinitionSource(a,i),n===`openapi`){let i=normalizeOpenApiConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(i.auth,i.instanceKey,r),omitUndefined({approval:i.approval,authorization:i.auth,connectionName:t.connectionName,description:i.description,exportName:t.exportName,headers:i.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:i.instanceKey,protocol:n,sourceId:t.sourceId,url:i.baseUrl??``}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,spec:i.spec,toolCall:i.toolCall,tools:i.operations,url:i.baseUrl??``})}let o=normalizeMcpClientConnectionDefinition(e,r);return assertAuthenticatedDynamicInstanceKey(o.auth,o.instanceKey,r),omitUndefined({approval:o.approval,authorization:o.auth,connectionName:t.connectionName,description:o.description,exportName:t.exportName,headers:o.headers,instanceId:createConnectionInstanceId({connectionName:t.connectionName,instanceKey:o.instanceKey,protocol:n,sourceId:t.sourceId,url:o.url}),logicalPath:t.logicalPath,protocol:n,sourceId:t.sourceId,sourceKind:`module`,toolCall:o.toolCall,tools:o.tools,url:o.url})}function assertAuthenticatedDynamicInstanceKey(e,t,n){if(e!==void 0&&t===void 0)throw Error(`${n} Authenticated dynamic connections must set "instanceKey" to a stable, non-secret account or tenant identifier.`)}function omitUndefined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}export{resolveConnectionDefinition,resolveDynamicConnectionValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{realpath}from"node:fs/promises";import{resolveVercelProjectIdFromEnvironment}from"#shared/vercel-project.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getRuntimeCompiledArtifactsCacheKey,getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{loadCompileMetadata}from"#runtime/loaders/compile-metadata.js";async function createRuntimeSandboxKeys(e){let t=await deriveRuntimeSandboxKeyParts(e);return{sessionKey:buildRuntimeSandboxSessionKey(e,t),templateKey:buildRuntimeSandboxTemplateKey(e,t)}}async function createRuntimeSandboxTemplateKey(e){return buildRuntimeSandboxTemplateKey(e,await deriveRuntimeSandboxKeyParts(e))}async function deriveRuntimeSandboxKeyParts(e){
|
|
1
|
+
import{createHash}from"node:crypto";import{realpath}from"node:fs/promises";import{resolveVercelProjectIdFromEnvironment}from"#shared/vercel-project.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{getRuntimeCompiledArtifactsCacheKey,getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{loadCompileMetadata}from"#runtime/loaders/compile-metadata.js";async function createRuntimeSandboxKeys(e){let t=await deriveRuntimeSandboxKeyParts(e);return{sessionKey:buildRuntimeSandboxSessionKey(e,t),templateKey:buildRuntimeSandboxTemplateKey(e,t)}}async function createRuntimeSandboxTemplateKey(e){return buildRuntimeSandboxTemplateKey(e,await deriveRuntimeSandboxKeyParts(e))}async function deriveRuntimeSandboxKeyParts(e){return{metadata:await loadCompileMetadataForKeys(e.compiledArtifactsSource),scope:await resolveRuntimeSandboxScope(e),versionHash:e.templatePlan.kind===`none`?null:resolveRuntimeSandboxVersionHash({nodeId:e.nodeId,sourceId:e.sourceId,templatePlan:e.templatePlan})}}function buildRuntimeSandboxTemplateKey(e,t){if(t.versionHash===null)return null;let n=createStableHash(`${resolvePackageVersionForTemplateKey(t.metadata)}:7:${t.versionHash}`).slice(0,20);return sanitizeRuntimeSandboxKey(`eve-sbx-tpl-${e.backendName}-${t.scope}-${n}`)}function buildRuntimeSandboxSessionKey(e,t){let n=createStableHash(`7:${t.versionHash??`none`}`).slice(0,12),r=sanitizeRuntimeSandboxKey(e.nodeId);return sanitizeRuntimeSandboxKey(`eve-sbx-ses-${e.backendName}-${t.scope}-${n}-${e.sessionId}-${r}`)}function resolvePackageVersionForTemplateKey(e){return e?.generator.version??resolveInstalledPackageInfo().version}async function loadCompileMetadataForKeys(e){try{return await loadCompileMetadata({compiledArtifactsSource:e})}catch{return null}}async function resolveRuntimeSandboxScope(e){if(e.backendName===`vercel`){let e=resolveVercelProjectIdFromEnvironment();if(e!==void 0)return createStableHash(`vercel-project:${e}`).slice(0,16)}let t=getRuntimeCompiledArtifactsSandboxAppRoot(e.compiledArtifactsSource);return t===void 0?createStableHash(getRuntimeCompiledArtifactsCacheKey(e.compiledArtifactsSource)).slice(0,16):createStableHash(await realpath(t)).slice(0,16)}function resolveRuntimeSandboxVersionHash(e){let t=e.templatePlan.contentHash??``;return e.templatePlan.kind===`bootstrap`?createStableHash(`bootstrap:${e.templatePlan.revalidationKey??``}:${e.templatePlan.sourceHash}:${t}:${e.nodeId}:${e.sourceId}`):createStableHash(`workspace-content:${t}:${e.nodeId}:${e.sourceId}`)}function createStableHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function sanitizeRuntimeSandboxKey(e){return e.replaceAll(/[^a-zA-Z0-9._-]+/g,`-`).slice(0,120)}export{createRuntimeSandboxKeys,createRuntimeSandboxTemplateKey};
|
|
@@ -23,6 +23,8 @@ export interface DefaultSandboxProbes {
|
|
|
23
23
|
readonly isDockerAvailable: () => boolean;
|
|
24
24
|
readonly isMicrosandboxSupported: () => boolean;
|
|
25
25
|
}
|
|
26
|
+
/** Runtime probes shared by availability-aware built-in backend selectors. @internal */
|
|
27
|
+
export declare const SANDBOX_BACKEND_PROBES: DefaultSandboxProbes;
|
|
26
28
|
/**
|
|
27
29
|
* Constructs an availability-aware sandbox backend. On first use it
|
|
28
30
|
* picks the best backend the host supports, in priority order:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLinuxDockerDaemonAvailableSync,isMicrosandboxPlatformSupported}from"#execution/sandbox/bindings/local.js";import{lazyBackend}from"#execution/sandbox/lazy-backend.js";import{docker}from"#sandbox/backends/docker.js";import{justbash}from"#sandbox/backends/just-bash.js";import{microsandbox}from"#sandbox/backends/microsandbox.js";import{vercel}from"#sandbox/backends/vercel.js";const
|
|
1
|
+
import{isLinuxDockerDaemonAvailableSync,isMicrosandboxPlatformSupported}from"#execution/sandbox/bindings/local.js";import{lazyBackend}from"#execution/sandbox/lazy-backend.js";import{docker}from"#sandbox/backends/docker.js";import{justbash}from"#sandbox/backends/just-bash.js";import{microsandbox}from"#sandbox/backends/microsandbox.js";import{vercel}from"#sandbox/backends/vercel.js";const SANDBOX_BACKEND_PROBES={isDeployedOnVercel:()=>!!process.env.VERCEL,isDockerAvailable:()=>isLinuxDockerDaemonAvailableSync(),isMicrosandboxSupported:()=>isMicrosandboxPlatformSupported()};function defaultSandbox(e){return lazyBackend(()=>selectDefaultSandbox(e,SANDBOX_BACKEND_PROBES))}function selectDefaultSandbox(e,t){return t.isDeployedOnVercel()?vercel(e?.vercel):t.isDockerAvailable()?docker(e?.docker):t.isMicrosandboxSupported()?microsandbox(e?.microsandbox):justbash(e?.justBash)}export{SANDBOX_BACKEND_PROBES,defaultSandbox,selectDefaultSandbox};
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { type AgentStaticModelDefinition } from "#public/index.js";
|
|
2
|
+
import { type SelfModificationConfig } from "./config.js";
|
|
2
3
|
/** Default model used by the self-modification subagent. */
|
|
3
4
|
export declare const DEFAULT_SELF_MODIFICATION_MODEL = "anthropic/claude-sonnet-5";
|
|
4
|
-
/** Configuration for the
|
|
5
|
+
/** Configuration for the self-modification subagent. */
|
|
5
6
|
export interface SelfModificationAgentOptions {
|
|
7
|
+
/** Policy shared with the sandbox and extension mount. */
|
|
8
|
+
readonly config?: SelfModificationConfig;
|
|
6
9
|
/**
|
|
7
10
|
* Model used by the self-modification subagent.
|
|
8
11
|
*
|
|
@@ -10,7 +13,7 @@ export interface SelfModificationAgentOptions {
|
|
|
10
13
|
*/
|
|
11
14
|
readonly model?: AgentStaticModelDefinition;
|
|
12
15
|
}
|
|
13
|
-
/** Defines the
|
|
16
|
+
/** Defines the environment-aware self-modification dynamic subagent. */
|
|
14
17
|
export declare function defineSelfModificationAgent(options?: SelfModificationAgentOptions): import("#public/index.js").DynamicSentinel<import("#public/index.js").DefinedAgent<{
|
|
15
18
|
description: string;
|
|
16
19
|
model: AgentStaticModelDefinition;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5
|
|
1
|
+
import{resolveSelfModificationConfig}from"./config.js";import{hasGitHubCredential}from"./credentials.js";import{resolveSelfModificationMode}from"./mode.js";import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5`,n=resolveSelfModificationConfig(e.config),resolve=()=>{let e=resolveSelfModificationMode(n);return e===`local`?defineAgent({description:`Delegate here when the developer asks to change this eve agent or its authored source. Describe the requested behavior change without guessing source paths or passing runtime skill paths under $HOME/.agents or /workspace/skills; the subagent discovers authored files under its /source mount. Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the developer does not mention files or source code. Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. Also delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them. Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted. Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn. If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.`,model:t}):e!==`deployed`||n.deployed===void 0||n.deployed.credentials.kind===`pat`&&!hasGitHubCredential()?null:defineAgent({description:`Delegate here when the user asks to change this eve agent or its authored source. Describe the requested behavior change without guessing source paths or passing runtime skill paths under $HOME/.agents or /workspace/skills; the subagent discovers authored files in an isolated checkout under its /source mount. Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the user does not mention files or source code. Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround. Also delegate requests to add integrations, channels, connections, or capabilities: the subagent searches the official eve registry and can install source changes into the draft proposal. Setup may require non-secret answers or an external action, and secret binding remains separate. Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. Source edits do not affect the caller’s current turn. The subagent can publish only a draft pull request, and changes become effective only after review, merge, and redeployment. If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.`,model:t})};return defineDynamic({events:{"session.started":resolve,"turn.started":resolve}})}var agent_default=defineSelfModificationAgent();export{DEFAULT_SELF_MODIFICATION_MODEL,agent_default as default,defineSelfModificationAgent};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export interface SelfModificationConfig {
|
|
2
|
+
readonly local?: {
|
|
3
|
+
readonly enabled?: boolean;
|
|
4
|
+
};
|
|
5
|
+
readonly deployed?: {
|
|
6
|
+
readonly source: {
|
|
7
|
+
readonly git: {
|
|
8
|
+
/** GitHub repository in github.com/owner/repository form. */
|
|
9
|
+
readonly repository: string;
|
|
10
|
+
/** Application directory relative to the repository root. */
|
|
11
|
+
readonly directory: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
readonly target: {
|
|
15
|
+
readonly branch: string;
|
|
16
|
+
};
|
|
17
|
+
readonly credentials?: {
|
|
18
|
+
/** Ephemeral, repository-scoped GitHub App credentials from Vercel Connect. */
|
|
19
|
+
readonly vercelConnect?: {
|
|
20
|
+
readonly connector: string;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Self-hosted exception. Reads `EVE_SELF_MODIFICATION_GITHUB_TOKEN` from
|
|
24
|
+
* the trusted deployment environment; never injects it into the sandbox.
|
|
25
|
+
*/
|
|
26
|
+
readonly pat?: true;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export interface ResolvedSelfModificationConfig {
|
|
31
|
+
readonly localEnabled: boolean;
|
|
32
|
+
readonly deployed?: ResolvedDeployedSelfModificationConfig;
|
|
33
|
+
}
|
|
34
|
+
export interface ResolvedDeployedSelfModificationConfig {
|
|
35
|
+
readonly credentials: ResolvedGitHubCredentials;
|
|
36
|
+
readonly directory: string;
|
|
37
|
+
readonly repository: GitHubRepository;
|
|
38
|
+
readonly targetBranch: string;
|
|
39
|
+
}
|
|
40
|
+
export type ResolvedGitHubCredentials = {
|
|
41
|
+
readonly kind: "pat";
|
|
42
|
+
} | {
|
|
43
|
+
readonly connector: string;
|
|
44
|
+
readonly kind: "vercel-connect";
|
|
45
|
+
};
|
|
46
|
+
export interface GitHubRepository {
|
|
47
|
+
readonly owner: string;
|
|
48
|
+
readonly repo: string;
|
|
49
|
+
}
|
|
50
|
+
/** Defines the policy shared by the self-modification agent, sandbox, and extension. */
|
|
51
|
+
export declare function defineSelfModificationConfig(config?: SelfModificationConfig): SelfModificationConfig;
|
|
52
|
+
export declare function resolveSelfModificationConfig(config?: SelfModificationConfig): ResolvedSelfModificationConfig;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertGitRef,assertRepositoryPart}from"./identifiers.js";function defineSelfModificationConfig(e={}){return resolveSelfModificationConfig(e),e}function resolveSelfModificationConfig(e={}){if(!isRecord(e))throw Error(`Self-modification configuration must be an object.`);let t=e.local;if(t!==void 0&&!isRecord(t))throw Error(`Self-modification local must be an object.`);let n=t?.enabled??!0;if(typeof n!=`boolean`)throw Error(`Self-modification local.enabled must be a boolean.`);let r=e.deployed;if(r===void 0)return{localEnabled:n};if(!isRecord(r))throw Error(`Self-modification deployed must be an object.`);let{source:i,target:a,credentials:o}=r;if(i===void 0||a===void 0)throw Error(`Self-modification deployed requires both source and target configuration.`);if(!isRecord(i))throw Error(`Self-modification deployed.source must be an object.`);if(!isRecord(i.git))throw Error(`Self-modification deployed.source.git must be an object.`);if(!isRecord(a))throw Error(`Self-modification deployed.target must be an object.`);let{git:s}=i;if(typeof s.repository!=`string`||typeof s.directory!=`string`)throw Error(`Self-modification deployed.source.git.repository and deployed.source.git.directory must be strings.`);if(typeof a.branch!=`string`)throw Error(`Self-modification deployed.target.branch must be a string.`);return{deployed:{credentials:parseCredentials(o),directory:parseDirectory(s.directory),repository:parseGitHubRepository(s.repository),targetBranch:parseBranch(a.branch)},localEnabled:n}}function parseCredentials(e){if(!isRecord(e))throw Error(`Self-modification deployed.credentials must explicitly configure Vercel Connect or the self-hosted PAT exception.`);if(e.vercelConnect!==void 0==(e.pat!==void 0))throw Error(`Self-modification deployed.credentials must configure exactly one of vercelConnect or pat.`);if(e.pat!==void 0){if(e.pat!==!0)throw Error(`Self-modification deployed.credentials.pat must be true.`);return{kind:`pat`}}if(!isRecord(e.vercelConnect))throw Error(`Self-modification deployed.credentials.vercelConnect must be an object.`);let t=e.vercelConnect.connector;if(typeof t!=`string`||t.trim().length===0)throw Error(`Self-modification deployed.credentials.vercelConnect.connector must be a string.`);return{connector:t.trim(),kind:`vercel-connect`}}function parseGitHubRepository(e){let t=/^github\.com\/([^/]+)\/([^/]+)$/u.exec(e);if(t?.[1]===void 0||t[2]===void 0)throw Error(`Self-modification deployed.source.git.repository must use github.com/owner/repo form.`);return assertRepositoryPart(t[1],`repository owner`),assertRepositoryPart(t[2],`repository name`),{owner:t[1],repo:t[2]}}function parseDirectory(e){if(e!==`.`&&(e.length===0||e.startsWith(`/`)||e.includes(`\\`)||e.split(`/`).some(e=>e===``||e===`.`||e===`..`)))throw Error(`Self-modification deployed.source.git.directory must be a safe repository-relative path.`);return e}function parseBranch(e){if(assertGitRef(e,`target branch`),e.startsWith(`refs/`))throw Error(`Self-modification deployed.target.branch must be a branch name, not a full Git ref.`);return e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{defineSelfModificationConfig,resolveSelfModificationConfig};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { GitHubRepository, ResolvedGitHubCredentials } from "./config.js";
|
|
2
|
+
export type GitHubCredentialCapability = "checkout" | "publish";
|
|
3
|
+
export interface GitHubCredentialRequest {
|
|
4
|
+
readonly capability: GitHubCredentialCapability;
|
|
5
|
+
readonly repository: GitHubRepository;
|
|
6
|
+
}
|
|
7
|
+
export interface GitHubCredentialProvider {
|
|
8
|
+
resolve(request: GitHubCredentialRequest): Promise<string>;
|
|
9
|
+
}
|
|
10
|
+
export declare const SELF_MODIFICATION_GITHUB_TOKEN_ENV = "EVE_SELF_MODIFICATION_GITHUB_TOKEN";
|
|
11
|
+
/** Checks PAT availability without returning the credential. */
|
|
12
|
+
export declare function hasGitHubCredential(): boolean;
|
|
13
|
+
/** Constructs the configured provider without resolving a credential. */
|
|
14
|
+
export declare function createGitHubCredentialProvider(credentials: ResolvedGitHubCredentials): GitHubCredentialProvider;
|
|
15
|
+
/** Resolves a PAT GitHub credential without exposing it to authored code. */
|
|
16
|
+
export declare function resolveGitHubCredential(request: GitHubCredentialRequest): Promise<string>;
|
|
17
|
+
export declare const defaultGitHubCredentialProvider: GitHubCredentialProvider;
|
|
18
|
+
export declare function createVercelConnectCredentialProvider(connector: string): GitHubCredentialProvider;
|