eve 0.52.3 → 0.52.5
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 +27 -0
- package/dist/src/cli/commands/init-agent-workspace.d.ts +2 -0
- package/dist/src/cli/commands/init-agent-workspace.js +1 -1
- package/dist/src/cli/commands/init-install.d.ts +8 -0
- package/dist/src/cli/commands/init-install.js +1 -0
- package/dist/src/cli/commands/init.d.ts +3 -4
- package/dist/src/cli/commands/init.js +1 -1
- 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/cli/run.js +2 -2
- package/dist/src/cli/telemetry/index.d.ts +3 -0
- package/dist/src/cli/telemetry/index.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -2
- package/dist/src/compiled/@workflow/world-local/index.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +4 -4
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/dynamic-model-lifecycle.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +11 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/mock-model.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/evals/runner/run-evals.d.ts +1 -1
- package/dist/src/evals/runner/run-evals.js +1 -1
- package/dist/src/execution/activity-cohort.d.ts +20 -0
- package/dist/src/execution/activity-cohort.js +1 -0
- package/dist/src/execution/authorization-callback-match.d.ts +1 -0
- package/dist/src/execution/authorization-callback-match.js +1 -1
- 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-activity-projection.d.ts +2 -0
- package/dist/src/execution/session-activity-projection.js +1 -1
- package/dist/src/execution/session-command-inbox.js +1 -1
- package/dist/src/execution/skills/instructions.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/execution/workflow-steps.js +1 -1
- package/dist/src/harness/approval-delivery-coordinator.js +1 -1
- package/dist/src/harness/authorization.d.ts +6 -2
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/current-messages.d.ts +8 -2
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/hitl/approval-input-requests.js +1 -1
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/pending-input-batches.d.ts +4 -0
- package/dist/src/harness/pending-input-batches.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-client-context.d.ts +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/mock-model-identity.d.ts +2 -0
- package/dist/src/internal/mock-model-identity.js +1 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.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/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.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/delivery-context.d.ts +2 -2
- package/dist/src/tasks/delivery-context.js +2 -18
- package/dist/src/tasks/delivery-policy.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/durable-callbacks.d.ts +18 -1
- package/dist/src/tools/durable-callbacks.js +1 -1
- package/dist/src/tools/workflow-definition.d.ts +5 -2
- package/docs/channels/overview.mdx +2 -0
- package/docs/channels/slack.mdx +2 -0
- package/docs/concepts/sessions-runs-and-streaming.md +2 -0
- package/docs/evals/reporters.mdx +20 -1
- package/docs/evals/running.mdx +3 -1
- package/docs/guides/dynamic-capabilities.md +36 -1
- package/docs/guides/instrumentation.md +3 -2
- package/docs/instructions.mdx +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/reference/telemetry.md +1 -1
- package/docs/reference/typescript-api.md +36 -35
- package/docs/sandbox.mdx +2 -0
- package/docs/subagents/index.mdx +10 -0
- package/docs/tools/overview.mdx +4 -2
- 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
|
@@ -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};
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export { type BackgroundToolDefinition, type DisabledToolSentinel, defineTool, disableTool, isDisabledToolSentinel, type TaskExec, type TaskReceipt, type ToolLabelDefinition, type ToolAuthOptions, type ToolAuthProvider, type ToolDefinition, type ToolContext, type ToolModelOutput, type ToolModelOutputPart, } from "#tools/definition.js";
|
|
5
5
|
export { defineDynamic } from "#dynamic/definition.js";
|
|
6
|
+
export { defineDurableCallback } from "#tools/durable-callbacks.js";
|
|
6
7
|
export { toolOutput, toolOutputPart } from "#tools/model-output.js";
|
|
7
8
|
export type { DynamicEvents, DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";
|
|
8
9
|
export type { DynamicToolEntry, DynamicToolEvents, DynamicToolSet, DynamicToolResult, } from "#tools/dynamic.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineTool,disableTool,isDisabledToolSentinel}from"#tools/definition.js";import{defineDynamic}from"#dynamic/definition.js";import{defineWorkflowTool}from"#tools/workflow-definition.js";import{toolOutput,toolOutputPart}from"#tools/model-output.js";import{toolResultFrom}from"#public/tools/result.js";export{defineDynamic,defineTool,defineWorkflowTool,disableTool,isDisabledToolSentinel,toolOutput,toolOutputPart,toolResultFrom};
|
|
1
|
+
import{defineTool,disableTool,isDisabledToolSentinel}from"#tools/definition.js";import{defineDynamic}from"#dynamic/definition.js";import{defineDurableCallback}from"#tools/durable-callbacks.js";import{defineWorkflowTool}from"#tools/workflow-definition.js";import{toolOutput,toolOutputPart}from"#tools/model-output.js";import{toolResultFrom}from"#public/tools/result.js";export{defineDurableCallback,defineDynamic,defineTool,defineWorkflowTool,disableTool,isDisabledToolSentinel,toolOutput,toolOutputPart,toolResultFrom};
|
|
@@ -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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const SELF_MODIFICATION_GITHUB_TOKEN_ENV=`EVE_SELF_MODIFICATION_GITHUB_TOKEN`;function hasGitHubCredential(){return(process.env.EVE_SELF_MODIFICATION_GITHUB_TOKEN?.trim().length??0)>0}function createGitHubCredentialProvider(e){return e.kind===`pat`?defaultGitHubCredentialProvider:createVercelConnectCredentialProvider(e.connector)}async function resolveGitHubCredential(e){return defaultGitHubCredentialProvider.resolve(e)}const defaultGitHubCredentialProvider={async resolve(){let e=process.env[SELF_MODIFICATION_GITHUB_TOKEN_ENV];if(e===void 0||e.trim().length===0)throw Error(`Self-modification requires ${SELF_MODIFICATION_GITHUB_TOKEN_ENV} in the deployment environment.`);return e.trim()}};function createVercelConnectCredentialProvider(e){return{async resolve(t){try{let{getToken:n}=await import(`@vercel/connect`),r=await n(e,{authorizationDetails:[{type:`github_app_installation`,repositories:[`${t.repository.owner}/${t.repository.repo}`]}],scopes:t.capability===`checkout`?[`contents:read`,`metadata:read`]:[`contents:write`,`pull_requests:write`,`metadata:read`],subject:{type:`app`}});if(r.trim().length===0)throw Error(`empty token`);return r}catch(t){throw Error(`Self-modification could not obtain a GitHub credential from Vercel Connect for ${e}. Install and attach the configured GitHub connector to this Vercel project, install the managed GitHub App for the configured repository, then retry.`,{cause:t})}}}}export{SELF_MODIFICATION_GITHUB_TOKEN_ENV,createGitHubCredentialProvider,createVercelConnectCredentialProvider,defaultGitHubCredentialProvider,hasGitHubCredential,resolveGitHubCredential};
|
|
@@ -13,11 +13,17 @@ export type EveAddOutcome = {
|
|
|
13
13
|
readonly message: string;
|
|
14
14
|
readonly changed?: readonly string[];
|
|
15
15
|
};
|
|
16
|
-
interface HeadlessEvent {
|
|
16
|
+
export interface HeadlessEvent {
|
|
17
17
|
readonly version?: number;
|
|
18
18
|
readonly type: string;
|
|
19
19
|
readonly item?: string;
|
|
20
|
+
readonly completedItems?: readonly string[];
|
|
21
|
+
readonly deploymentRequired?: boolean;
|
|
22
|
+
readonly installed?: boolean;
|
|
20
23
|
readonly message?: string;
|
|
24
|
+
readonly question?: unknown;
|
|
25
|
+
readonly url?: string;
|
|
26
|
+
readonly userCode?: string;
|
|
21
27
|
readonly failureCode?: string;
|
|
22
28
|
readonly rolledBack?: boolean;
|
|
23
29
|
readonly changed?: readonly string[];
|
|
@@ -53,4 +59,3 @@ export declare function runEveAdd(input: {
|
|
|
53
59
|
readonly signal?: AbortSignal | undefined;
|
|
54
60
|
readonly spawn?: SpawnLike | undefined;
|
|
55
61
|
}): Promise<EveAddOutcome>;
|
|
56
|
-
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{findPackageJSON}from"node:module";import{readFile}from"node:fs/promises";import{dirname,isAbsolute,relative,resolve}from"node:path";import{spawn,spawnSync}from"node:child_process";import{pathToFileURL}from"node:url";const INSTALL_TIMEOUT_MS=6e5;function terminateChildTree(e,t){if(e.pid!==void 0){if(process.platform===`win32`){let n=process.env.SystemRoot??process.env.WINDIR;if(n!==void 0&&n!==``&&spawnSync(resolve(n,`System32`,`taskkill.exe`),[`/pid`,String(e.pid),`/t`,...t===`SIGKILL`?[`/f`]:[]],{stdio:`ignore`,windowsHide:!0}).status===0)return}else try{process.kill(-e.pid,t);return}catch{}}e.kill(t)}function isChildTreeAlive(e){if(process.platform===`win32`||e.pid===void 0)return!1;try{return process.kill(-e.pid,0),!0}catch{return!1}}async function resolveEveExecutable(e){let t=findPackageJSON(`eve`,pathToFileURL(resolve(e,`package.json`)));if(t===void 0)throw Error(`The "eve" package is not installed under ${e}, so registry items cannot be installed from here.`);let n=dirname(t),r=JSON.parse(await readFile(t,`utf8`)),i=typeof r==`object`&&r?r.bin:void 0,a=typeof i==`string`?i:typeof i==`object`&&i?i.eve:void 0;if(typeof a!=`string`||a.length===0)throw Error(`The installed "eve" package does not declare an "eve" binary.`);let o=resolve(n,a),s=relative(n,o);if(s.startsWith(`..`)||isAbsolute(s))throw Error(`The installed "eve" package declares its binary outside the package.`);return o}function readTerminalHeadlessEvent(e){let t;for(let n of e.split(`
|
|
2
|
-
`)){let e=n.trim();if(!e.startsWith(`{`))continue;let r;try{r=JSON.parse(e)}catch{continue}if(typeof r!=`object`||!r)continue;let i=r;i.version===1&&(i.type===`completed`||i.type===`blocked`||i.type===`failed`||i.type===`cancelled`)&&(t=i)}return t}async function runEveAdd(e){let t=await resolveEveExecutable(e.appRoot),n=e.spawn??spawn;return await new Promise(r=>{let i=n(process.execPath,[t,`add`,e.address,`--non-interactive`,`--skip-setup`],{cwd:e.appRoot,detached:process.platform!==`win32`,env:process.env,stdio:[`ignore`,`pipe`,`pipe`]}),a=``,collect=e=>{a=`${a}${String(e)}`.slice(-64e3)};i.stdout?.on(`data`,collect),i.stderr?.on(`data`,collect);let o=!1,s,c,l,finish=t=>{o||(o=!0,clearTimeout(u),c!==void 0&&clearTimeout(c),l!==void 0&&clearTimeout(l),e.signal?.removeEventListener(`abort`,abort),r(t))},finishAfterTreeExits=e=>{if(isChildTreeAlive(i)){l=setTimeout(()=>finishAfterTreeExits(e),25),l.unref?.();return}finish(s??e)},stop=e=>{s===void 0&&(s=e,terminateChildTree(i,`SIGTERM`),c=setTimeout(()=>terminateChildTree(i,`SIGKILL`),5e3),c.unref?.())},abort=()=>{stop({kind:`failed`,message:`Installing ${e.address} was cancelled.`})},u=setTimeout(()=>{stop({kind:`failed`,message:`Installing ${e.address} did not finish within ${INSTALL_TIMEOUT_MS/6e4} minutes.`})},INSTALL_TIMEOUT_MS);u.unref?.(),e.signal?.aborted===!0?abort():e.signal?.addEventListener(`abort`,abort,{once:!0}),i.on(`error`,()=>{stop({kind:`failed`,message:`Could not run \`eve add ${e.address}\`. Run the command in a terminal for details.`})}),i.on(`close`,t=>{let n,r=readTerminalHeadlessEvent(a);if(t===0&&r?.type===`completed`&&r.item===e.address)n={kind:`installed`};else if(r?.type===`blocked`&&r.item===e.address)n={kind:`blocked`,message:`Installing ${e.address} stopped for input that only a terminal can supply.`};else if(r?.type===`failed`&&r.item===e.address&&typeof r.message==`string`){let e=r.failureCode===`pnpm_build_policy`?"Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command.":`Dependency installation failed. Retry the eve add command in a terminal for details.`,t=Array.isArray(r.changed)?r.changed.filter(e=>typeof e==`string`&&e.length<=300&&!e.includes(`..`)&&/^[\w@+./ -]+$/u.test(e)):[],i=r.rolledBack===!0?`${e} Project files were restored.`:t.length===0?`${e} The install may have partially changed the project.`:`${e} The install partially changed: ${t.join(`, `)}. Restore those files, then retry.`;n=t.length===0?{kind:`failed`,message:i}:{kind:`failed`,message:i,changed:t}}else n={kind:`failed`,message:`\`eve add ${e.address}\` failed and may have partially changed the project. Run it in a terminal for details.`};finishAfterTreeExits(n)})})}export{readTerminalHeadlessEvent,resolveEveExecutable,runEveAdd};
|
|
2
|
+
`)){let e=n.trim();if(!e.startsWith(`{`))continue;let r;try{r=JSON.parse(e)}catch{continue}if(typeof r!=`object`||!r)continue;let i=r;i.version===1&&(i.type===`completed`||i.type===`blocked`||i.type===`failed`||i.type===`cancelled`||i.type===`external_action`)&&(t=i)}return t}async function runEveAdd(e){let t=await resolveEveExecutable(e.appRoot),n=e.spawn??spawn;return await new Promise(r=>{let i=n(process.execPath,[t,`add`,e.address,`--non-interactive`,`--skip-setup`],{cwd:e.appRoot,detached:process.platform!==`win32`,env:process.env,stdio:[`ignore`,`pipe`,`pipe`]}),a=``,collect=e=>{a=`${a}${String(e)}`.slice(-64e3)};i.stdout?.on(`data`,collect),i.stderr?.on(`data`,collect);let o=!1,s,c,l,finish=t=>{o||(o=!0,clearTimeout(u),c!==void 0&&clearTimeout(c),l!==void 0&&clearTimeout(l),e.signal?.removeEventListener(`abort`,abort),r(t))},finishAfterTreeExits=e=>{if(isChildTreeAlive(i)){l=setTimeout(()=>finishAfterTreeExits(e),25),l.unref?.();return}finish(s??e)},stop=e=>{s===void 0&&(s=e,terminateChildTree(i,`SIGTERM`),c=setTimeout(()=>terminateChildTree(i,`SIGKILL`),5e3),c.unref?.())},abort=()=>{stop({kind:`failed`,message:`Installing ${e.address} was cancelled.`})},u=setTimeout(()=>{stop({kind:`failed`,message:`Installing ${e.address} did not finish within ${INSTALL_TIMEOUT_MS/6e4} minutes.`})},INSTALL_TIMEOUT_MS);u.unref?.(),e.signal?.aborted===!0?abort():e.signal?.addEventListener(`abort`,abort,{once:!0}),i.on(`error`,()=>{stop({kind:`failed`,message:`Could not run \`eve add ${e.address}\`. Run the command in a terminal for details.`})}),i.on(`close`,t=>{let n,r=readTerminalHeadlessEvent(a);if(t===0&&r?.type===`completed`&&r.item===e.address)n={kind:`installed`};else if(r?.type===`blocked`&&r.item===e.address)n={kind:`blocked`,message:`Installing ${e.address} stopped for input that only a terminal can supply.`};else if(r?.type===`failed`&&r.item===e.address&&typeof r.message==`string`){let e=r.failureCode===`pnpm_build_policy`?"Dependency installation stopped because pnpm requires build-script decisions. Run `pnpm approve-builds`, then retry the eve add command.":`Dependency installation failed. Retry the eve add command in a terminal for details.`,t=Array.isArray(r.changed)?r.changed.filter(e=>typeof e==`string`&&e.length<=300&&!e.includes(`..`)&&/^[\w@+./ -]+$/u.test(e)):[],i=r.rolledBack===!0?`${e} Project files were restored.`:t.length===0?`${e} The install may have partially changed the project.`:`${e} The install partially changed: ${t.join(`, `)}. Restore those files, then retry.`;n=t.length===0?{kind:`failed`,message:i}:{kind:`failed`,message:i,changed:t}}else n={kind:`failed`,message:`\`eve add ${e.address}\` failed and may have partially changed the project. Run it in a terminal for details.`};finishAfterTreeExits(n)})})}export{readTerminalHeadlessEvent,resolveEveExecutable,runEveAdd};
|
|
@@ -1,2 +1,47 @@
|
|
|
1
|
-
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const selfModificationConfigSchema: z.ZodObject<{
|
|
3
|
+
local: z.ZodOptional<z.ZodObject<{
|
|
4
|
+
enabled: z.ZodOptional<z.ZodBoolean>;
|
|
5
|
+
}, z.core.$strip>>;
|
|
6
|
+
deployed: z.ZodOptional<z.ZodObject<{
|
|
7
|
+
credentials: z.ZodOptional<z.ZodObject<{
|
|
8
|
+
pat: z.ZodOptional<z.ZodLiteral<true>>;
|
|
9
|
+
vercelConnect: z.ZodOptional<z.ZodObject<{
|
|
10
|
+
connector: z.ZodString;
|
|
11
|
+
}, z.core.$strip>>;
|
|
12
|
+
}, z.core.$strip>>;
|
|
13
|
+
source: z.ZodObject<{
|
|
14
|
+
git: z.ZodObject<{
|
|
15
|
+
directory: z.ZodString;
|
|
16
|
+
repository: z.ZodString;
|
|
17
|
+
}, z.core.$strip>;
|
|
18
|
+
}, z.core.$strip>;
|
|
19
|
+
target: z.ZodObject<{
|
|
20
|
+
branch: z.ZodString;
|
|
21
|
+
}, z.core.$strip>;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
/** Extension mount configured with the same policy as the agent and sandbox. */
|
|
25
|
+
declare const _default: import("eve/extension").ExtensionHandle<z.ZodObject<{
|
|
26
|
+
local: z.ZodOptional<z.ZodObject<{
|
|
27
|
+
enabled: z.ZodOptional<z.ZodBoolean>;
|
|
28
|
+
}, z.core.$strip>>;
|
|
29
|
+
deployed: z.ZodOptional<z.ZodObject<{
|
|
30
|
+
credentials: z.ZodOptional<z.ZodObject<{
|
|
31
|
+
pat: z.ZodOptional<z.ZodLiteral<true>>;
|
|
32
|
+
vercelConnect: z.ZodOptional<z.ZodObject<{
|
|
33
|
+
connector: z.ZodString;
|
|
34
|
+
}, z.core.$strip>>;
|
|
35
|
+
}, z.core.$strip>>;
|
|
36
|
+
source: z.ZodObject<{
|
|
37
|
+
git: z.ZodObject<{
|
|
38
|
+
directory: z.ZodString;
|
|
39
|
+
repository: z.ZodString;
|
|
40
|
+
}, z.core.$strip>;
|
|
41
|
+
}, z.core.$strip>;
|
|
42
|
+
target: z.ZodObject<{
|
|
43
|
+
branch: z.ZodString;
|
|
44
|
+
}, z.core.$strip>;
|
|
45
|
+
}, z.core.$strip>>;
|
|
46
|
+
}, z.core.$strip>>;
|
|
2
47
|
export default _default;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineExtension}from"eve/extension";var extension_default=defineExtension();export{extension_default as default};
|
|
1
|
+
import{boolean,literal,object,string}from"../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/schemas.js";import"../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/index.js";import{defineExtension}from"eve/extension";const selfModificationConfigSchema=object({local:object({enabled:boolean().optional()}).optional(),deployed:object({credentials:object({pat:literal(!0).optional(),vercelConnect:object({connector:string()}).optional()}).optional(),source:object({git:object({directory:string(),repository:string()})}),target:object({branch:string()})}).optional()});var extension_default=defineExtension({config:selfModificationConfigSchema});export{extension_default as default,selfModificationConfigSchema};
|