eve 0.74.0 → 0.75.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/src/channel/auth/result.d.ts +4 -0
- package/dist/src/channel/auth/result.js +1 -0
- package/dist/src/channel/types.d.ts +14 -2
- package/dist/src/chunks/{use-eve-agent-mP0M7SrL.js → use-eve-agent-B2Kne9z6.js} +7 -2
- package/dist/src/chunks/{use-eve-agent-DOOXadF0.js → use-eve-agent-DK_T88EP.js} +7 -2
- package/dist/src/cli/commands/integration-connect.d.ts +2 -0
- package/dist/src/cli/commands/integration-connect.js +1 -1
- package/dist/src/cli/commands/integration-setup.js +1 -1
- package/dist/src/cli/commands/registry-declared-setups.d.ts +19 -0
- package/dist/src/cli/commands/registry-declared-setups.js +1 -1
- package/dist/src/cli/commands/registry-recovery.d.ts +3 -1
- package/dist/src/cli/commands/registry-recovery.js +1 -1
- package/dist/src/cli/commands/registry.d.ts +12 -4
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/dev/tui/registry-result-message.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +2 -0
- package/dist/src/cli/dev/tui/setup-commands.js +2 -2
- package/dist/src/client/index.d.ts +1 -0
- package/dist/src/client/session.d.ts +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +1 -1
- package/dist/src/client/types.d.ts +6 -0
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +18 -12
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/dynamic-connection-lifecycle.d.ts +6 -0
- package/dist/src/context/dynamic-connection-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +4 -1
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/providers/sandbox.js +1 -1
- package/dist/src/context/providers/tool-stubs-key.d.ts +8 -0
- package/dist/src/context/providers/tool-stubs-key.js +1 -0
- package/dist/src/context/providers/tool-stubs.d.ts +10 -0
- package/dist/src/context/providers/tool-stubs.js +1 -0
- package/dist/src/context/run-step.js +1 -1
- package/dist/src/evals/index.d.ts +1 -0
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/session-manager.d.ts +2 -0
- package/dist/src/evals/session-manager.js +1 -1
- package/dist/src/eve-channel/create-request.d.ts +2 -0
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/eve-channel/request.js +1 -1
- package/dist/src/execution/agent-sessions/context.d.ts +2 -0
- package/dist/src/execution/agent-sessions/context.js +1 -1
- package/dist/src/execution/agent-sessions/steps.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/dynamic-connection-recovery.d.ts +14 -0
- package/dist/src/execution/dynamic-connection-recovery.js +1 -0
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/forward-session-input.js +1 -1
- package/dist/src/execution/legacy-session/authorization.js +1 -1
- package/dist/src/execution/legacy-session/completion-step.js +1 -1
- package/dist/src/execution/legacy-session/inbox.js +1 -1
- package/dist/src/execution/legacy-session/interrupt-step.js +1 -1
- package/dist/src/execution/proxied-deliver-step.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/ensure.d.ts +3 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/session/active-turn.js +1 -1
- package/dist/src/execution/session/admission.js +1 -1
- package/dist/src/execution/session/checkpoint-migrations.js +1 -1
- package/dist/src/execution/session/end-sandbox-step.d.ts +12 -0
- package/dist/src/execution/session/end-sandbox-step.js +1 -0
- package/dist/src/execution/session/finalization.js +1 -1
- package/dist/src/execution/session/handoff-steps.js +1 -1
- package/dist/src/execution/session/handoff.d.ts +1 -1
- package/dist/src/execution/session/handoff.js +1 -1
- package/dist/src/execution/session/program.js +1 -1
- package/dist/src/execution/session/timeout-steps.js +1 -1
- package/dist/src/execution/session/turn-step.js +1 -1
- package/dist/src/execution/session-inbox/inbox.d.ts +6 -1
- package/dist/src/execution/session-inbox/inbox.js +1 -1
- package/dist/src/execution/session-inbox/release-step.js +1 -1
- package/dist/src/execution/session-inbox/resume.d.ts +2 -1
- package/dist/src/execution/session-inbox/resume.js +1 -1
- package/dist/src/execution/session-workflow-tool-run.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/tasks/model-step.js +1 -1
- package/dist/src/execution/tasks/steps.js +1 -1
- package/dist/src/execution/tasks/table.d.ts +7 -1
- package/dist/src/execution/tasks/table.js +1 -1
- package/dist/src/execution/tool-stubs/playback.d.ts +11 -0
- package/dist/src/execution/tool-stubs/playback.js +1 -0
- package/dist/src/execution/tool-stubs/steps.d.ts +18 -0
- package/dist/src/execution/tool-stubs/steps.js +1 -0
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/connection-tools.d.ts +0 -6
- package/dist/src/execution/tools/connection-tools.js +2 -2
- package/dist/src/execution/tools/workflow/authorization-completion.js +1 -1
- package/dist/src/execution/tools/workflow/body.js +1 -1
- package/dist/src/execution/tools/workflow/serve.js +1 -1
- package/dist/src/execution/tools/workflow/withdraw-step.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-webhook-route.js +1 -1
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/hitl/approved-calls.d.ts +2 -0
- package/dist/src/harness/hitl/approved-calls.js +1 -1
- package/dist/src/harness/hitl/index.d.ts +9 -1
- package/dist/src/harness/hitl/index.js +1 -1
- package/dist/src/harness/hitl/intake.js +1 -1
- package/dist/src/harness/model-call/run.js +1 -1
- package/dist/src/harness/proxy-input-requests.d.ts +17 -6
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/session-machine/current.d.ts +4 -0
- package/dist/src/harness/session-machine/current.js +1 -1
- package/dist/src/harness/step/after-model.js +1 -1
- package/dist/src/harness/step/context.d.ts +7 -2
- package/dist/src/harness/step/context.js +1 -1
- package/dist/src/harness/tool-call-io.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/invocation/workflow-execution.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow/cancel-expired-development-run.js +1 -1
- package/dist/src/protocol/routes.d.ts +4 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.d.ts +21 -4
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/mcp.js +1 -1
- package/dist/src/public/schedules/providers/in-memory.js +1 -1
- package/dist/src/public/schedules/providers/vercel.js +1 -1
- package/dist/src/public/schedules/subscription.d.ts +0 -1
- package/dist/src/sandbox/state.d.ts +1 -0
- package/dist/src/self-modification/extension/subagents/agent/instructions.js +1 -1
- package/dist/src/self-modification/extension/subagents/agent/tools/registry_add.js +1 -1
- package/dist/src/setup/flows/registry-session.d.ts +10 -2
- package/dist/src/setup/flows/registry-session.js +1 -1
- package/dist/src/setup/flows/registry.d.ts +2 -0
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/integrations/shared/prerequisite.d.ts +8 -0
- package/dist/src/setup/integrations/shared/prerequisite.js +1 -1
- package/dist/src/setup/registry-setup-client.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/index.js +1 -1
- package/dist/src/setup/vercel-project.d.ts +1 -2
- package/dist/src/setup/vercel-project.js +0 -0
- package/dist/src/shared/sandbox-provider.d.ts +9 -2
- package/dist/src/subagents/adapter.d.ts +3 -2
- package/dist/src/subagents/adapter.js +1 -1
- package/dist/src/subagents/callback-route.js +1 -1
- package/dist/src/subagents/hitl-proxy.d.ts +4 -3
- package/dist/src/subagents/hitl-proxy.js +1 -1
- package/dist/src/subagents/parent-notification.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tool-stubs/execute.d.ts +13 -0
- package/dist/src/tool-stubs/execute.js +1 -0
- package/dist/src/tool-stubs/output.d.ts +4 -0
- package/dist/src/tool-stubs/output.js +1 -0
- package/dist/src/tool-stubs/playback.d.ts +15 -0
- package/dist/src/tool-stubs/playback.js +1 -0
- package/dist/src/tool-stubs/rules.d.ts +3 -0
- package/dist/src/tool-stubs/rules.js +1 -0
- package/dist/src/tool-stubs/schema.d.ts +4 -0
- package/dist/src/tool-stubs/schema.js +1 -0
- package/dist/src/tool-stubs/target.d.ts +8 -0
- package/dist/src/tool-stubs/target.js +1 -0
- package/dist/src/tool-stubs/types.d.ts +56 -0
- package/dist/src/tool-stubs/types.js +1 -0
- package/dist/src/tool-stubs/validate-targets.d.ts +6 -0
- package/dist/src/tool-stubs/validate-targets.js +1 -0
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +2 -2
- package/docs/evals/meta.json +10 -1
- package/docs/evals/overview.mdx +2 -0
- package/docs/evals/tool-stubs.mdx +257 -0
- package/docs/extensions.md +1 -1
- package/docs/guides/auth-and-route-protection.md +25 -0
- package/docs/guides/dynamic-capabilities.md +10 -3
- package/docs/guides/frontend/nextjs.mdx +17 -4
- package/docs/sandbox/index.mdx +10 -2
- package/docs/subagents/index.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tools/overview.mdx +8 -4
- package/docs/tools/workflows.mdx +15 -7
- package/package.json +1 -1
|
@@ -220,6 +220,13 @@ export declare class ForbiddenError extends Error {
|
|
|
220
220
|
readonly response: Response;
|
|
221
221
|
constructor(opts?: AuthErrorOptions);
|
|
222
222
|
}
|
|
223
|
+
export interface AuthResult extends SessionAuthContext {
|
|
224
|
+
/**
|
|
225
|
+
* Set to true to let this authenticated caller create sessions with tool stubs.
|
|
226
|
+
* Callers without this permission cannot supply stubs.
|
|
227
|
+
*/
|
|
228
|
+
readonly allowToolStubs?: boolean;
|
|
229
|
+
}
|
|
223
230
|
/**
|
|
224
231
|
* Route auth callback. Returned value semantics inside {@link routeAuth}:
|
|
225
232
|
*
|
|
@@ -231,7 +238,7 @@ export declare class ForbiddenError extends Error {
|
|
|
231
238
|
* {@link UnauthenticatedError} or {@link ForbiddenError}. To accept anonymous
|
|
232
239
|
* traffic, include {@link none} as the final entry.
|
|
233
240
|
*/
|
|
234
|
-
export type AuthFn<TEvent = Request> = (event: TEvent) =>
|
|
241
|
+
export type AuthFn<TEvent = Request> = (event: TEvent) => AuthResult | null | undefined | Promise<AuthResult | null | undefined>;
|
|
235
242
|
/**
|
|
236
243
|
* OAuth protected-resource metadata attached to an inbound auth policy.
|
|
237
244
|
* `issuer` is shorthand for a single authorization server.
|
|
@@ -297,7 +304,7 @@ export declare function withAuthChallenges<TEvent>(fn: AuthFn<TEvent>, challenge
|
|
|
297
304
|
* a custom `defineChannel` route handler) should call `routeAuth` rather than
|
|
298
305
|
* re-implement the walk.
|
|
299
306
|
*/
|
|
300
|
-
export declare function routeAuth(request: Request, auth: AuthFn<Request> | readonly AuthFn<Request>[]): Promise<
|
|
307
|
+
export declare function routeAuth(request: Request, auth: AuthFn<Request> | readonly AuthFn<Request>[]): Promise<AuthResult | Response>;
|
|
301
308
|
/**
|
|
302
309
|
* Returns an {@link AuthFn} for scaffolded apps that makes unfinished
|
|
303
310
|
* production auth fail as an intentional 401 rather than an internal route
|
|
@@ -343,7 +350,7 @@ export declare function none<TEvent = unknown>(): AuthFn<TEvent>;
|
|
|
343
350
|
*/
|
|
344
351
|
export declare function localDev(): AuthFn<Request>;
|
|
345
352
|
/**
|
|
346
|
-
* Options for
|
|
353
|
+
* Options for verifying a Vercel OIDC token with {@link verifyVercelOidc}.
|
|
347
354
|
*/
|
|
348
355
|
export interface VerifyVercelOidcOptions {
|
|
349
356
|
/**
|
|
@@ -452,13 +459,23 @@ export interface VercelSubjectInput {
|
|
|
452
459
|
* not exposed in `sub`. See Vercel's OIDC reference for the token anatomy.
|
|
453
460
|
*/
|
|
454
461
|
export declare function vercelSubject(input: VercelSubjectInput): string;
|
|
462
|
+
export interface VercelOidcOptions extends Omit<VerifyVercelOidcOptions, "subjects"> {
|
|
463
|
+
/**
|
|
464
|
+
* Additional token subjects allowed to authenticate.
|
|
465
|
+
* To allow stubs, use { subject, allowToolStubs: true } for that subject.
|
|
466
|
+
*/
|
|
467
|
+
readonly subjects?: readonly (string | {
|
|
468
|
+
readonly subject: string;
|
|
469
|
+
readonly allowToolStubs?: boolean;
|
|
470
|
+
})[];
|
|
471
|
+
}
|
|
455
472
|
/**
|
|
456
473
|
* Returns an HTTP route auth callback backed by Vercel OIDC. See
|
|
457
474
|
* {@link verifyVercelOidc} for the always-on current-project bypass and how
|
|
458
475
|
* `subjects` extends acceptance to other Vercel projects. Declares a
|
|
459
476
|
* `Bearer` {@link withAuthChallenges} challenge for {@link routeAuth}'s 401.
|
|
460
477
|
*/
|
|
461
|
-
export declare function vercelOidc(opts?:
|
|
478
|
+
export declare function vercelOidc(opts?: VercelOidcOptions): AuthFn<Request>;
|
|
462
479
|
/**
|
|
463
480
|
* Options accepted by {@link httpBasic}.
|
|
464
481
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}function localDev(){return()=>isLocalDevelopmentServer()?LOCAL_DEV_SESSION_AUTH_CONTEXT:null}function isLocalDevelopmentServer(){return process.env.VERCEL&&process.env.VERCEL_ENV===`development`?!0:isEveDevEnvironment()}const ANONYMOUS_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`none`,principalId:`anonymous`,principalType:`anonymous`},LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,...i.kind===`misconfigured`?{detail:i.message}:{}}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){return withAuthChallenges(async t=>{let n=extractBearerToken(t.headers.get(`authorization`)),r=e.currentVercelProject??(n!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(t):void 0),i=await verifyVercelOidc(n,r===void 0?e:{...e,currentVercelProject:r});return i.ok?i.sessionAuth:null},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{decodeJwt}from"#compiled/jose/index.js";import{areTokenClaimMatchersSatisfied}from"#channel/auth/token-claims.js";import{isVercelOidcIssuer}from"#shared/vercel-project.js";import{isLoopbackHostname}from"#shared/network-address.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{resolveVercelOidcCurrentProject}from"#channel/auth/vercel-oidc-project.js";import{authenticateHttpBasicStrategy}from"#channel/auth/http-basic.js";import{authenticateJwtEcdsaStrategy}from"#channel/auth/jwt-ecdsa.js";import{authenticateJwtHmacStrategy}from"#channel/auth/jwt-hmac.js";import{authenticateOidcStrategy}from"#channel/auth/oidc.js";import{createRuntimeSessionAuthContext}from"#channel/auth/types.js";import{createRuntimeIpAllowList,isRuntimeIpAllowed}from"#channel/ip-allow-list.js";const vercelOidcLog=createLogger(`auth.vercel-oidc`);function verifyHttpBasic(e,t){if(e===null)return{ok:!1};let n=authenticateHttpBasicStrategy({authorization:e,strategy:{kind:`http-basic`,password:t.password,username:t.username}});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function verifyJwtHmac(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-hmac`,secret:t.secret,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtHmacStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyJwtEcdsa(e,t){if(e===null||e.length===0)return{ok:!1};let n={algorithm:t.algorithm,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,issuer:t.issuer,kind:`jwt-ecdsa`,publicKey:t.publicKey,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=await authenticateJwtEcdsaStrategy({strategy:n,token:e});return r.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(r.principal)}:{ok:!1}}async function verifyOidc(e,t){let n=await runOidcVerification(e,{...t,acceptCurrentVercelProject:!1,currentVercelProject:void 0});return n.kind===`authenticated`?{ok:!0,sessionAuth:createRuntimeSessionAuthContext(n.principal)}:{ok:!1}}async function runOidcVerification(e,t){if(e===null||e.length===0)return{kind:`not-authenticated`};let n={acceptCurrentVercelProject:t.acceptCurrentVercelProject,audiences:[...t.audiences],clockSkewSeconds:t.clockSkewSeconds??30,discoveryUrl:t.discoveryUrl??`${t.issuer.replace(/\/$/,``)}/.well-known/openid-configuration`,issuer:t.issuer,kind:`oidc`,...t.claims===void 0?{}:{claims:t.claims},...t.subjects===void 0?{}:{subjects:t.subjects}},r=t.currentVercelProject===void 0?n:{...n,currentVercelProject:t.currentVercelProject};return await authenticateOidcStrategy({strategy:r,token:e})}function extractBearerToken(e){if(e===null)return null;let t=/^Bearer\s+(.+)$/i.exec(e)?.[1]?.trim();return t===void 0||t.length===0?null:t}function createIpAllowList(e){return createRuntimeIpAllowList(e)}function isIpAllowed(e,t){return e!==null&&isRuntimeIpAllowed(e,t)}function createUnauthorizedResponse(e={}){let t=e.status??401,n=e.code??(t===403?`forbidden`:`unauthorized`),r=e.message??(t===403?`Forbidden.`:`Authorization is required for this route.`),i=e.challenges??[],a=new Headers({"cache-control":`no-store`});for(let e of i)a.append(`www-authenticate`,formatChallenge(e));return Response.json({code:n,error:r,ok:!1},{headers:a,status:t})}function formatChallenge(e){if(e.parameters===void 0||Object.keys(e.parameters).length===0)return e.scheme;let t=Object.entries(e.parameters).map(([e,t])=>`${e}="${escapeAuthChallengeParameter(t)}"`).join(`, `);return`${e.scheme} ${t}`}function escapeAuthChallengeParameter(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}function isValidOAuthIdentifierUrl(e){try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`&&isLoopbackHostname(t.hostname))&&t.username.length===0&&t.password.length===0&&t.search.length===0&&t.hash.length===0}catch{return!1}}function isValidMetadataPath(e){if(!e.startsWith(`/`)||e.startsWith(`//`))return!1;let t=new URL(e,`https://eve.invalid`);return t.origin===`https://eve.invalid`&&t.search.length===0&&t.hash.length===0}var UnauthenticatedError=class extends Error{response;constructor(e={}){super(e.message??`Authorization is required for this route.`),this.name=`UnauthenticatedError`,this.response=createUnauthorizedResponse({...e,status:401})}},ForbiddenError=class extends Error{response;constructor(e={}){super(e.message??`Forbidden.`),this.name=`ForbiddenError`,this.response=createUnauthorizedResponse({...e,status:403})}};const OAUTH_RESOURCE_SYMBOL=Symbol.for(`eve.channels.auth.oauthResource`);function oauthResource(e,t){let n=t.issuer===void 0?t.authorizationServers:[t.issuer];if(n.length===0||n.some(e=>!isValidOAuthIdentifierUrl(e)))throw Error(`oauthResource requires at least one HTTPS authorization server URL (HTTP is allowed only on loopback).`);if(t.resource!==void 0&&!isValidOAuthIdentifierUrl(t.resource))throw Error(`oauthResource resource must be an HTTPS URL without credentials, query, or fragment (HTTP is allowed only on loopback).`);if(t.metadataPath!==void 0&&!isValidMetadataPath(t.metadataPath))throw Error(`oauthResource metadataPath must be an absolute path without a host, query, or fragment.`);let r=Array.isArray(e)?e:[e],composed=async e=>{for(let t of r){let n=await t(e);if(n)return n}return null},i=collectDeclaredChallenges(r),a=withAuthChallenges(composed,i.length>0?i:[{scheme:`Bearer`}]);return Object.defineProperty(a,OAUTH_RESOURCE_SYMBOL,{enumerable:!1,value:t}),a}function readOAuthResourceOptions(e){if(!Array.isArray(e))return e[OAUTH_RESOURCE_SYMBOL]}const AUTH_CHALLENGES_SYMBOL=Symbol.for(`eve.channels.auth.challenges`);function withAuthChallenges(e,t){let wrapped=t=>e(t);return Object.defineProperty(wrapped,AUTH_CHALLENGES_SYMBOL,{value:t}),wrapped}function getDeclaredChallenges(e){return e[AUTH_CHALLENGES_SYMBOL]}function collectDeclaredChallenges(e){let t=new Set,n=[];for(let r of e)for(let e of getDeclaredChallenges(r)??[]){let r=formatChallenge(e);t.has(r)||(t.add(r),n.push(e))}return n}async function routeAuth(e,t){let n=Array.isArray(t)?t:[t];try{for(let t of n){let n=await t(e);if(n)return n}}catch(e){if(typeof e==`object`&&e&&`response`in e&&e.response instanceof Response)return e.response;throw e}let r=collectDeclaredChallenges(n);return createUnauthorizedResponse({challenges:r.length>0?addInvalidBearerTokenError(e,r):[{scheme:`Bearer`}]})}function addInvalidBearerTokenError(e,t){let n=e.headers.get(`authorization`);return n===null||!/^Bearer(?:\s|$)/i.test(n.trim())||!t.some(e=>e.scheme===`Bearer`)?t:t.map(e=>e.scheme!==`Bearer`||e.parameters?.error!==void 0?e:{...e,parameters:{...e.parameters,error:`invalid_token`}})}function placeholderAuth(){return()=>{if(process.env.VERCEL_ENV!==`production`)return null;throw new UnauthenticatedError({code:`eve_production_auth_not_configured`,message:`Production auth is not configured. Replace placeholderAuth() in agent/channels/eve.ts with your app's auth provider.`})}}function none(){return()=>ANONYMOUS_SESSION_AUTH_CONTEXT}function localDev(){return()=>isLocalDevelopmentServer()?LOCAL_DEV_SESSION_AUTH_CONTEXT:null}function isLocalDevelopmentServer(){return process.env.VERCEL&&process.env.VERCEL_ENV===`development`?!0:isEveDevEnvironment()}const ANONYMOUS_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`none`,principalId:`anonymous`,principalType:`anonymous`},LOCAL_DEV_SESSION_AUTH_CONTEXT={attributes:{},authenticator:`local-dev`,principalId:`local-dev`,principalType:`local-dev`};async function verifyVercelOidc(e,t={}){if(e===null||e.length===0)return{ok:!1};let n=decodeUnverifiedJwtClaims(e);if(n===null)return vercelOidcLog.debug(`Rejected token that failed to decode as a JWT.`),{ok:!1};if(!isVercelOidcIssuer(n.issuer))return vercelOidcLog.debug(`Rejected token whose issuer is not a Vercel OIDC issuer.`,{issuer:n.issuer}),{ok:!1};if(n.audiences.length===0)return vercelOidcLog.debug(`Rejected token with no audience claim.`,{issuer:n.issuer}),{ok:!1};if(!n.audiences.some(e=>e.startsWith(`https://vercel.com/`)))return vercelOidcLog.debug(`Rejected token whose audience is not a Vercel audience.`,{audiences:n.audiences,issuer:n.issuer}),{ok:!1};let r=resolveCurrentVercelProject(t),i=await runOidcVerification(e,{acceptCurrentVercelProject:!0,audiences:n.audiences,currentVercelProject:r,issuer:n.issuer,subjects:t.subjects??[]});return i.kind===`authenticated`?(vercelOidcLog.debug(`Accepted Vercel OIDC token.`,{issuer:n.issuer,principalType:i.principal.principalType,subject:i.principal.subject}),{ok:!0,sessionAuth:createRuntimeSessionAuthContext(i.principal)}):(vercelOidcLog.debug(`Rejected Vercel OIDC token after verification.`,{audiences:n.audiences,issuer:n.issuer,reason:i.kind,subjectsConfigured:(t.subjects??[]).length>0,...i.kind===`misconfigured`?{detail:i.message}:{}}),{ok:!1})}function resolveCurrentVercelProject(e){if(e.currentVercelProject!==void 0)return e.currentVercelProject;let t=process.env.VERCEL_PROJECT_ID?.trim();if(t===void 0||t.length===0)return;let n=process.env.VERCEL_TARGET_ENV?.trim()||process.env.VERCEL_ENV?.trim();return n===void 0||n.length===0?{projectId:t}:{environment:n,projectId:t}}function vercelSubject(e){assertVercelSubjectSegment(`teamSlug`,e.teamSlug),assertVercelSubjectSegment(`projectName`,e.projectName);let t=e.environment??`production`;if(t!==`production`&&t!==`preview`&&t!==`development`&&t!==`*`)throw Error(`vercelSubject: invalid environment ${JSON.stringify(t)}; expected "production", "preview", "development", or "*".`);return`owner:${e.teamSlug}:project:${e.projectName}:environment:${t}`}function assertVercelSubjectSegment(e,t){if(t.length===0)throw Error(`vercelSubject: ${e} must be a non-empty string.`);if(t.includes(`*`)||t.includes(`:`))throw Error(`vercelSubject: ${e} ${JSON.stringify(t)} may not contain ${t.includes(`:`)?`':'`:`'*'`}. Hand-write the subject string when wildcards are intentional.`)}function vercelOidc(e={}){let{subjects:t,...n}=e,r={...n,subjects:t?.map(e=>typeof e==`string`?e:e.subject)};return withAuthChallenges(async n=>{let i=extractBearerToken(n.headers.get(`authorization`)),a=e.currentVercelProject??(i!==null&&isLocalDevelopmentVercelOidc()?await resolveVercelOidcCurrentProject(n):void 0),o=await verifyVercelOidc(i,a===void 0?r:{...r,currentVercelProject:a});if(!o.ok)return null;let s=o.sessionAuth;return(s.principalType===`service`||s.principalType===`runtime`)&&t?.some(e=>typeof e!=`string`&&e.allowToolStubs===!0&&areTokenClaimMatchersSatisfied({sub:s.subject},{subjects:[e.subject]}))?{...s,allowToolStubs:!0}:s},[{scheme:`Bearer`}])}function isLocalDevelopmentVercelOidc(){return process.env.VERCEL_ENV===`development`?!0:process.env.VERCEL_ENV===`preview`||process.env.VERCEL_ENV===`production`?!1:isEveDevEnvironment()}function httpBasic(e,t){return withAuthChallenges(t=>{let n=verifyHttpBasic(t.headers.get(`authorization`),e);return n.ok?n.sessionAuth:null},[{parameters:{realm:t?.realm??`eve`,charset:`UTF-8`},scheme:`Basic`}])}function jwtHmac(e){return withAuthChallenges(async t=>{let n=await verifyJwtHmac(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function jwtEcdsa(e){return withAuthChallenges(async t=>{let n=await verifyJwtEcdsa(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function oidc(e){return withAuthChallenges(async t=>{let n=await verifyOidc(extractBearerToken(t.headers.get(`authorization`)),e);return n.ok?n.sessionAuth:null},[{scheme:`Bearer`}])}function decodeUnverifiedJwtClaims(e){let t;try{t=decodeJwt(e)}catch{return null}return typeof t.iss!=`string`||t.iss.length===0?null:{audiences:typeof t.aud==`string`?[t.aud]:Array.isArray(t.aud)?t.aud.filter(e=>typeof e==`string`):[],issuer:t.iss}}export{ForbiddenError,UnauthenticatedError,createIpAllowList,createUnauthorizedResponse,escapeAuthChallengeParameter,extractBearerToken,httpBasic,isIpAllowed,jwtEcdsa,jwtHmac,localDev,none,oauthResource,oidc,placeholderAuth,readOAuthResourceOptions,routeAuth,vercelOidc,vercelSubject,verifyHttpBasic,verifyJwtEcdsa,verifyJwtHmac,verifyOidc,verifyVercelOidc,withAuthChallenges};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{inputRequestSchema,inputResponseSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions,routeAuth}from"#public/channels/auth.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=await resolveMcpRequestPrincipals(e,o,n.trustedForwarders);return s instanceof Response?s:await handleMcpRequest(e,t,o,s,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer every entry in inputRequests in one agent_update call; repeating accepted answers is safe.`,`If status is authorization_required, show the user the authorization url or instructions and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. Terminal statuses are completed, failed, and cancelled. input_required needs agent_update; authorization_required needs the user to follow the returned authorization.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in inputRequests, each keyed by its requestId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject(e);return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const AUTHORIZATION_CHALLENGE_SCHEMA=z.strictObject({displayName:z.string().optional(),expiresAt:z.iso.datetime().optional(),instructions:z.string().optional(),url:z.url().optional(),userCode:z.string().optional()}),AUTHORIZATION_REQUEST_SCHEMA=z.strictObject({authorization:AUTHORIZATION_CHALLENGE_SCHEMA.optional(),description:z.string(),name:z.string(),webhookUrl:z.url().optional()}),MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=inputResponseSchema.safeExtend({optionId:z.string().max(256).optional(),requestId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),MCP_INPUT_REQUEST_SCHEMA=inputRequestSchema.safeExtend({action:z.strictObject({callId:z.string(),input:z.record(z.string(),z.json()),kind:z.literal(`tool-call`),toolName:z.string()})}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({inputRequests:z.record(z.string(),MCP_INPUT_REQUEST_SCHEMA),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({authorizations:z.array(AUTHORIZATION_REQUEST_SCHEMA).min(1),pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`authorization_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{inputRequestSchema,inputResponseSchema}from"#shared/input.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{parseJsonObject}from"#shared/json.js";import{DELETE,GET,HEAD,OPTIONS,POST,defineChannel}from"#public/definitions/channel.js";import{readAgentInfoRouteResponse,readRouteChannelName,readRouteSessionCreator,readSkillFileSource}from"#internal/nitro/routes/channel-route-context.js";import{sessionAuthFromResult}from"#channel/auth/result.js";import{escapeAuthChallengeParameter,readOAuthResourceOptions,routeAuth}from"#public/channels/auth.js";import{McpToolOperationError,createMcpStreamableHttpServer,defineMcpTool}from"#internal/mcp/streamable-http-server.js";import{WorkflowAgentInvocationExecution}from"#internal/invocation/workflow-execution.js";import{MCP_TOOL_SESSIONS_EXTENSION,createPublishedTools}from"#internal/mcp/published-tools.js";import{resolveMcpRequestPrincipals}from"#internal/mcp/forwarded-principal-header.js";import{createMcpSkillsFeature}from"#internal/mcp/skills.js";import{validateMcpHttpRequest,validateMcpMetadataRequest}from"#internal/mcp/http-security.js";import{createMcpProtectedResourceMetadata,createMcpResourceChallenge}from"#internal/mcp/protected-resource.js";function mcpChannel(e){if(e?.auth===void 0)throw Error(`mcpChannel requires auth. Use none() for explicit public access.`);let t={agent:e.agent??!0,skills:e.skills??!1,tools:e.tools??!1};if(!t.agent&&!t.tools&&!t.skills)throw Error(`mcpChannel publishes nothing with agent, tools, and skills all false. Enable one.`);let n=e.route??`/eve/v1/mcp`,r=readOAuthResourceOptions(e.auth),handle=async(n,i)=>await authenticateMcpRequest(n,i,e,r,t),i=[GET(n,handle),POST(n,handle),DELETE(n,handle)];return r!==void 0&&i.unshift(...protectedResourceMetadataRoutes(r,n)),defineChannel({routes:i})}function protectedResourceMetadataRoutes(e,t){let n=protectedResourceMetadataPath(e,t);return[GET(n,async n=>protectedResourceMetadataResponse(n,e,t,!1)),HEAD(n,async n=>protectedResourceMetadataResponse(n,e,t,!0)),OPTIONS(n,async e=>protectedResourceMetadataOptionsResponse(e))]}function protectedResourceMetadataPath(e,t){if(e.metadataPath!==void 0)return e.metadataPath;let n=e.resource===void 0?t:new URL(e.resource).pathname;return n===`/`?`/.well-known/oauth-protected-resource`:`/.well-known/oauth-protected-resource${n}`}function protectedResourceMetadataResponse(e,t,n,r){let i=validateMcpMetadataRequest(e);if(i!==void 0)return i;let a=t.resource??new URL(n,new URL(e.url).origin).toString(),o=t.issuer===void 0?t.authorizationServers:[t.issuer],s=Response.json(createMcpProtectedResourceMetadata({authorizationServers:o,resource:a,scopesSupported:t.scopes}),{headers:{"access-control-allow-origin":`*`,"cache-control":`no-store`}});return r?new Response(null,{headers:s.headers,status:s.status}):s}function protectedResourceMetadataOptionsResponse(e){let t=validateMcpMetadataRequest(e);if(t!==void 0)return t;let n=new Headers({"access-control-allow-methods":`GET, HEAD, OPTIONS`,"access-control-allow-origin":`*`,"cache-control":`no-store`}),r=e.headers.get(`access-control-request-headers`);return r!==null&&(n.set(`access-control-allow-headers`,r),n.set(`vary`,`Access-Control-Request-Headers`)),new Response(null,{headers:n,status:204})}function addResourceChallenge(e,t,n){if(e.status!==401&&e.status!==403)return e;let r=protectedResourceMetadataPath(n,new URL(t.url).pathname),i=n.resource??new URL(t.url).origin,a=new URL(r,i).toString(),o=new Headers(e.headers),s=o.get(`www-authenticate`);if(e.status===401)o.set(`www-authenticate`,mergeMcpBearerChallenge(s,a,n.scopes));else{let t=augmentInsufficientScopeChallenge(s,a);if(t===void 0)return e;o.set(`www-authenticate`,t)}return new Response(e.body,{headers:o,status:e.status,statusText:e.statusText})}function mergeMcpBearerChallenge(e,t,n){let r=parseAuthChallenges(e),i=r.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`))??r.find(e=>e.scheme.toLowerCase()===`bearer`);return replaceBearerChallenges(r,i,i===void 0?createMcpResourceChallenge(t,n):augmentBearerChallenge(i.value,t,n))}function augmentInsufficientScopeChallenge(e,t){let n=parseAuthChallenges(e),r=n.find(e=>e.scheme.toLowerCase()===`bearer`&&hasAuthParameter(e.value,`error`,`insufficient_scope`));if(r!==void 0)return replaceBearerChallenges(n,r,augmentBearerChallenge(r.value,t))}function replaceBearerChallenges(e,t,n){let r=[],i=!1;for(let a of e){if(a.scheme.toLowerCase()!==`bearer`){r.push(a.value);continue}!i&&a===t&&(r.push(n),i=!0)}return i||r.push(n),r.join(`, `)}function augmentBearerChallenge(e,t,n){let r=e;return hasAuthParameter(r,`resource_metadata`)||(r=appendAuthParameter(r,`resource_metadata`,t)),n?.length&&!hasAuthParameter(r,`scope`)&&(r=appendAuthParameter(r,`scope`,n.join(` `))),r}function appendAuthParameter(e,t,n){return`${e}${e.trim().toLowerCase()===`bearer`?` `:`, `}${t}="${escapeAuthChallengeParameter(n)}"`}function hasAuthParameter(e,t,n){let r=t.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(n===void 0)return RegExp(`(?:^|[\\s,])${r}\\s*=`,`i`).test(e);let i=n.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(?:^|[\\s,])${r}\\s*=\\s*(?:"${i}"|${i})(?=$|[\\s,])`,`i`).test(e)}function parseAuthChallenges(e){if(e===null)return[];let t=[];for(let n of splitQuotedHeaderList(e)){let e=readChallengeScheme(n);if(e!==void 0){t.push({scheme:e,value:n});continue}let r=t.at(-1);r!==void 0&&(r.value+=`, ${n}`)}return t}function splitQuotedHeaderList(e){let t=[],n=!1,r=!1,i=0;for(let a=0;a<e.length;a++){let o=e[a];if(n)n=!1;else if(o===`\\`)n=!0;else if(o===`"`)r=!r;else if(o===`,`&&!r){let n=e.slice(i,a).trim();n.length>0&&t.push(n),i=a+1}}let a=e.slice(i).trim();return a.length>0&&t.push(a),t}function readChallengeScheme(e){let t=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?:\s+|$)/.exec(e);if(t===null)return;let n=t[1];if(n!==void 0)return e.slice(n.length).trimStart().startsWith(`=`)?void 0:n}async function authenticateMcpRequest(e,t,n,r,i){let a=validateMcpHttpRequest(e);if(a!==void 0)return a;let o=await routeAuth(e,n.auth);if(o instanceof Response)return r===void 0?o:addResourceChallenge(o,e,r);let s=sessionAuthFromResult(o),c=await resolveMcpRequestPrincipals(e,s,n.trustedForwarders);return c instanceof Response?c:await handleMcpRequest(e,t,s,c,i)}async function handleMcpRequest(e,t,n,r,i){let a=readRouteSessionCreator(t),o=readRouteChannelName(t),s=readAgentInfoRouteResponse(t);if(o===void 0||a===void 0||s===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});let c=await s();if(!c.ok)return c;let l=await c.json();if(typeof l.agent?.name!=`string`)return Response.json({error:`MCP requires compiled agent metadata.`},{status:500});let u=typeof l.agent.description==`string`?l.agent.description:void 0,d=new WorkflowAgentInvocationExecution({createSession:a,from:t.from}),f=i.agent?createInvocationTools(d,u,n.authenticator===`none`&&n.principalType===`anonymous`):[],p=i.tools||i.skills?await t.describe():void 0,m=i.tools&&p!==void 0?createPublishedTools({invokeTool:t.invokeTool,principals:r,reserved:new Set(f.map(e=>e.name)),tools:p.tools}):[],h=[];if(i.tools&&h.push({capabilities:{extensions:{[MCP_TOOL_SESSIONS_EXTENSION]:{}}},register(){}}),i.skills&&p!==void 0){let e=readSkillFileSource(t);if(e===void 0)return Response.json({error:`MCP requires agent route context.`},{status:500});h.push(createMcpSkillsFeature({files:e,skills:p.skills}))}return await createMcpStreamableHttpServer({authenticate:async()=>n,features:h,instructions:i.agent?MCP_SERVER_INSTRUCTIONS:void 0,name:l.agent.name,tools:i.agent||i.tools?[...f,...m]:void 0,version:resolveInstalledPackageInfo().version})(e)}const MCP_SERVER_INSTRUCTIONS=[`Each invocation is one durable agent task.`,`Call agent_start once per task and keep the returned invocationId.`,`Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.`,`If status is input_required, answer every entry in inputRequests in one agent_update call; repeating accepted answers is safe.`,`If status is authorization_required, show the user the authorization url or instructions and keep polling.`,`isError on a tool result means your call was rejected; a failed status means the task failed.`,`agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.`,`Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.`].join(` `);function createInvocationTools(e,t,n){let r=n?` On this public channel, the invocation ID is a bearer capability until workflow retention expires.`:``,i=`Starts durable work and returns an invocation handle immediately. Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, ask the user before starting again rather than retrying.${r}`;return[defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:t===void 0?i:`${t} ${i}`,inputSchema:z.strictObject({message:utf8Bounded(MAX_MESSAGE_BYTES).min(1)}),name:`agent_start`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(await e.create({auth:n.auth,message:t.message}))}}),defineMcpTool({definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},description:`Reads complete durable invocation state. Wait at least pollAfterMs between calls. Terminal statuses are completed, failed, and cancelled. input_required needs agent_update; authorization_required needs the user to follow the returned authorization.${r}`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_get`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.read({auth:n.auth,invocationId:t.invocationId})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},description:`Answers the pending input batch on an input_required invocation. Include one response per entry in inputRequests, each keyed by its requestId, in a single call; partial batches are rejected. Returns the current invocation state; repeating the same accepted answers is safe.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS),responses:z.array(MCP_INPUT_RESPONSE_SCHEMA).min(1).max(MAX_RESPONSES_PER_UPDATE)}),name:`agent_update`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredMutation(await e.update({auth:n.auth,invocationId:t.invocationId,responses:t.responses})))}}),defineMcpTool({definition:{annotations:{destructiveHint:!0,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!1},description:`Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). Safe to call repeatedly.`,inputSchema:z.strictObject({invocationId:z.string().min(1).max(MAX_ID_CHARS)}),name:`agent_cancel`,outputSchema:AGENT_INVOCATION_OUTPUT_SCHEMA},async call(t,n){return invocationResult(requiredInvocation(await e.cancel({auth:n.auth,invocationId:t.invocationId})))}})]}const INVOCATION_NOT_FOUND=`Invocation not found. It may have expired or belong to another caller.`;function requiredInvocation(e){if(e===void 0)throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND);return e}function requiredMutation(e){switch(e.type){case`success`:return e.invocation;case`conflict`:throw new McpToolOperationError(`conflict`,`${e.message} Call agent_get to read the current state before answering again.`);case`not_found`:throw new McpToolOperationError(`not_found`,INVOCATION_NOT_FOUND)}}function invocationResult(e){let t=parseJsonObject(e);return{content:[{text:JSON.stringify(t),type:`text`}],structuredContent:t}}const AUTHORIZATION_CHALLENGE_SCHEMA=z.strictObject({displayName:z.string().optional(),expiresAt:z.iso.datetime().optional(),instructions:z.string().optional(),url:z.url().optional(),userCode:z.string().optional()}),AUTHORIZATION_REQUEST_SCHEMA=z.strictObject({authorization:AUTHORIZATION_CHALLENGE_SCHEMA.optional(),description:z.string(),name:z.string(),webhookUrl:z.url().optional()}),MAX_MESSAGE_BYTES=65536,MAX_ID_CHARS=256,MAX_RESPONSES_PER_UPDATE=64;function utf8Bounded(e){let t=new TextEncoder;return z.string().refine(n=>t.encode(n).byteLength<=e,{message:`must be at most ${String(e)} bytes when UTF-8 encoded`})}const MCP_INPUT_RESPONSE_SCHEMA=inputResponseSchema.safeExtend({optionId:z.string().max(256).optional(),requestId:z.string().min(1).max(256),text:utf8Bounded(16384).optional()}),MCP_INPUT_REQUEST_SCHEMA=inputRequestSchema.safeExtend({action:z.strictObject({callId:z.string(),input:z.record(z.string(),z.json()),kind:z.literal(`tool-call`),toolName:z.string()})}),AGENT_INVOCATION_BASE_SCHEMA=z.strictObject({createdAt:z.iso.datetime(),expiresAt:z.iso.datetime().optional(),invocationId:z.string()}),AGENT_INVOCATION_OUTPUT_SCHEMA=z.discriminatedUnion(`status`,[AGENT_INVOCATION_BASE_SCHEMA.extend({pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`working`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({inputRequests:z.record(z.string(),MCP_INPUT_REQUEST_SCHEMA),result:z.json().optional(),status:z.literal(`input_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({authorizations:z.array(AUTHORIZATION_REQUEST_SCHEMA).min(1),pollAfterMs:z.number().int().nonnegative(),result:z.json().optional(),status:z.literal(`authorization_required`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({result:z.json().optional(),status:z.literal(`completed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({error:z.strictObject({code:z.number().int(),data:z.json().optional(),message:z.string()}),status:z.literal(`failed`)}),AGENT_INVOCATION_BASE_SCHEMA.extend({status:z.literal(`cancelled`)})]);export{mcpChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash,randomUUID}from"node:crypto";function inMemoryScheduleProvider(e={}){let t=new Map,n=new Map,r=new Map,i=new Set,a=new Set,o=e.now??(()=>new Date);return{kind:`in-memory`,async create(e,a){return withOperationResult(n,e.operationId,()=>{let n=scheduleKey(e,a.name);if(t.has(n))throw Error(`Schedule ${JSON.stringify(a.name)} already exists.`);let s=o().getTime(),c={createdAt:s,expression:normalizeExpression(a.expression),payload:a.payload,name:a.name,scheduleId:allocateScheduleId(e,a.name,r,i),state:a.expression.type===`single`&&Date.parse(a.expression.at)<=s?`completed
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";function inMemoryScheduleProvider(e={}){let t=new Map,n=new Map,r=new Map,i=new Set,a=new Set,o=e.now??(()=>new Date);return{kind:`in-memory`,async create(e,a){return withOperationResult(n,e.operationId,()=>{let n=scheduleKey(e,a.name);if(t.has(n))throw Error(`Schedule ${JSON.stringify(a.name)} already exists.`);let s=o().getTime(),c={createdAt:s,expression:normalizeExpression(a.expression),payload:a.payload,name:a.name,scheduleId:allocateScheduleId(e,a.name,r,i),state:a.expression.type===`single`&&Date.parse(a.expression.at)<=s?`completed`:`active`,target:e.target,updatedAt:s};return t.set(n,c),publicRecord(c)})},async list(e,n){let r=[...t.entries()].filter(([t])=>t.startsWith(collectionPrefix(e))).map(([,e])=>publicRecord(e)).sort((e,t)=>e.name.localeCompare(t.name)),i=decodeCursor(n.cursor),a=normalizeLimit(n.limit),o=r.slice(i,i+a),s=i+o.length;return{cursor:s<r.length?String(s):null,data:o}},async get(e,n){let r=t.get(scheduleKey(e,n));return r===void 0?null:publicRecord(r)},async enable(e,r){return setState(t,n,e,r,`active`,o)},async disable(e,r){return setState(t,n,e,r,`inactive`,o)},async invoke(e,r){let i=n.get(e.operationId);if(i!==void 0){e.target.deliver!==void 0&&await e.target.deliver(i);return}let s=requireSchedule(t,scheduleKey(e,r),r);if(s.state===`completed`)throw Error(`Completed schedule ${JSON.stringify(r)} cannot be invoked.`);let c=o().toISOString(),l={payload:s.payload,occurrence:{executionId:allocateOccurrenceId(e.operationId,a),name:s.name,scheduleId:s.scheduleId,scheduledAt:c}};n.set(e.operationId,l),s.target.deliver!==void 0&&await s.target.deliver(l)},async delete(e,i){return withOperationResult(n,e.operationId,()=>{let n=scheduleKey(e,i),a=t.delete(n);return a&&r.delete(n),a})}}}async function setState(e,t,n,r,i,a){return withOperationResult(t,n.operationId,()=>{let t=scheduleKey(n,r),o={...requireSchedule(e,t,r),state:i,updatedAt:a().getTime()};return e.set(t,o),publicRecord(o)})}function requireSchedule(e,t,n){let r=e.get(t);if(r===void 0)throw Error(`Schedule ${JSON.stringify(n)} was not found.`);return r}function withOperationResult(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}function allocateOccurrenceId(e,t){let n=`manual_${createHash(`sha256`).update(e).digest(`base64url`)}`,r=n,i=0;for(;t.has(r);)r=`${n}_${++i}`;return t.add(r),r}function normalizeExpression(e){if(e.type===`cron`){let t={type:`cron`,cron:e.cron.trim().replace(/\s+/gu,` `)};return e.timezone!==void 0&&(t.timezone=e.timezone),e.jitter!==void 0&&(t.jitter=e.jitter),t}let t={type:`single`,at:e.at};return e.timezone!==void 0&&(t.timezone=e.timezone),t}function publicRecord(e){return{createdAt:e.createdAt,expression:e.expression,name:e.name,scheduleId:e.scheduleId,state:e.state,updatedAt:e.updatedAt}}function collectionPrefix(e){return`${e.collection}\0${e.namespace}\0`}function scheduleKey(e,t){return`${collectionPrefix(e)}${t}`}function allocateScheduleId(e,t,n,r){let i=scheduleKey(e,t),a=n.get(i);if(a!==void 0)return a;let o;do o=`mem_${createHash(`sha256`).update(`${i}:${randomUUID()}`).digest(`hex`)}`;while(r.has(o));return n.set(i,o),r.add(o),o}function normalizeLimit(e){if(e===void 0)return 20;if(!Number.isSafeInteger(e)||e<1||e>100)throw Error(`Schedule list limit must be an integer from 1 through 100.`);return e}function decodeCursor(e){if(e===void 0)return 0;let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw Error(`Invalid schedule cursor.`);return t}export{inMemoryScheduleProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{deriveEveScheduleQueueTopic}from"#runtime/schedules/queue-namespace.js";import{inMemoryScheduleProvider}from"#public/schedules/providers/in-memory.js";const DEVELOPMENT_PROVIDER=inMemoryScheduleProvider(),CLIENT_OPTIONS=new WeakMap;function readVercelScheduleClientOptions(e){return CLIENT_OPTIONS.get(e)}function vercelScheduleProvider(e={}){if(isEveDevEnvironment())return DEVELOPMENT_PROVIDER;let client=t=>createClient(e,t),t={kind:`vercel`,async create(e,t){
|
|
1
|
+
import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{deriveEveScheduleQueueTopic}from"#runtime/schedules/queue-namespace.js";import{inMemoryScheduleProvider}from"#public/schedules/providers/in-memory.js";const DEVELOPMENT_PROVIDER=inMemoryScheduleProvider(),CLIENT_OPTIONS=new WeakMap;function readVercelScheduleClientOptions(e){return CLIENT_OPTIONS.get(e)}function vercelScheduleProvider(e={}){if(isEveDevEnvironment())return DEVELOPMENT_PROVIDER;let client=t=>createClient(e,t),t={kind:`vercel`,async create(e,t){return fromVercelSchedule(await(await client(e.abortSignal)).create({expression:toVercelExpression(t.expression),jitter:t.expression.type===`cron`?t.expression.jitter:void 0,name:t.name,namespace:e.namespace,payload:createDispatchPayload(e,t.payload),target:{topic:deriveEveScheduleQueueTopic(e.target.key)},timezone:t.expression.timezone}))},async list(e,t){let n=t.cursor?.trim()||void 0,r={namespace:e.namespace};n!==void 0&&(r.cursor=n),t.limit!==void 0&&(r.limit=t.limit);let i=await(await client(e.abortSignal)).list(r);return{cursor:i.cursor,data:i.data.map(fromVercelSchedule)}},async get(e,t){let n=await getScheduleOrNull(await client(e.abortSignal),t,e.namespace);return n===null?null:fromVercelSchedule(n)},async enable(e,t){return fromVercelSchedule(await(await client(e.abortSignal)).enable({name:t,namespace:e.namespace}))},async disable(e,t){return fromVercelSchedule(await(await client(e.abortSignal)).disable({name:t,namespace:e.namespace}))},async invoke(e,t){await(await client(e.abortSignal)).invoke({name:t,namespace:e.namespace})},async delete(e,t){try{return await(await client(e.abortSignal)).delete({name:t,namespace:e.namespace}),!0}catch(e){if(isNotFoundError(e))return!1;throw e}}};return CLIENT_OPTIONS.set(t,e),t}async function createClient(e,t){assertSupportedVercelEnvironment();let{SchedulesClient:n}=await import(`#compiled/@vercel/schedules/index.js`);t.throwIfAborted();let r=e.fetch??fetch;return new n({...e,fetch:(e,n)=>r(e,{...n,signal:t})})}function createDispatchPayload(e,t){return{eve:{application:e.target.key,collection:e.collection,version:1},payload:t}}function toVercelExpression(e){return e.type===`cron`?{type:`cron`,cron:e.cron}:{type:`single`,at:e.at}}function fromVercelSchedule(e){let t;if(e.expression.type===`cron`){let n={type:`cron`,cron:e.expression.cron,timezone:e.timezone};e.jitter!==void 0&&(n.jitter=e.jitter),t=n}else t={type:`single`,at:e.expression.at,timezone:e.timezone};return{createdAt:e.createdAt,expression:t,name:e.name,scheduleId:e.scheduleId,state:e.state,updatedAt:e.updatedAt}}async function getScheduleOrNull(e,t,n){try{return await e.get({name:t,namespace:n})}catch(e){if(isNotFoundError(e))return null;throw e}}function isNotFoundError(e){return typeof e==`object`&&!!e&&Reflect.get(e,`name`)===`SchedulesApiError`&&Reflect.get(e,`status`)===404}function assertSupportedVercelEnvironment(){if(!process.env.VERCEL?.trim())throw Error(`vercelScheduleProvider() requires a Vercel production deployment or eve dev.`);if(process.env.VERCEL_ENV!==`production`)throw Error("Vercel Schedules currently supports production deployments only. Deploy with `vercel --prod`.")}export{readVercelScheduleClientOptions,vercelScheduleProvider};
|
|
@@ -105,7 +105,6 @@ export interface ScheduleCreate<TPayload> {
|
|
|
105
105
|
readonly expression: ScheduleExpression;
|
|
106
106
|
readonly payload: TPayload;
|
|
107
107
|
readonly name: string;
|
|
108
|
-
readonly state?: ScheduleState;
|
|
109
108
|
}
|
|
110
109
|
export interface ScheduleList {
|
|
111
110
|
readonly cursor?: string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { SandboxSession } from "#public/definitions/sandbox.js";
|
|
2
2
|
import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";
|
|
3
3
|
import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sandbox-provider.js";
|
|
4
|
+
export type SandboxSessionEndReason = "completed" | "expired" | "failed";
|
|
4
5
|
export interface SandboxSessionState {
|
|
5
6
|
readonly providerName: string;
|
|
6
7
|
readonly state: SandboxPreparedArtifact;
|
|
@@ -2,7 +2,7 @@ import{resolveSelfModificationConfig}from"../../../config.js";import{isLocalSelf
|
|
|
2
2
|
|
|
3
3
|
Only when the requester explicitly names the self-modification subagent, edit whichever of /source/extensions/self-modification.ts or /source/extensions/self-modification/extension.ts exists. If neither exists, create /source/extensions/self-modification/extension.ts with write_file using this content, then make the requested model or reasoning change:
|
|
4
4
|
\`\`\`ts
|
|
5
|
-
${renderLocalSelfModificationExtension()}\`\`\``;var instructions_default=defineDynamic({events:{"session.started":()=>isLocalSelfModificationEnabled(resolveSelfModificationConfig(extension_default.config))?defineInstructions({markdown:renderInstructions([roleInstructions,sourceWorkspaceInstructions,sourceEditingInstructions,toolAuthoringInstructions,registryWorkflowInstructions,documentationInstructions,"## Local environment\n\nThe registry_add tool will complete installation for items that need no setup. In the local dev TUI, a `needs-terminal` result
|
|
5
|
+
${renderLocalSelfModificationExtension()}\`\`\``;var instructions_default=defineDynamic({events:{"session.started":()=>isLocalSelfModificationEnabled(resolveSelfModificationConfig(extension_default.config))?defineInstructions({markdown:renderInstructions([roleInstructions,sourceWorkspaceInstructions,sourceEditingInstructions,toolAuthoringInstructions,registryWorkflowInstructions,documentationInstructions,"## Local environment\n\nThe registry_add tool will complete installation for items that need no setup. In the local dev TUI, a `needs-terminal` result queues the existing setup panel, which opens after your reply and reports the setup outcome itself. Until then nothing is installed: say that setup continues in the panel and never describe the item as added, connected, or set up. In headless development, if a `needs-terminal` result includes `nextCommand`, present that exact value as the only shell command in your response. Never infer, construct, or rewrite a command: installing an item uses `eve add <item>`; `eve registry add` configures registry namespace mappings and does not install items.\n\nLocal eve dev logs are mounted read-only at /logs. Local trace segments are mounted read-only at /traces when available. For latency, failure, token, or behavior analysis, load and follow the `trace_analysis` skill. Trace searches are scoped to the invoking conversation and exclude the current investigation by default.\n\nThe application package.json is not mounted. Do not search outside /source for application files. You cannot run host binaries such as git, node, pnpm, or tsc. Use existing imports and registry_add for supported registry installations.",workingInstructions,selfModificationSubagentGuidance,`## Report results
|
|
6
6
|
|
|
7
7
|
For source-modification tasks, return a concise handoff to the caller. Use at most four short bullets covering changed paths and behavior, and any required setup or unresolved issues.
|
|
8
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{classifyCatalogEntry}from"../../../classify-registry-item.js";import{runEveAdd}from"../../../eve-add.js";import{defineLocalOnlyDynamic,resolveLocalOnly}from"../../../local-only.js";import{withSelfModificationWorkspaceLock}from"../../../../workspace-lock.js";import{loadRegistryIndex,resolveRegistryIndexUrl}from"./search_registry.js";import{defineTool}from"eve/tools";import{getLocalDevCapability}from"eve/local-dev";const localInputSchema={type:`object`,additionalProperties:!1,properties:{address:{type:`string`,minLength:1,maxLength:200,description:"Exact address of an item in the configured eve registry, for example `channel/slack` or `extension/browserbase`."}},required:[`address`]},localOutputSchema={type:`object`,additionalProperties:!1,properties:{status:{type:`string`,enum:[`installed`,`needs-terminal`,`failed`]},address:{type:`string`},title:{type:`string`},envVars:{type:`array`,items:{type:`string`},description:`Environment variables the item needs that are not set. The item is installed but will not work until the developer sets them. Never ask for or repeat their values.`},reason:{type:`string`,description:`Why the item was not installed here.`},changed:{type:`array`,items:{type:`string`},description:`Project-relative paths a failed install could not restore.`},nextCommand:{type:`string`,description:"The command that completes a `needs-terminal` item."},message:{type:`string`,description:`One-line summary to relay to the developer.`}},required:[`status`,`address`,`message`]};function unsetEnvVars(e,t=process.env){return(e.envVars??[]).filter(e=>{let n=t[e];return n===void 0||n===``})}function handoffMessage(e){if(e.interactiveClient)return{message:`${e.title}
|
|
1
|
+
import{classifyCatalogEntry}from"../../../classify-registry-item.js";import{runEveAdd}from"../../../eve-add.js";import{defineLocalOnlyDynamic,resolveLocalOnly}from"../../../local-only.js";import{withSelfModificationWorkspaceLock}from"../../../../workspace-lock.js";import{loadRegistryIndex,resolveRegistryIndexUrl}from"./search_registry.js";import{defineTool}from"eve/tools";import{getLocalDevCapability}from"eve/local-dev";const localInputSchema={type:`object`,additionalProperties:!1,properties:{address:{type:`string`,minLength:1,maxLength:200,description:"Exact address of an item in the configured eve registry, for example `channel/slack` or `extension/browserbase`."}},required:[`address`]},localOutputSchema={type:`object`,additionalProperties:!1,properties:{status:{type:`string`,enum:[`installed`,`needs-terminal`,`failed`]},address:{type:`string`},title:{type:`string`},envVars:{type:`array`,items:{type:`string`},description:`Environment variables the item needs that are not set. The item is installed but will not work until the developer sets them. Never ask for or repeat their values.`},reason:{type:`string`,description:`Why the item was not installed here.`},changed:{type:`array`,items:{type:`string`},description:`Project-relative paths a failed install could not restore.`},nextCommand:{type:`string`,description:"The command that completes a `needs-terminal` item."},message:{type:`string`,description:`One-line summary to relay to the developer.`}},required:[`status`,`address`,`message`]};function unsetEnvVars(e,t=process.env){return(e.envVars??[]).filter(e=>{let n=t[e];return n===void 0||n===``})}function handoffMessage(e){if(e.interactiveClient)return{message:`${e.title} has not been installed yet. ${e.reason} Its setup panel opens after this reply, asks for anything setup needs, and reports whether setup succeeded; tell the developer to complete it there, and do not describe ${e.title} as added, connected, or set up. Do not ask the developer to run another command.`};let t=`eve add ${e.address}`;return{message:`${e.title} was not installed. ${e.reason} Run \`${t}\` in a terminal to finish it.`,nextCommand:t}}async function addLocalRegistryItem(e,t={}){let n=(t.getCapability??getLocalDevCapability)();if(n===void 0)throw Error("Registry items can only be installed while `eve dev` is running. Report the item address to the developer instead of installing it.");let r=(await loadRegistryIndex({nowMs:Date.now(),signal:t.signal,url:resolveRegistryIndexUrl()})).find(t=>t.address===e);if(r===void 0)throw Error(`No item in the configured eve registry is published at "${e}". Check the address before trying again.`);let i=classifyCatalogEntry(r);if(i.kind===`self-modification-mount`)throw Error(i.reason);if(i.kind===`needs-terminal`){let t=handoffMessage({address:e,interactiveClient:n.interactiveClient,reason:i.reason,title:r.title});return{address:e,reason:i.reason,status:`needs-terminal`,title:r.title,...t}}let a=await withSelfModificationWorkspaceLock(`local:${n.appRoot}`,async()=>n.withSuspendedSource(()=>runEveAdd({address:e,appRoot:n.appRoot,signal:t.signal,spawn:t.spawn})));if(a.kind===`blocked`){let t=handoffMessage({address:e,interactiveClient:n.interactiveClient,reason:a.message,title:r.title});return{address:e,reason:a.message,status:`needs-terminal`,title:r.title,...t}}if(a.kind===`failed`)return a.changed===void 0?{address:e,status:`failed`,title:r.title,reason:a.message,message:a.message}:{address:e,status:`failed`,title:r.title,reason:a.message,message:a.message,changed:a.changed};let o=unsetEnvVars(r);return{address:e,envVars:[...o],message:o.length===0?`Installed ${r.title}.`:`Installed ${r.title}. It will not work until ${o.join(`, `)} ${o.length===1?`is`:`are`} set.`,status:`installed`,title:r.title}}function localRegistryAddTool(){return defineTool({description:`Install an item from the configured eve registry into this project. Items that need setup are handed to the local setup flow instead. Search first, then call this with the exact item address.`,inputSchema:localInputSchema,outputSchema:localOutputSchema,async execute(e,t){let{address:n}=e;if(typeof n!=`string`||n.length===0)throw Error(`address must be an exact item address from the configured eve registry.`);return await addLocalRegistryItem(n,{signal:t.abortSignal})}})}function resolveRegistryAddTool(e){return resolveLocalOnly(e,localRegistryAddTool())}var registry_add_default=defineLocalOnlyDynamic(localRegistryAddTool());export{addLocalRegistryItem,registry_add_default as default,handoffMessage,resolveRegistryAddTool,unsetEnvVars};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SetupPrerequisite } from "#setup/integrations/shared/prerequisite.js";
|
|
1
2
|
import type { Prompter } from "#setup/prompter.js";
|
|
2
3
|
import { detectDeployment } from "#setup/project-resolution.js";
|
|
3
4
|
import type { RegistrySetupCompletion, RegistrySetupFact } from "#setup/registry-setup-protocol.js";
|
|
@@ -12,11 +13,16 @@ export type RegistrySessionOutcome = {
|
|
|
12
13
|
facts: readonly RegistrySetupFact[];
|
|
13
14
|
output: readonly string[];
|
|
14
15
|
}
|
|
15
|
-
/** Files were added, but the item's setup was cancelled or
|
|
16
|
+
/** Files were added, but the item's setup was cancelled, skipped, or failed. */
|
|
16
17
|
| {
|
|
17
18
|
kind: "incomplete";
|
|
18
19
|
title: string;
|
|
20
|
+
/** Registry address, used to resume setup without reinstalling. */
|
|
21
|
+
address: string;
|
|
19
22
|
resumeCommand: string;
|
|
23
|
+
/** Why setup failed; absent when it was cancelled or skipped. */
|
|
24
|
+
reason?: string;
|
|
25
|
+
prerequisite?: SetupPrerequisite;
|
|
20
26
|
}
|
|
21
27
|
/** User-facing installation error, including any actionable follow-up lines. */
|
|
22
28
|
| {
|
|
@@ -38,7 +44,9 @@ export interface RegistrySessionResult {
|
|
|
38
44
|
}
|
|
39
45
|
interface RegistrySession {
|
|
40
46
|
add(title: string, output: readonly string[], setup?: RegistrySetupCompletion): void;
|
|
41
|
-
addIncomplete(title: string,
|
|
47
|
+
addIncomplete(title: string, incomplete: Omit<Extract<RegistrySessionOutcome, {
|
|
48
|
+
kind: "incomplete";
|
|
49
|
+
}>, "kind" | "title">): void;
|
|
42
50
|
addFailure(title: string, message: string): void;
|
|
43
51
|
addCancellation(title: string): void;
|
|
44
52
|
result(deployed?: "production"): RegistrySessionResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./deploy.js";import"#setup/project-resolution.js";function createRegistrySession(e){let t=[],n=!1;function result(e){let n={outcomes:[...t]};return e!==void 0&&(n.deployed=e),n}return{add(e,r,i={facts:[]}){t.push({kind:`installed`,title:e,facts:i.facts,output:r}),n||=i.deploymentRequired===!0},addIncomplete(e,n){t.push({kind:`incomplete`,title:e
|
|
1
|
+
import"./deploy.js";import"#setup/project-resolution.js";function createRegistrySession(e){let t=[],n=!1;function result(e){let n={outcomes:[...t]};return e!==void 0&&(n.deployed=e),n}return{add(e,r,i={facts:[]}){t.push({kind:`installed`,title:e,facts:i.facts,output:r}),n||=i.deploymentRequired===!0},addIncomplete(e,n){t.push({kind:`incomplete`,title:e,...n})},addFailure(e,n){t.push({kind:`failed`,title:e,message:n})},addCancellation(e){t.push({kind:`cancelled`,title:e})},result,async continueAfterInstall(t){if(!n)return result();let r=await e.detectDeployment(t.appRoot,{signal:t.signal}),i=r.state===`linked`||r.state===`deployed`;for(t.prompter.replaceContent?.();;){if(await t.prompter.select({message:`What would you like to do next?`,initialValue:`finish`,hintLayout:`inline`,options:[...i?[{value:`deploy`,label:`Deploy`}]:[],{value:`finish`,label:`Start chatting`}]})===`finish`)return result();if(await t.prompter.select({message:`Deploy to prod?`,initialValue:`yes`,options:[{value:`yes`,label:`Yes`},{value:`back`,label:`Back`}]})!==`back`)return result((await e.runDeployFlow({appRoot:t.appRoot,prompter:t.prompter,signal:t.signal,interactive:!0})).kind===`deployed`?`production`:void 0)}}}}export{createRegistrySession};
|
|
@@ -22,6 +22,8 @@ export declare function runRegistryFlow(input: {
|
|
|
22
22
|
signal?: AbortSignal;
|
|
23
23
|
/** Registry item supplied by `/add <item>`, installed directly. */
|
|
24
24
|
initialAddress?: string;
|
|
25
|
+
/** Rerun the item's setup only; its source is already installed. */
|
|
26
|
+
skipInstall?: boolean;
|
|
25
27
|
onScreen?: (input: {
|
|
26
28
|
screen: "registry_install";
|
|
27
29
|
registrySelectedCount?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRegistrySession}from"./registry-session.js";import{WizardCancelledError}from"#setup/step.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{withSpinner}from"#setup/with-spinner.js";function label(e){return e.name}var RegistryFlowFailedError=class extends Error{completed;constructor(e,t){super(e instanceof Error?e.message:String(e),{cause:e}),this.name=`RegistryFlowFailedError`,this.completed=t}};function hasSettledOutcomes(e){return e!==void 0&&e.outcomes.length>0}async function runRegistryFlow(e){let t;try{let n=e.initialAddress?.trim(),r;if(n!==void 0&&n!==``)r=[{address:n,name:n,source:`Registry`}];else{let t=e.deps?.browseRegistryCatalog??(await import(`#cli/commands/registry.js`)).browseRegistryCatalog,n=await withSpinner(e.prompter,`Loading registry…`,()=>t(e.appRoot)),i=[...n.items],a=await e.prompter.select({message:`Add to your agent`,search:!0,options:i.map(e=>({value:e.address,label:e.name,hint:e.address,keywords:[e.title??``,e.description??``]})),notices:n.errors.map(e=>({tone:`warning`,text:`${e.registry}: ${e.message}`}))}),o=i.find(e=>e.address===a);if(o===void 0)throw Error(`That registry item is no longer available. Run /add to try again.`);r=[o]}let i=e.deps?.installRegistryItem??(await import(`#cli/commands/registry.js`)).installRegistryItem,a=e.installRoot??e.appRoot,o=e.deps?.detectDeployment??(await import(`#setup/project-resolution.js`)).detectDeployment,s=e.deps?.runDeployFlow??(await import(`./deploy.js`)).runDeployFlow;t=createRegistrySession({detectDeployment:o,runDeployFlow:s}),e.onScreen?.({screen:`registry_install`});let c=t;for(let[t,n]of r.entries()){e.signal?.throwIfAborted(),e.onItemStart?.(n,t,r.length);try{let install=(t=e.signal)=>i(a,n.address,{silent:!0,prompter:e.prompter,signal:t}),run=()=>e.runItem===void 0?install():e.runItem(install),t=await(e.prompter.withExclusiveTerminal?.(run)??run());t.setupIncomplete===void 0?c.add(label(n),t.output,t.setup):c.addIncomplete(label(n),t.setupIncomplete
|
|
1
|
+
import{createRegistrySession}from"./registry-session.js";import{WizardCancelledError}from"#setup/step.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{withSpinner}from"#setup/with-spinner.js";function label(e){return e.name}var RegistryFlowFailedError=class extends Error{completed;constructor(e,t){super(e instanceof Error?e.message:String(e),{cause:e}),this.name=`RegistryFlowFailedError`,this.completed=t}};function hasSettledOutcomes(e){return e!==void 0&&e.outcomes.length>0}async function runRegistryFlow(e){let t;try{let n=e.initialAddress?.trim(),r;if(n!==void 0&&n!==``)r=[{address:n,name:n,source:`Registry`}];else{let t=e.deps?.browseRegistryCatalog??(await import(`#cli/commands/registry.js`)).browseRegistryCatalog,n=await withSpinner(e.prompter,`Loading registry…`,()=>t(e.appRoot)),i=[...n.items],a=await e.prompter.select({message:`Add to your agent`,search:!0,options:i.map(e=>({value:e.address,label:e.name,hint:e.address,keywords:[e.title??``,e.description??``]})),notices:n.errors.map(e=>({tone:`warning`,text:`${e.registry}: ${e.message}`}))}),o=i.find(e=>e.address===a);if(o===void 0)throw Error(`That registry item is no longer available. Run /add to try again.`);r=[o]}let i=e.deps?.installRegistryItem??(await import(`#cli/commands/registry.js`)).installRegistryItem,a=e.installRoot??e.appRoot,o=e.deps?.detectDeployment??(await import(`#setup/project-resolution.js`)).detectDeployment,s=e.deps?.runDeployFlow??(await import(`./deploy.js`)).runDeployFlow;t=createRegistrySession({detectDeployment:o,runDeployFlow:s}),e.onScreen?.({screen:`registry_install`});let c=t;for(let[t,n]of r.entries()){e.signal?.throwIfAborted(),e.onItemStart?.(n,t,r.length);try{let install=(t=e.signal)=>i(a,n.address,{silent:!0,...e.skipInstall===!0&&{skipInstall:!0},prompter:e.prompter,signal:t}),run=()=>e.runItem===void 0?install():e.runItem(install),t=await(e.prompter.withExclusiveTerminal?.(run)??run());t.setupIncomplete===void 0?c.add(label(n),t.output,t.setup):c.addIncomplete(label(n),{address:n.address,...t.setupIncomplete})}catch(t){if(e.signal?.throwIfAborted(),t instanceof WizardCancelledError){c.addCancellation(label(n));continue}if(t instanceof HumanActionRequiredError)throw t;let r=(t instanceof Error?t.message:String(t)).trim()||`Installation failed.`;c.addFailure(label(n),r)}}return{kind:`done`,result:await c.continueAfterInstall({appRoot:e.appRoot,prompter:e.prompter,signal:e.signal})}}catch(e){if(e instanceof WizardCancelledError){let e=t?.result();return hasSettledOutcomes(e)?{kind:`done`,result:{...e,cancelled:!0}}:{kind:`cancelled`}}let n=t?.result();throw hasSettledOutcomes(n)?new RegistryFlowFailedError(e,n):e}}export{RegistryFlowFailedError,runRegistryFlow};
|
|
@@ -15,3 +15,11 @@ export declare class SetupPrerequisiteRequired extends Error {
|
|
|
15
15
|
readonly prerequisite: SetupPrerequisite;
|
|
16
16
|
constructor(prerequisite: SetupPrerequisite);
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* The structured prerequisite behind a setup error, if any. Shared Vercel
|
|
20
|
+
* provisioning steps throw {@link HumanActionRequiredError} (for example
|
|
21
|
+
* `vercel login`); setup callers report it as a command prerequisite so the
|
|
22
|
+
* action survives process and protocol boundaries instead of being flattened
|
|
23
|
+
* into an unactionable message.
|
|
24
|
+
*/
|
|
25
|
+
export declare function setupPrerequisiteOf(error: unknown): SetupPrerequisite | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var SetupPrerequisiteRequired=class extends Error{prerequisite;constructor(e){super(e.message),this.name=`SetupPrerequisiteRequired`,this.prerequisite=e}};export{SetupPrerequisiteRequired};
|
|
1
|
+
import{HumanActionRequiredError}from"../../human-action.js";var SetupPrerequisiteRequired=class extends Error{prerequisite;constructor(e){super(e.message),this.name=`SetupPrerequisiteRequired`,this.prerequisite=e}};function setupPrerequisiteOf(e){if(e instanceof SetupPrerequisiteRequired)return e.prerequisite;if(e instanceof HumanActionRequiredError)return{kind:`command`,code:e.action.kind,message:e.action.reason,command:e.action.command}}export{SetupPrerequisiteRequired,setupPrerequisiteOf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{InteractionRequired,InvalidAnswerError}from"./ask-signals.js";import{
|
|
1
|
+
import{InteractionRequired,InvalidAnswerError}from"./ask-signals.js";import{setupPrerequisiteOf}from"./integrations/shared/prerequisite.js";import"./ask.js";import{WizardCancelledError}from"./step.js";import{setupQuestionToWire}from"./setup-question-wire.js";import"./registry-setup-protocol.js";function send(e,t){if(e.send===void 0||!e.connected)throw Error(`The registry setup host disconnected.`);e.send(t)}function registrySetupBlocker(e){if(e instanceof InteractionRequired)return{status:`input_required`,question:setupQuestionToWire(e.question)};if(e instanceof InvalidAnswerError)return{status:`input_required`,question:setupQuestionToWire(e.question),issue:{code:`invalid_answer`,message:e.message}};let t=setupPrerequisiteOf(e);return t===void 0?void 0:{status:`prerequisite_required`,prerequisite:t}}function registrySetupError(e){if(!(e instanceof Error))return{message:String(e)};let t=e.stack?.split(`
|
|
2
2
|
`).slice(1).map(e=>e.trim()).filter(Boolean);return t===void 0||t.length===0?{message:e.message}:{message:e.message,details:t}}function createRegistrySetupClient(e={}){let t=e.process??process;if(t.send===void 0||process.env.EVE_SETUP_PROTOCOL===void 0)return;let n=new AbortController;e.signal!==void 0&&e.signal.addEventListener(`abort`,()=>n.abort(e.signal?.reason),{once:!0});let r=1,i=new Map,onMessage=e=>{if(e.type===`cancel`){n.abort(new WizardCancelledError);for(let e of i.values())e({type:`cancel`});i.clear();return}i.get(e.id)?.(e)};t.on(`message`,onMessage),send(t,{type:`ready`,version:2});async function prompt(e){n.signal.throwIfAborted();let a=r++,o=await new Promise(n=>{i.set(a,n),send(t,{type:`prompt`,id:a,prompt:e})});if(i.delete(a),o.type===`cancel`||o.cancelled===!0)throw new WizardCancelledError;return o.value}async function validatedText(e,t){let n=t.notices;for(;;){let r=await prompt({kind:e,message:t.message,placeholder:t.placeholder,defaultValue:t.defaultValue,notices:n}),i=t.validate?.(r);if(i===void 0)return r;n=[{tone:`error`,text:i}]}}function select(e){return prompt({kind:`select`,options:e})}let a={text:e=>validatedText(`text`,e),password:e=>validatedText(`password`,e),select,async selectEditable(e){let t=await prompt({kind:`editable-select`,options:{...e,editable:{value:e.editable.value,defaultValue:e.editable.defaultValue}}});if(t.kind===`selected`)return{kind:`selected`,value:t.value};let n=e.editable.validate?.(t.text);if(n!==void 0)throw Error(n);return{kind:`edited`,value:t.value,text:t.text}},acknowledge:e=>prompt({kind:`acknowledge`,options:e}),awaitChoice(e){let n=r++;return{choice:new Promise((r,a)=>{i.set(n,e=>{i.delete(n),e.type===`cancel`||e.cancelled===!0?a(new WizardCancelledError):r(e.value)}),send(t,{type:`prompt`,id:n,prompt:{kind:`choice`,options:e}})}),close:()=>{i.delete(n),send(t,{type:`close-prompt`,id:n})}}},note(e,n,r){send(t,{type:`note`,message:e,title:n,tone:r?.tone})},intro(e,n){send(t,{type:`intro`,text:e,subtitle:n})},outro(e){send(t,{type:`outro`,text:e})},log:{message:e=>send(t,{type:`log`,level:`message`,text:e}),info:e=>send(t,{type:`log`,level:`info`,text:e}),success:e=>send(t,{type:`log`,level:`success`,text:e}),warning:e=>send(t,{type:`log`,level:`warning`,text:e}),error:e=>send(t,{type:`log`,level:`error`,text:e}),commandOutput:e=>send(t,{type:`log`,level:`commandOutput`,text:e}),spinner(e){let n=r++;return send(t,{type:`status`,id:n,status:e}),{stop:()=>send(t,{type:`status`,id:n})}}}},o=!1,finish=e=>{o||(o=!0,send(t,{type:`result`,outcome:e}),t.off(`message`,onMessage),t.disconnect?.())};return{prompter:a,signal:n.signal,complete:(e={facts:[]})=>finish({kind:`completed`,...e}),cancel:()=>finish({kind:`cancelled`}),fail(e){let t=registrySetupBlocker(e);finish(t===void 0?{kind:`failed`,error:registrySetupError(e)}:{kind:`blocked`,blocker:t})}}}export{createRegistrySetupClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.128`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{parseChatGptModelSelection}from"../../../shared/chatgpt-model.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{DEFAULT_CONNECT_PACKAGE_VERSION,resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_CHANNEL_TEMPLATES}from"./web-template.js";import{AGENT_INSTRUCTIONS_TEMPLATE}from"./instructions-template.js";import{SCAFFOLDED_AGENT_PATHS}from"./agent-paths.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.128`,DEFAULT_ZOD_PACKAGE_VERSION=`4.5.4`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.75.0`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e,t){return{[SCAFFOLDED_AGENT_PATHS.config]:renderAgentTemplate(e,t),[SCAFFOLDED_AGENT_PATHS.channel]:WEB_CHANNEL_TEMPLATES.default,[SCAFFOLDED_AGENT_PATHS.instructions]:AGENT_INSTRUCTIONS_TEMPLATE}}function renderAgentTemplate(e,t){let n=parseChatGptModelSelection(e);return n===void 0?BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t)):`import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(n)}),\n${reasoningTemplateLine(t)}});\n`}function reasoningTemplateLine(e){return e===void 0||e===`provider-default`?``:` reasoning: "${e}",\n`}function renderTemplate(e,t){return e===BASE_AGENT_TEMPLATE&&parseChatGptModelSelection(t.model)!==void 0?renderAgentTemplate(t.model,t.reasoning):e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_REASONING__`,reasoningTemplateLine(t.reasoning)).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WriteFileExistsError}from"./files.js";import{CURRENT_DIRECTORY_PROJECT_NAME,byokProviderEnvVar,isEveProject,scaffoldBaseProject}from"./create/project.js";import{scaffoldExtensionProject}from"./create/extension.js";import{DEFAULT_SLACK_CONNECTOR_SLUG,SLACK_CHANNEL_DEFAULT_ROUTE,deriveSlackConnectorSlug,ensureChannel,hasVercelHostFramework,isNextJsProject,listAuthoredChannels,normalizeSlackConnectorSlug,resolveVercelHostFrameworkPreset}from"./update/channels.js";import{SCAFFOLDABLE_CHANNELS}from"./channels-catalog.js";import{CONNECTION_CATALOG,CUSTOM_CONNECTION_SLUG,SUPPORTED_PROTOCOLS,catalogSlugs,effectiveProtocols,endpointForProtocol,getCatalogEntry,isValidConnectionSlug}from"./connections/catalog.js";import{ensureConnection,ensureConnectionDependencies,listAuthoredConnections}from"./update/connections.js";import{ensurePackageDependencies}from"./update/dependencies.js";
|
|
1
|
+
import{HumanActionRequiredError}from"../human-action.js";import{WriteFileExistsError}from"./files.js";import{CURRENT_DIRECTORY_PROJECT_NAME,byokProviderEnvVar,isEveProject,scaffoldBaseProject}from"./create/project.js";import{scaffoldExtensionProject}from"./create/extension.js";import{DEFAULT_SLACK_CONNECTOR_SLUG,SLACK_CHANNEL_DEFAULT_ROUTE,deriveSlackConnectorSlug,ensureChannel,hasVercelHostFramework,isNextJsProject,listAuthoredChannels,normalizeSlackConnectorSlug,resolveVercelHostFrameworkPreset}from"./update/channels.js";import{SCAFFOLDABLE_CHANNELS}from"./channels-catalog.js";import{CONNECTION_CATALOG,CUSTOM_CONNECTION_SLUG,SUPPORTED_PROTOCOLS,catalogSlugs,effectiveProtocols,endpointForProtocol,getCatalogEntry,isValidConnectionSlug}from"./connections/catalog.js";import{ensureConnection,ensureConnectionDependencies,listAuthoredConnections}from"./update/connections.js";import{ensurePackageDependencies}from"./update/dependencies.js";export{CONNECTION_CATALOG,CURRENT_DIRECTORY_PROJECT_NAME,CUSTOM_CONNECTION_SLUG,DEFAULT_SLACK_CONNECTOR_SLUG,HumanActionRequiredError,SCAFFOLDABLE_CHANNELS,SLACK_CHANNEL_DEFAULT_ROUTE,SUPPORTED_PROTOCOLS,WriteFileExistsError,byokProviderEnvVar,catalogSlugs,deriveSlackConnectorSlug,effectiveProtocols,endpointForProtocol,ensureChannel,ensureConnection,ensureConnectionDependencies,ensurePackageDependencies,getCatalogEntry,hasVercelHostFramework,isEveProject,isNextJsProject,isValidConnectionSlug,listAuthoredChannels,listAuthoredConnections,normalizeSlackConnectorSlug,resolveVercelHostFrameworkPreset,scaffoldBaseProject,scaffoldExtensionProject};
|
|
@@ -31,8 +31,7 @@ export declare function assertNewProjectNameAvailable(projectRoot: string, team:
|
|
|
31
31
|
* The Vercel auth state, read-only. `cli-missing` (ENOENT) and `unavailable` (a
|
|
32
32
|
* transient network/API fault) are each kept distinct from `logged-out` so a
|
|
33
33
|
* caller never tells the user to log in when the real cause is a missing CLI or
|
|
34
|
-
* an unreachable network.
|
|
35
|
-
* not-authenticated diagnostic.
|
|
34
|
+
* an unreachable network.
|
|
36
35
|
*/
|
|
37
36
|
export type VercelAuthStatus = "authenticated" | "logged-out" | "cli-missing" | "unavailable";
|
|
38
37
|
export declare function getVercelAuthStatus(projectRoot: string, options?: VercelProjectOperationOptions): Promise<VercelAuthStatus>;
|
|
Binary file
|
|
@@ -73,10 +73,17 @@ export interface SandboxProviderSessionContext {
|
|
|
73
73
|
export interface SandboxProviderHandle<Session extends SandboxSession = SandboxSession> {
|
|
74
74
|
readonly sandbox: Session;
|
|
75
75
|
onRuntimeShutdown(): Promise<void>;
|
|
76
|
-
|
|
77
|
-
|
|
76
|
+
onSandboxDelete(options?: SandboxDeleteOptions): Promise<void>;
|
|
77
|
+
onSandboxStop(): Promise<void>;
|
|
78
78
|
}
|
|
79
79
|
export interface SandboxProviderImplementation<OpenOptions extends object | undefined, PreparedArtifact extends SandboxPreparedArtifact, SessionState, Session extends SandboxSession = SandboxSession> {
|
|
80
|
+
/**
|
|
81
|
+
* Permanently releases resources owned by a durable session after its terminal outcome.
|
|
82
|
+
* Implementations must be idempotent because the cleanup step may retry.
|
|
83
|
+
*/
|
|
84
|
+
onSessionEnd?(context: SandboxProviderSessionContext, artifact: Readonly<PreparedArtifact>, state: Readonly<SessionState>, options: {
|
|
85
|
+
readonly reason: "completed" | "expired" | "failed";
|
|
86
|
+
}): Promise<void>;
|
|
80
87
|
prepare(context: SandboxProviderPrepareContext): Promise<PreparedArtifact>;
|
|
81
88
|
resume(context: SandboxProviderSessionContext, artifact: Readonly<PreparedArtifact>, state: Readonly<SessionState>): Promise<SandboxProviderHandle<Session>>;
|
|
82
89
|
start(context: SandboxProviderSessionContext, options: Readonly<OpenOptions> | undefined, artifact: Readonly<PreparedArtifact>): Promise<{
|
|
@@ -3,7 +3,8 @@ import type { ChannelAdapter } from "#channel/adapter.js";
|
|
|
3
3
|
* Framework adapter that bridges a child subagent session to its
|
|
4
4
|
* parent.
|
|
5
5
|
*
|
|
6
|
-
* It proxies child `input.requested` events upward so the parent channel
|
|
7
|
-
*
|
|
6
|
+
* It proxies child `input.requested` events upward so the parent channel can
|
|
7
|
+
* render HITL prompts and route responses back down to the child, and the
|
|
8
|
+
* `input.resolved` of requests only the child can close.
|
|
8
9
|
*/
|
|
9
10
|
export declare const SUBAGENT_ADAPTER: ChannelAdapter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createErrorId,createLogger}from"#internal/logging.js";import{ContinuationTokenKey,SessionIdKey,SessionInboxKey}from"#context/keys.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#subagents/adapter-state.js";const log=createLogger(`execution.subagent-adapter`),SUBAGENT_ADAPTER={kind:SUBAGENT_ADAPTER_KIND,async"approval.candidate"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`approval.candidate`},t)},async"approval.settled"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`approval.settled`},t)},async"authorization.required"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.required`},t)},async"authorization.completed"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.completed`},t)},async"input.requested"(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentInputRequestStep({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(ContinuationTokenKey),childSessionId:t.ctx.require(SessionIdKey),childSessionInbox:t.ctx.get(SessionInboxKey),inputSource:t.inputSource,event:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},kind:`subagent-input-request`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}};async function forwardSubagentAuthorizationEvent(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentAuthorizationEventStep({hookPayload:{callId:n.callId,childSessionId:t.ctx.require(SessionIdKey),event:e,kind:`subagent-authorization-event`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}async function forwardSubagentAuthorizationEventStep(e){"use step";try{await resumeParentHook(e.parentContinuationToken,e.hookPayload)}catch(t){let n=createErrorId();throw log.warn(`failed to forward subagent authorization event to parent`,{callId:e.hookPayload.callId,childSessionId:e.hookPayload.childSessionId,errorId:n,eventType:e.hookPayload.event.type,parentContinuationToken:e.parentContinuationToken,subagentName:e.hookPayload.subagentName,error:t}),t}}async function forwardSubagentInputRequestStep(e){"use step";try{await resumeParentHook(e.parentContinuationToken,e.hookPayload)}catch(t){let n=createErrorId();throw log.warn(`failed to forward proxied HITL batch to parent`,{callId:e.hookPayload.callId,childContinuationToken:e.hookPayload.childContinuationToken,childSessionId:e.hookPayload.childSessionId,errorId:n,parentContinuationToken:e.parentContinuationToken,subagentName:e.hookPayload.subagentName,error:t}),t}}async function resumeParentHook(e,t){let{resumeHook:n}=await import(`#internal/workflow/runtime.js`);await n(e,t)}export{SUBAGENT_ADAPTER};
|
|
1
|
+
import{createErrorId,createLogger}from"#internal/logging.js";import{ContinuationTokenKey,SessionIdKey,SessionInboxKey}from"#context/keys.js";import{resolvedForParent}from"#harness/proxy-input-requests.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#subagents/adapter-state.js";const log=createLogger(`execution.subagent-adapter`),SUBAGENT_ADAPTER={kind:SUBAGENT_ADAPTER_KIND,async"approval.candidate"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`approval.candidate`},t)},async"approval.settled"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`approval.settled`},t)},async"authorization.required"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.required`},t)},async"authorization.completed"(e,t){await forwardSubagentAuthorizationEvent({data:e,type:`authorization.completed`},t)},async"input.resolved"(e,t){let n=resolvedForParent(e);n!==void 0&&await forwardSubagentAuthorizationEvent({data:n,type:`input.resolved`},t)},async"input.requested"(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentInputRequestStep({hookPayload:{callId:n.callId,childContinuationToken:t.ctx.require(ContinuationTokenKey),childSessionId:t.ctx.require(SessionIdKey),childSessionInbox:t.ctx.get(SessionInboxKey),inputSource:t.inputSource,event:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},kind:`subagent-input-request`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}};async function forwardSubagentAuthorizationEvent(e,t){let n=t.state;isSubagentAdapterState(n)&&await forwardSubagentAuthorizationEventStep({hookPayload:{callId:n.callId,childSessionId:t.ctx.require(SessionIdKey),event:e,kind:`subagent-authorization-event`,subagentName:n.subagentName},parentContinuationToken:n.parentContinuationToken})}async function forwardSubagentAuthorizationEventStep(e){"use step";try{await resumeParentHook(e.parentContinuationToken,e.hookPayload)}catch(t){let n=createErrorId();throw log.warn(`failed to forward subagent authorization event to parent`,{callId:e.hookPayload.callId,childSessionId:e.hookPayload.childSessionId,errorId:n,eventType:e.hookPayload.event.type,parentContinuationToken:e.parentContinuationToken,subagentName:e.hookPayload.subagentName,error:t}),t}}async function forwardSubagentInputRequestStep(e){"use step";try{await resumeParentHook(e.parentContinuationToken,e.hookPayload)}catch(t){let n=createErrorId();throw log.warn(`failed to forward proxied HITL batch to parent`,{callId:e.hookPayload.callId,childContinuationToken:e.hookPayload.childContinuationToken,childSessionId:e.hookPayload.childSessionId,errorId:n,parentContinuationToken:e.parentContinuationToken,subagentName:e.hookPayload.subagentName,error:t}),t}}async function resumeParentHook(e,t){let{resumeHook:n}=await import(`#internal/workflow/runtime.js`);await n(e,t)}export{SUBAGENT_ADAPTER};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{inputRequestSchema}from"#shared/input.js";import{jsonValueSchema}from"#shared/json-schemas.js";import{
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{inputRequestSchema,inputResponseSchema}from"#shared/input.js";import{jsonValueSchema}from"#shared/json-schemas.js";import{resumeHook}from"#internal/workflow/runtime.js";import{renameLegacyTaskCallback}from"#execution/legacy-remote-agent/protocol.js";import{agentTurnOutcomeWithCostSchema}from"#shared/agent-turn-outcome.js";const sessionInputCallbackSchema=z.object({callId:z.string().min(1),childContinuationToken:z.string().min(1),childSessionId:z.string().min(1),childSessionInbox:z.object({sessionId:z.string().min(1)}).strict().optional(),inputSource:z.string().min(1).optional(),remote:z.object({name:z.string().min(1),url:z.string().url(),forwardPrincipal:z.boolean().optional(),sessionId:z.string().min(1),resolverId:z.string().min(1).optional()}).strict().optional(),kind:z.literal(`subagent-input-request`),subagentName:z.string().min(1),event:z.object({requests:z.array(inputRequestSchema).min(1),sequence:z.number(),stepIndex:z.number(),taskId:z.string().optional(),turnId:z.string()})}),sessionAuthorizationCallbackSchema=z.object({callId:z.string().min(1),childSessionId:z.string().min(1),kind:z.literal(`subagent-authorization-event`),subagentName:z.string().min(1),event:z.discriminatedUnion(`type`,[z.object({type:z.literal(`approval.candidate`),data:z.object({candidateId:z.string(),outcome:z.enum([`pending`,`rejected`,`failed`,`timed-out`,`stale`]),requestId:z.string(),responderPrincipalId:z.string(),reason:z.string().optional(),sequence:z.number(),stepIndex:z.number(),turnId:z.string()}).passthrough()}),z.object({type:z.literal(`approval.settled`),data:z.object({outcome:z.enum([`approved`,`cancelled`]),requestId:z.string(),responderPrincipalId:z.string(),sequence:z.number(),stepIndex:z.number(),turnId:z.string()}).passthrough()}),z.object({type:z.literal(`input.resolved`),data:z.object({resolutions:z.array(z.object({kind:z.enum([`question`,`session-limit`,`tool-approval`]),outcome:z.enum([`answered`,`approved`,`cancelled`,`denied`,`ignored`,`invalid`]),requestId:z.string(),response:inputResponseSchema.optional()}).passthrough()),sequence:z.number(),stepIndex:z.number(),turnId:z.string()}).passthrough()}),z.object({type:z.literal(`authorization.required`),data:z.object({description:z.string(),name:z.string(),sequence:z.number(),stepIndex:z.number(),turnId:z.string(),webhookUrl:z.string().optional(),attemptId:z.string().optional(),taskId:z.string().optional(),principalId:z.string().optional()}).passthrough()}),z.object({type:z.literal(`authorization.completed`),data:z.object({name:z.string(),outcome:z.enum([`authorized`,`declined`,`failed`,`timed-out`]),sequence:z.number(),stepIndex:z.number(),turnId:z.string(),attemptId:z.string().optional(),taskId:z.string().optional(),principalId:z.string().optional()}).passthrough()})])}),sessionResultCallbackSchema=z.discriminatedUnion(`kind`,[z.object({callId:z.string().min(1),kind:z.literal(`turn.completed`),outcome:agentTurnOutcomeWithCostSchema,output:jsonValueSchema.optional(),subagentName:z.string().min(1)}),z.object({callId:z.string().min(1),error:jsonValueSchema,kind:z.literal(`turn.failed`),outcome:agentTurnOutcomeWithCostSchema,subagentName:z.string().min(1)})]);async function handleSessionCallbackRequest(e,t){let n=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let r;try{r=renameLegacyTaskCallback(await e.json())}catch{return Response.json({error:`Invalid JSON body.`,ok:!1},{status:400})}let i=callbackKind(r),a=i===`subagent-input-request`?sessionInputCallbackSchema.safeParse(r):i===`subagent-authorization-event`?sessionAuthorizationCallbackSchema.safeParse(r):void 0;if(a!==void 0&&!a.success)return Response.json({error:`Invalid session input callback.`,ok:!1},{status:400});let o=a===void 0?projectSessionCallbackResult(r):void 0;if(o instanceof Response)return o;try{await resumeHook(n,a?.success?a.data:{kind:`runtime-action-result`,results:[o]})}catch{return Response.json({error:`Session callback not pending.`,ok:!1},{status:404})}return Response.json({ok:!0},{status:202})}function callbackKind(e){if(typeof e==`object`&&e)return Reflect.get(e,`kind`)}function projectSessionCallbackResult(e){if(typeof e!=`object`||!e)return Response.json({error:`Expected a JSON object.`,ok:!1},{status:400});let t=callbackKind(e);if(t!==`turn.completed`&&t!==`turn.failed`)return Response.json({error:`Unsupported callback kind.`,ok:!1},{status:400});let n=sessionResultCallbackSchema.safeParse(e);if(!n.success)return Response.json({error:`Invalid session result callback.`,ok:!1},{status:400});let r=n.data;return r.kind===`turn.completed`?{callId:r.callId,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.output??``,subagentName:r.subagentName,usage:r.outcome.usageDelta}:{callId:r.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:r.outcome,output:r.error,subagentName:r.subagentName}}export{handleSessionCallbackRequest};
|
|
@@ -45,9 +45,10 @@ export interface RoutedDeliverPayload {
|
|
|
45
45
|
/**
|
|
46
46
|
* Splits a deliver payload into parent-local and proxied-child buckets.
|
|
47
47
|
*
|
|
48
|
-
* With `resolveMessage`, a plain-text message is also resolved against
|
|
49
|
-
*
|
|
50
|
-
*
|
|
48
|
+
* With `resolveMessage`, a plain-text message is also resolved against the
|
|
49
|
+
* first open request when a child asked it, whether a `ctx.ask()` question, a
|
|
50
|
+
* tool approval, or a session-limit prompt: a matching option or permitted free
|
|
51
|
+
* text answers that one request, and the message is consumed along with its
|
|
51
52
|
* `context`. Otherwise the message stays with the parent.
|
|
52
53
|
*/
|
|
53
54
|
export declare function routeDeliverPayload(input: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inputTextKey,readAnswerText}from"#internal/input-text.js";import{firstOpenInput}from"#harness/open-input-request.js";import{resolveTextToResponse}from"#channel/resolve-text.js";import{storedProjection}from"#harness/session-machine/view.js";import{getProxyInputRequests}from"#harness/proxy-input-requests.js";import{resolveInputOutcome}from"#harness/input-request-resolution.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/hitl/budget-request.js";const CONSUMED_MESSAGE_KEYS=new Set([`context`,`message`,inputTextKey]);function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),routable=(t,n)=>n!==void 0&&e.allowRoute?.(t,n)!==!1,n=
|
|
1
|
+
import{inputTextKey,readAnswerText}from"#internal/input-text.js";import{firstOpenInput}from"#harness/open-input-request.js";import{resolveTextToResponse}from"#channel/resolve-text.js";import{storedProjection}from"#harness/session-machine/view.js";import{getProxyInputRequests,resolvedByChild}from"#harness/proxy-input-requests.js";import{resolveInputOutcome}from"#harness/input-request-resolution.js";import{SESSION_LIMIT_STOP_OPTION_ID}from"#harness/hitl/budget-request.js";const CONSUMED_MESSAGE_KEYS=new Set([`context`,`message`,inputTextKey]);function routeDeliverPayload(e){let t=getProxyInputRequests(e.state),routable=(t,n)=>n!==void 0&&e.allowRoute?.(t,n)!==!1,n=resolveMessageAgainstFirstRequest({enabled:e.resolveMessage===!0,entries:t,payload:e.payload,routable,state:e.state}),[r]=n.responses,i=[...e.payload.inputResponses??[],...n.responses],a=new Map,o=[],s,bucketFor=e=>{let t=JSON.stringify([e.childContinuationToken,e.childSessionInbox?.sessionId??``,e.remote?.sessionId??``,e.event.sequence,e.event.stepIndex,e.event.turnId,e.inputSource??null]),n=a.get(t);if(n!==void 0)return n;let r={childContinuationToken:e.childContinuationToken,remote:e.remote,event:e.event,parentRequestIds:[],responses:[],routes:[],...e.childSessionInbox!==void 0&&{childSessionInbox:e.childSessionInbox},...e.workflowAsk!==void 0&&{workflowAsk:e.workflowAsk}};return a.set(t,r),r},c=new Set;for(let e of i){let n=t.get(e.requestId);if(n===void 0||!routable(e.requestId,n)){o.push(e);continue}if(c.has(e.requestId))continue;c.add(e.requestId),n.kind===`session-limit`&&e.optionId===SESSION_LIMIT_STOP_OPTION_ID&&(s={kind:`cancel-turn`});let r=bucketFor(n);r.parentRequestIds.push(e.requestId),r.responses.push(e),r.routes.push(n)}let l=[...a.values()].map(({workflowAsk:n,remote:i,childContinuationToken:a,childSessionInbox:o,event:s,parentRequestIds:c,responses:l,routes:u})=>{let d=new Set(c),decided=e=>{let n=t.get(e)?.kind;return n===void 0||!resolvedByChild(n)},f=new Set([...d].filter(decided));for(let e of u)if(e.batch!==void 0&&batchResolves({batch:e.batch,childContinuationToken:a,entries:t,responseIds:d}))for(let t of e.batch.requestIds)decided(t)&&f.add(t);return{childContinuationToken:a,payload:{inputResponses:l},resolved:{event:s,resolutions:resolveRetiredRequests({entries:t,responses:l,retireRequestIds:f})},...o!==void 0&&{childSessionInbox:o},...r!==void 0&&l.includes(r)&&{message:e.payload.message},...n!==void 0&&{workflowAsk:n},...i!==void 0&&{remote:i},...u[0]?.inputSource!==void 0&&{inputSource:u[0].inputSource}}}),u={};for(let[t,r]of Object.entries(e.payload))t!==`inputResponses`&&r!==void 0&&(n.consumed&&CONSUMED_MESSAGE_KEYS.has(t)||(u[t]=r));return o.length>0&&(u.inputResponses=o),{forChildren:l,forSelf:Object.keys(u).length>0?u:void 0,parentAction:s}}function resolveRetiredRequests(e){let t=new Map(e.responses.map(e=>[e.requestId,e])),n=[];for(let r of e.retireRequestIds){let i=e.entries.get(r);i!==void 0&&n.push(toInputResolution(r,i,t.get(r)))}return n}function toInputResolution(e,t,n){let r=resolveInputOutcome(t.kind,n),i={kind:t.kind,outcome:r,requestId:e};return n===void 0?i:{...i,response:n}}function resolveMessageAgainstFirstRequest(e){let t={consumed:!1,responses:[]};if(!e.enabled||(e.payload.inputResponses?.length??0)>0)return t;let n=readAnswerText(e.payload);if(n===void 0)return t;let answered=t=>{let n=e.entries.get(t);return n!==void 0&&!e.routable(t,n)},r=firstOpenInput(storedProjection(e.state),answered)?.request.requestId??[...e.entries.keys()].find(e=>!answered(e)),i=r===void 0?void 0:e.entries.get(r)?.reply;if(r===void 0||i===void 0)return t;let a=resolveTextToResponse(n,{requestId:r,...i});return a===void 0?t:{consumed:!0,responses:[a]}}function batchResolves(e){return e.batch.approvalRequestIds.length===0||e.batch.approvalRequestIds.every(t=>{let n=e.entries.get(t);return n===void 0||!sameBatch(n,e)||e.responseIds.has(t)})}function sameBatch(e,t){return e.childContinuationToken===t.childContinuationToken&&e.batch?.requestIds.length===t.batch.requestIds.length&&e.batch.requestIds.every((e,n)=>e===t.batch.requestIds[n])}export{routeDeliverPayload};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{parseSessionCallback}from"#channel/session-callback.js";import{deserializeContext}from"#context/serialize.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{SessionCallbackKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{parseJsonValue}from"#shared/json.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{resumeHook}from"#internal/workflow/runtime.js";import{parseSessionCallback}from"#channel/session-callback.js";import{deserializeContext}from"#context/serialize.js";import{postSessionCallbackRequest}from"#execution/session-callback-request.js";import{HookNotFoundError}from"#compiled/@workflow/errors/index.js";import{SUBAGENT_ADAPTER_KIND,isSubagentAdapterState}from"#subagents/adapter-state.js";const log=createLogger(`execution.delegated-parent-notification`),SUBAGENT_EXECUTION_FAILED=`SUBAGENT_EXECUTION_FAILED`,ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,inputTokens:0,outputTokens:0};async function notifyTurnCallerStep(e){"use step";if(e.caller===void 0)return;let t=createSettledTurnResult({caller:e.caller,lifecycle:e.lifecycle,sessionId:e.sessionId,settled:e.settled});if(e.caller.replyTo.kind===`callback`){await postSettledTurnCallback({result:t,sessionId:e.sessionId,url:e.caller.replyTo.url});return}await resumeSettledTurnHook(e.caller.replyTo.token,t)}async function notifyCancelledTaskCallerStep(e){"use step";let t=e.usage??ZERO_TOKEN_USAGE,n={code:SUBAGENT_EXECUTION_FAILED,message:`The agent invocation was cancelled.`},r={callId:e.caller.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:{kind:`parked`,result:{kind:`cancelled`},usageDelta:t},output:n,subagentName:e.caller.subagentName},i=e.usage===void 0?r:{...r,usage:e.usage};if(e.caller.replyTo.kind===`callback`){await postSettledTurnCallback({result:i,sessionId:e.sessionId,url:e.caller.replyTo.url});return}await resumeSettledTurnHook(e.caller.replyTo.token,i)}function createSettledTurnResult(e){let t=e.settled.usage??ZERO_TOKEN_USAGE;if(e.settled.isError===!0){let n={code:SUBAGENT_EXECUTION_FAILED,message:toErrorMessage(e.settled.output)};return{callId:e.caller.callId,isError:!0,kind:`subagent-result`,origin:`child`,outcome:{kind:e.lifecycle,result:{error:n,kind:`failed`},usageDelta:t},output:n,subagentName:e.caller.subagentName}}let n=parseJsonValue(e.settled.output),r={callId:e.caller.callId,kind:`subagent-result`,origin:`child`,outcome:{kind:e.lifecycle,result:{kind:`succeeded`,output:n},usageDelta:t},output:n,subagentName:e.caller.subagentName};return e.settled.usage===void 0?r:{...r,usage:e.settled.usage}}async function resolveInitialTurnCallerStep(e){"use step";let t=e.serializedContext[SessionCallbackKey.name];if(t!==void 0){let e=parseSessionCallback(t);if(!e.ok)throw Error(`Serialized session callback is invalid.`,{cause:e.cause});return{callId:e.callback.callId,replyTo:{kind:`callback`,token:e.callback.token,url:e.callback.url},subagentName:e.callback.subagentName}}let n=(await deserializeContext(e.serializedContext)).get(ChannelKey);if(n?.kind===SUBAGENT_ADAPTER_KIND&&isSubagentAdapterState(n.state))return{callId:n.state.callId,replyTo:{kind:`hook`,token:n.state.parentContinuationToken},subagentName:n.state.subagentName}}function bindTurnCallerContext(e,t){if(e===void 0)return t;if(e.replyTo.kind===`callback`){let n={callId:e.callId,subagentName:e.subagentName,token:e.replyTo.token,url:e.replyTo.url};return{...t,[SessionCallbackKey.name]:n}}let n=t[ChannelKey.name];if(typeof n!=`object`||!n||Reflect.get(n,`kind`)!==SUBAGENT_ADAPTER_KIND||!isSubagentAdapterState(Reflect.get(n,`state`)))throw Error(`Delegated local turn is missing its subagent adapter binding.`);let r={...Reflect.get(n,`state`),callId:e.callId,parentContinuationToken:e.replyTo.token,subagentName:e.subagentName};return{...t,[ChannelKey.name]:{...n,state:r}}}async function postSettledTurnCallback(e){let{sessionId:t}=e;if(e.result.isError===!0){await postCallbackPayload({payload:{callId:e.result.callId,error:e.result.output,kind:`turn.failed`,outcome:e.result.outcome,sessionId:t,subagentName:e.result.subagentName},url:e.url});return}await postCallbackPayload({payload:{callId:e.result.callId,kind:`turn.completed`,outcome:e.result.outcome,output:e.result.output,sessionId:t,subagentName:e.result.subagentName},url:e.url})}async function postCallbackPayload(e){let t=await postSessionCallbackRequest({body:e.payload,url:e.url});if(!t.ok)throw Error(`Turn callback failed with HTTP ${t.status}.`)}async function resumeSettledTurnHook(e,t){try{await resumeHook(e,{kind:`runtime-action-result`,results:[t]})}catch(n){if(!HookNotFoundError.is(n))throw n;log.warn(`turn caller hook no longer exists`,{callId:t.callId,callerToken:e})}}export{bindTurnCallerContext,notifyCancelledTaskCallerStep,notifyTurnCallerStep,resolveInitialTurnCallerStep};
|