experimental-ash 0.61.0 → 0.63.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 +72 -0
- package/dist/docs/public/advanced/hooks.mdx +8 -2
- package/dist/docs/public/advanced/runs-and-streaming.md +6 -3
- package/dist/docs/public/advanced/typescript-api.md +32 -0
- package/dist/docs/public/channels/custom.mdx +23 -0
- package/dist/docs/public/frontend/README.md +8 -4
- package/dist/docs/public/frontend/meta.json +9 -1
- package/dist/docs/public/frontend/nextjs.md +4 -4
- package/dist/docs/public/frontend/nuxt.md +168 -0
- package/dist/docs/public/frontend/sveltekit.md +177 -0
- package/dist/docs/public/frontend/use-ash-agent-svelte.md +185 -0
- package/dist/docs/public/frontend/use-ash-agent-vue.md +236 -0
- package/dist/docs/public/frontend/use-ash-agent.md +14 -14
- package/dist/docs/public/getting-started.mdx +2 -0
- package/dist/skills/ash-add-agent/SKILL.md +29 -17
- package/dist/skills/ash-add-next/SKILL.md +58 -8
- package/dist/src/channel/websocket-upgrade-server.d.ts +26 -0
- package/dist/src/channel/websocket-upgrade-server.js +1 -0
- package/dist/src/chunks/use-ash-agent-BQJLh7KU.js +1224 -0
- package/dist/src/chunks/use-ash-agent-CRWVA4i-.js +1192 -0
- package/dist/src/client/ash-agent-store.d.ts +61 -0
- package/dist/src/client/ash-agent-store.js +2 -0
- package/dist/src/client/index.d.ts +2 -0
- package/dist/src/client/index.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +9 -9
- package/dist/src/compiled/@ai-sdk/anthropic/_provider-utils.d.ts +1 -1
- package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +3 -3
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +52 -2
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +32 -2
- package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/provider/index.d.ts +507 -1
- package/dist/src/compiled/@chat-adapter/slack/index.js +25 -25
- package/dist/src/compiled/@workflow/core/events-consumer.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +1 -0
- package/dist/src/compiled/@workflow/core/runtime.js +29 -29
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
- package/dist/src/compiled/@workflow/errors/index.d.ts +14 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/queue.d.ts +8 -0
- package/dist/src/compiled/_chunks/workflow/{dist-Chj-QcBs.js → dist-gEXVSMPU.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-zpK2YVVA.js +3 -0
- package/dist/src/compiled/_chunks/workflow/resume-hook-BFK9mgsb.js +12 -0
- package/dist/src/compiled/_chunks/workflow/{sleep-Bg0t23kF.js → sleep-CeJckNg2.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{symbols-u476uwyR.js → symbols-BWCAoPHE.js} +1 -1
- package/dist/src/compiler/manifest.d.ts +12 -0
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-connection.d.ts +10 -2
- package/dist/src/compiler/normalize-connection.js +1 -1
- package/dist/src/execution/sandbox/bindings/local.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/internal/application/package.d.ts +1 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/connection.d.ts +9 -0
- package/dist/src/internal/authored-definition/connection.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +1 -1
- package/dist/src/internal/nitro/host/build-vercel-agent-summary.js +1 -1
- package/dist/src/internal/nitro/host/channel-routes.js +2 -2
- package/dist/src/internal/vercel-agent-summary.d.ts +6 -4
- package/dist/src/internal/workflow-bundle/ash-service-route-output.js +11 -1
- package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
- package/dist/src/public/channels/auth.d.ts +1 -1
- package/dist/src/public/channels/index.d.ts +1 -0
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/connections/index.d.ts +3 -2
- package/dist/src/public/connections/index.js +1 -1
- package/dist/src/public/definitions/connections/mcp.d.ts +4 -12
- package/dist/src/public/definitions/connections/mcp.js +1 -1
- package/dist/src/public/definitions/connections/openapi.d.ts +100 -0
- package/dist/src/public/definitions/connections/openapi.js +1 -0
- package/dist/src/public/definitions/connections/protocol.d.ts +12 -0
- package/dist/src/public/definitions/connections/protocol.js +1 -0
- package/dist/src/public/next/index.d.ts +6 -6
- package/dist/src/public/next/index.js +1 -1
- package/dist/src/public/next/{vercel-json.d.ts → vercel-output-config.d.ts} +3 -3
- package/dist/src/public/next/vercel-output-config.js +1 -0
- package/dist/src/public/nuxt/dev-server.d.ts +24 -0
- package/dist/src/public/nuxt/dev-server.js +1 -0
- package/dist/src/public/nuxt/index.d.ts +1 -0
- package/dist/src/public/nuxt/index.js +1 -0
- package/dist/src/public/nuxt/module.d.ts +31 -0
- package/dist/src/public/nuxt/module.js +1 -0
- package/dist/src/public/nuxt/routing.d.ts +55 -0
- package/dist/src/public/nuxt/routing.js +1 -0
- package/dist/src/public/nuxt/vercel-json.d.ts +17 -0
- package/dist/src/public/{next → nuxt}/vercel-json.js +1 -1
- package/dist/src/public/sveltekit/dev-server.d.ts +24 -0
- package/dist/src/public/sveltekit/dev-server.js +1 -0
- package/dist/src/public/sveltekit/index.d.ts +39 -0
- package/dist/src/public/sveltekit/index.js +1 -0
- package/dist/src/public/sveltekit/routing.d.ts +32 -0
- package/dist/src/public/sveltekit/routing.js +1 -0
- package/dist/src/public/sveltekit/vercel-json.d.ts +17 -0
- package/dist/src/public/sveltekit/vercel-json.js +1 -0
- package/dist/src/react/use-ash-agent.d.ts +5 -27
- package/dist/src/react/use-ash-agent.js +1 -2
- package/dist/src/runtime/connections/openapi-client.d.ts +43 -0
- package/dist/src/runtime/connections/openapi-client.js +1 -0
- package/dist/src/runtime/connections/openapi-operations.d.ts +30 -0
- package/dist/src/runtime/connections/openapi-operations.js +1 -0
- package/dist/src/runtime/connections/openapi-schema.d.ts +39 -0
- package/dist/src/runtime/connections/openapi-schema.js +1 -0
- package/dist/src/runtime/connections/openapi-security.d.ts +41 -0
- package/dist/src/runtime/connections/openapi-security.js +1 -0
- package/dist/src/runtime/connections/openapi-spec.d.ts +20 -0
- package/dist/src/runtime/connections/openapi-spec.js +1 -0
- package/dist/src/runtime/connections/registry.d.ts +5 -7
- package/dist/src/runtime/connections/registry.js +1 -1
- package/dist/src/runtime/connections/types.d.ts +23 -0
- package/dist/src/runtime/resolve-connection.js +1 -1
- package/dist/src/runtime/types.d.ts +15 -1
- package/dist/src/shared/sandbox-session.d.ts +1 -1
- package/dist/src/shared/vercel-output-directory.d.ts +2 -0
- package/dist/src/shared/vercel-output-directory.js +1 -0
- package/dist/src/svelte/index.d.ts +3 -0
- package/dist/src/svelte/index.js +3 -0
- package/dist/src/svelte/use-ash-agent.d.ts +80 -0
- package/dist/src/svelte/use-ash-agent.js +3 -0
- package/dist/src/vue/index.d.ts +3 -0
- package/dist/src/vue/index.js +3 -0
- package/dist/src/vue/use-ash-agent.d.ts +78 -0
- package/dist/src/vue/use-ash-agent.js +3 -0
- package/package.json +59 -14
- package/dist/src/compiled/_chunks/workflow/dist-C4EHshZE.js +0 -3
- package/dist/src/compiled/_chunks/workflow/resume-hook-BlALLgSA.js +0 -12
|
@@ -210,6 +210,10 @@ declare const compiledConnectionDefinitionSchema: z.ZodObject<{
|
|
|
210
210
|
description: z.ZodString;
|
|
211
211
|
exportName: z.ZodOptional<z.ZodString>;
|
|
212
212
|
logicalPath: z.ZodString;
|
|
213
|
+
protocol: z.ZodDefault<z.ZodEnum<{
|
|
214
|
+
mcp: "mcp";
|
|
215
|
+
openapi: "openapi";
|
|
216
|
+
}>>;
|
|
213
217
|
sourceId: z.ZodString;
|
|
214
218
|
sourceKind: z.ZodLiteral<"module">;
|
|
215
219
|
url: z.ZodString;
|
|
@@ -230,6 +234,10 @@ declare const compiledAgentNodeManifestSchema: z.ZodObject<{
|
|
|
230
234
|
description: z.ZodString;
|
|
231
235
|
exportName: z.ZodOptional<z.ZodString>;
|
|
232
236
|
logicalPath: z.ZodString;
|
|
237
|
+
protocol: z.ZodDefault<z.ZodEnum<{
|
|
238
|
+
mcp: "mcp";
|
|
239
|
+
openapi: "openapi";
|
|
240
|
+
}>>;
|
|
233
241
|
sourceId: z.ZodString;
|
|
234
242
|
sourceKind: z.ZodLiteral<"module">;
|
|
235
243
|
url: z.ZodString;
|
|
@@ -324,6 +332,10 @@ export declare const compiledAgentManifestSchema: z.ZodObject<{
|
|
|
324
332
|
description: z.ZodString;
|
|
325
333
|
exportName: z.ZodOptional<z.ZodString>;
|
|
326
334
|
logicalPath: z.ZodString;
|
|
335
|
+
protocol: z.ZodDefault<z.ZodEnum<{
|
|
336
|
+
mcp: "mcp";
|
|
337
|
+
openapi: "openapi";
|
|
338
|
+
}>>;
|
|
327
339
|
sourceId: z.ZodString;
|
|
328
340
|
sourceKind: z.ZodLiteral<"module">;
|
|
329
341
|
url: z.ZodString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=28,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`WEBSOCKET`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({codeMode:z.boolean().optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(28),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{codeMode:e.config.experimental.codeMode},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:28}}function cloneCompiledRuntimeModelReference(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=28,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`WEBSOCKET`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({codeMode:z.boolean().optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),protocol:z.enum([`mcp`,`openapi`]).default(`mcp`),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(28),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{codeMode:e.config.experimental.codeMode},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:28}}function cloneCompiledRuntimeModelReference(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
|
|
@@ -4,10 +4,18 @@ import type { CompiledConnectionDefinition } from "#compiler/manifest.js";
|
|
|
4
4
|
* Compiles one authored connection module into the serializable metadata
|
|
5
5
|
* stored on the compiled agent manifest.
|
|
6
6
|
*
|
|
7
|
-
* The compiled manifest holds only serializable data. The live
|
|
8
|
-
*
|
|
7
|
+
* The compiled manifest holds only serializable data. The live authored
|
|
8
|
+
* `auth` callback (and, for OpenAPI connections, the `spec` and
|
|
9
|
+
* `operations` filter) is resolved at runtime by re-importing the
|
|
9
10
|
* authored module -- see `runtime/resolve-connection.ts`. Compile-time
|
|
10
11
|
* still imports and validates the module so authoring errors surface
|
|
11
12
|
* during `ash build`.
|
|
13
|
+
*
|
|
14
|
+
* The wire protocol is read from the marker stamped by the `define*`
|
|
15
|
+
* factory, defaulting to MCP, and selects which normalizer validates
|
|
16
|
+
* the authored shape. `url` carries the MCP server endpoint for MCP
|
|
17
|
+
* connections and the API base URL for OpenAPI connections, so the rest
|
|
18
|
+
* of the connection pipeline (auth context, tool-result narrowing,
|
|
19
|
+
* runtime resolution) stays protocol-agnostic.
|
|
12
20
|
*/
|
|
13
21
|
export declare function compileConnectionDefinition(agentRoot: string, source: ConnectionSourceRef): Promise<CompiledConnectionDefinition>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeMcpClientConnectionDefinition}from"#internal/authored-definition/connection.js";async function compileConnectionDefinition(
|
|
1
|
+
import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition}from"#internal/authored-definition/connection.js";import{readConnectionProtocol}from"#public/definitions/connections/protocol.js";async function compileConnectionDefinition(r,i){let a=await loadModuleBackedDefinition({agentRoot:r,kind:`connection`,source:i}),o=readConnectionProtocol(a),s=`Expected the connection export "${i.exportName??`default`}" from "${i.logicalPath}" to match the public Ash shape.`,c={connectionName:i.connectionName,exportName:i.exportName,logicalPath:i.logicalPath,sourceId:i.sourceId,sourceKind:`module`},l,u;if(o===`openapi`){let e=normalizeOpenApiConnectionDefinition(a,s);l={...c,description:e.description,protocol:`openapi`,url:e.baseUrl??``},u=e.auth}else{let e=normalizeMcpClientConnectionDefinition(a,s);l={...c,description:e.description,protocol:`mcp`,url:e.url},u=e.auth}let d=extractVercelConnectMarker(u);return d!==void 0&&(l.vercelConnect=d),l}function extractVercelConnectMarker(e){if(typeof e!=`object`||!e)return;let t=e.vercelConnect;if(typeof t!=`object`||!t)return;let n=t.connector;if(!(typeof n!=`string`||n.length===0))return{connector:n}}export{compileConnectionDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join}from"node:path";import{access,mkdir,readFile,writeFile}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{bufferToStream,streamToBuffer}from"#execution/sandbox/stream-utils.js";function createLocalSandboxBackend(e={}){return{name:`local`,async prewarm(e){let t=resolveTemplateSnapshotPath(resolveSandboxCacheDirectory(e.runtimeContext.appRoot),e.templateKey);if(await doesPathExist(t))return{reused:!0};let n=await createBashSandbox({sessionKey:e.templateKey,snapshotPath:t}),r=buildSandboxSession(createLocalInternalSandboxSession(n),localSetNetworkPolicyUnsupported);try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}return{reused:!1}},async create(e){let t=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),n=getLocalSnapshotPath(e.existingMetadata)??resolveSessionSnapshotPath(t,e.sessionKey);if(e.templateKey!==null&&!await doesPathExist(n)){let r=await readLocalSnapshot(resolveTemplateSnapshotPath(t,e.templateKey));if(r===null)throw new SandboxTemplateNotProvisionedError({backendName:`local`,templateKey:e.templateKey});await writeLocalSnapshot(n,r)}return createHandle(await createBashSandbox({sessionKey:e.sessionKey,snapshotPath:n}))}}}async function createBashSandbox(t){let{InMemoryFs:n,Sandbox:r}=await import(`#compiled/just-bash/index.js`),i=await readLocalSnapshot(t.snapshotPath),a=new n(createInitialFiles(i));await ensureLocalSandboxDirectories(a),await restoreLocalSandboxDirectories(a,i?.entries??[]);let o=await r.create({cwd:WORKSPACE_ROOT,env:i?.env,fs:a,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let e=await captureLocalSnapshot({filesystem:a,sandbox:o});return await writeLocalSnapshot(t.snapshotPath,e),{snapshotPath:t.snapshotPath}},async dispose(){await o.stop()},async readFileBytes(e){let t;try{t=await a.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await a.rm(e.path,{force:e.force,recursive:e.recursive})},sessionKey:t.sessionKey,snapshotPath:t.snapshotPath,async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${shellQuote(e.workingDirectory)} && ${e.command} )`;return adaptJustBashCommandToSandboxProcess(await o.runCommand({args:[t],cmd:`eval`,detached:!0,signal:e.abortSignal}))},async writeFiles(t){for(let n of t){let t=dirname(n.path);await a.mkdir(t,{recursive:!0}),await a.writeFile(n.path,n.content)}}}}function adaptJustBashCommandToSandboxProcess(e){let t=new TextEncoder,n,r,i=!1,a,o=new ReadableStream({start(e){n=e}}),s=new ReadableStream({start(e){r=e}});return(async()=>{try{for await(let i of e.logs()){let e=t.encode(i.data);i.type===`stdout`?n?.enqueue(e):r?.enqueue(e)}}catch(e){a=e,n?.error(e),r?.error(e)}finally{i=!0,a===void 0&&(n?.close(),r?.close())}})(),{stdout:o,stderr:s,async wait(){let t=await e.wait();for(;!i;)await new Promise(e=>setTimeout(e,0));if(a!==void 0)throw a;return{exitCode:t.exitCode}},async kill(){await e.kill()}}}async function localSetNetworkPolicyUnsupported(){throw Error(`setNetworkPolicy() is not supported on the local sandbox backend. just-bash applies its network policy only at sandbox creation (no run-time update) and does not run git or other binaries. Use the Vercel backend for credential brokering and egress control.`)}function createHandle(e){let t=buildSandboxSession(createLocalInternalSandboxSession(e),localSetNetworkPolicyUnsupported);return{session:t,useSessionFn:async()=>t,async captureState(){return{backendName:`local`,metadata:await e.captureSnapshot()??{},sessionKey:e.sessionKey}},async dispose(){await e.dispose()}}}function createLocalInternalSandboxSession(e){return{id:e.sessionKey,resolvePath:resolveLocalPath,async spawn(t){return await e.spawn(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:bufferToStream(n)},async removePath(t){await e.removePath(t)},async writeFile(t){let n=await streamToBuffer(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function resolveLocalPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}function resolveTemplateSnapshotPath(e,n){return join(e,`local`,`templates`,`${n}.json`)}function resolveSessionSnapshotPath(e,n){return join(e,`local`,`sessions`,`${n}.json`)}function createInitialFiles(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function ensureLocalSandboxDirectories(e){await e.mkdir(WORKSPACE_ROOT,{recursive:!0})}async function restoreLocalSandboxDirectories(e,t){let n=t.filter(e=>e.kind===`directory`).map(e=>e.path).sort((e,t)=>e.localeCompare(t));for(let t of n)t!==WORKSPACE_ROOT&&await e.mkdir(t,{recursive:!0})}async function captureLocalSnapshot(e){let t=[],n=e.filesystem.getAllPaths().sort((e,t)=>e.localeCompare(t));for(let r of n){let n=await e.filesystem.stat(r);if(n.isSymbolicLink)continue;if(n.isDirectory){t.push({kind:`directory`,path:r});continue}if(!n.isFile)continue;let i=await e.filesystem.readFileBuffer(r);t.push({contentBase64:Buffer.from(i).toString(`base64`),kind:`file`,path:r})}return{entries:t,env:{...e.sandbox.bashEnvInstance.getEnv()},version:1}}async function readLocalSnapshot(e){if(!await doesPathExist(e))return null;let t=JSON.parse(await readFile(e,`utf8`));return t.version===1?t:null}async function writeLocalSnapshot(t,n){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(n,null,2)}\n`)}async function doesPathExist(e){try{return await access(e),!0}catch{return!1}}function getLocalSnapshotPath(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}export{createLocalSandboxBackend};
|
|
1
|
+
import{dirname,join}from"node:path";import{access,mkdir,readFile,writeFile}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{bufferToStream,streamToBuffer}from"#execution/sandbox/stream-utils.js";function createLocalSandboxBackend(e={}){return{name:`local`,async prewarm(e){let t=resolveTemplateSnapshotPath(resolveSandboxCacheDirectory(e.runtimeContext.appRoot),e.templateKey);if(await doesPathExist(t))return{reused:!0};let n=await createBashSandbox({sessionKey:e.templateKey,snapshotPath:t}),r=buildSandboxSession(createLocalInternalSandboxSession(n),localSetNetworkPolicyUnsupported);try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}return{reused:!1}},async create(e){let t=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),n=getLocalSnapshotPath(e.existingMetadata)??resolveSessionSnapshotPath(t,e.sessionKey);if(e.templateKey!==null&&!await doesPathExist(n)){let r=await readLocalSnapshot(resolveTemplateSnapshotPath(t,e.templateKey));if(r===null)throw new SandboxTemplateNotProvisionedError({backendName:`local`,templateKey:e.templateKey});await writeLocalSnapshot(n,r)}return createHandle(await createBashSandbox({sessionKey:e.sessionKey,snapshotPath:n}))}}}async function createBashSandbox(t){let{InMemoryFs:n,Sandbox:r}=await import(`#compiled/just-bash/index.js`),i=await readLocalSnapshot(t.snapshotPath),a=new n(createInitialFiles(i));await ensureLocalSandboxDirectories(a),await restoreLocalSandboxDirectories(a,i?.entries??[]);let o=await r.create({cwd:WORKSPACE_ROOT,env:i?.env,fs:a,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let e=await captureLocalSnapshot({filesystem:a,sandbox:o});return await writeLocalSnapshot(t.snapshotPath,e),{snapshotPath:t.snapshotPath}},async dispose(){await o.stop()},async readFileBytes(e){let t;try{t=await a.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await a.rm(e.path,{force:e.force,recursive:e.recursive})},sessionKey:t.sessionKey,snapshotPath:t.snapshotPath,async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${shellQuote(e.workingDirectory)} && ${e.command} )`;return adaptJustBashCommandToSandboxProcess(await o.runCommand({args:[t],cmd:`eval`,detached:!0,env:e.env,signal:e.abortSignal}))},async writeFiles(t){for(let n of t){let t=dirname(n.path);await a.mkdir(t,{recursive:!0}),await a.writeFile(n.path,n.content)}}}}function adaptJustBashCommandToSandboxProcess(e){let t=new TextEncoder,n,r,i=!1,a,o=new ReadableStream({start(e){n=e}}),s=new ReadableStream({start(e){r=e}});return(async()=>{try{for await(let i of e.logs()){let e=t.encode(i.data);i.type===`stdout`?n?.enqueue(e):r?.enqueue(e)}}catch(e){a=e,n?.error(e),r?.error(e)}finally{i=!0,a===void 0&&(n?.close(),r?.close())}})(),{stdout:o,stderr:s,async wait(){let t=await e.wait();for(;!i;)await new Promise(e=>setTimeout(e,0));if(a!==void 0)throw a;return{exitCode:t.exitCode}},async kill(){await e.kill()}}}async function localSetNetworkPolicyUnsupported(){throw Error(`setNetworkPolicy() is not supported on the local sandbox backend. just-bash applies its network policy only at sandbox creation (no run-time update) and does not run git or other binaries. Use the Vercel backend for credential brokering and egress control.`)}function createHandle(e){let t=buildSandboxSession(createLocalInternalSandboxSession(e),localSetNetworkPolicyUnsupported);return{session:t,useSessionFn:async()=>t,async captureState(){return{backendName:`local`,metadata:await e.captureSnapshot()??{},sessionKey:e.sessionKey}},async dispose(){await e.dispose()}}}function createLocalInternalSandboxSession(e){return{id:e.sessionKey,resolvePath:resolveLocalPath,async spawn(t){return await e.spawn(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:bufferToStream(n)},async removePath(t){await e.removePath(t)},async writeFile(t){let n=await streamToBuffer(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function resolveLocalPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}function resolveTemplateSnapshotPath(e,n){return join(e,`local`,`templates`,`${n}.json`)}function resolveSessionSnapshotPath(e,n){return join(e,`local`,`sessions`,`${n}.json`)}function createInitialFiles(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function ensureLocalSandboxDirectories(e){await e.mkdir(WORKSPACE_ROOT,{recursive:!0})}async function restoreLocalSandboxDirectories(e,t){let n=t.filter(e=>e.kind===`directory`).map(e=>e.path).sort((e,t)=>e.localeCompare(t));for(let t of n)t!==WORKSPACE_ROOT&&await e.mkdir(t,{recursive:!0})}async function captureLocalSnapshot(e){let t=[],n=e.filesystem.getAllPaths().sort((e,t)=>e.localeCompare(t));for(let r of n){let n=await e.filesystem.stat(r);if(n.isSymbolicLink)continue;if(n.isDirectory){t.push({kind:`directory`,path:r});continue}if(!n.isFile)continue;let i=await e.filesystem.readFileBuffer(r);t.push({contentBase64:Buffer.from(i).toString(`base64`),kind:`file`,path:r})}return{entries:t,env:{...e.sandbox.bashEnvInstance.getEnv()},version:1}}async function readLocalSnapshot(e){if(!await doesPathExist(e))return null;let t=JSON.parse(await readFile(e,`utf8`));return t.version===1?t:null}async function writeLocalSnapshot(t,n){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(n,null,2)}\n`)}async function doesPathExist(e){try{return await access(e),!0}catch{return!1}}function getLocalSnapshotPath(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}export{createLocalSandboxBackend};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{streamToBuffer}from"#execution/sandbox/stream-utils.js";function createVercelSandboxBackend(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:DEFAULT_SANDBOX_TIMEOUT_MS,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=resolveVercelSandboxTags(n.tags,e.tags),a=e.templateKey===null?null:await readTemplateForCreate({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey}),o;try{o=await ensureSession({createOptions:n,existingMetadata:e.existingMetadata,sandboxModule:await t(),sessionKey:e.sessionKey,snapshotId:a?.snapshotId,tags:i})}catch(t){throw Error(`Failed to create sandbox session "${e.sessionKey}": ${errorMessage(t)}`,{cause:t})}return a===null&&o.created&&await ensureSandboxWorkingDirectory(o.sandbox,n),createHandle(o.sandbox,e.sessionKey)},async prewarm(e){let i;try{i=await ensureTemplate({bootstrap:e.bootstrap,createOptions:n,loadSandboxModule:t,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${errorMessage(t)}. Run \`vercel login\` and \`vercel link\` so the SDK can authenticate, or set VERCEL_TOKEN.`,{cause:t})}return r.set(e.templateKey,i.template),{reused:i.reused}}}}async function readTemplate(t){let n=t.prewarmedTemplates.get(t.templateKey);if(n!==void 0)return n;let r=await getNamedSandbox(await t.loadSandboxModule(),t.templateKey);if(r===null||typeof r.currentSnapshotId!=`string`)throw new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:t.templateKey});return{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:t.templateKey}}async function readTemplateForCreate(t){try{return await readTemplate(t)}catch(n){throw SandboxTemplateNotProvisionedError.is(n)?n:Error(`Failed to read sandbox template "${t.templateKey}": ${errorMessage(n)}`,{cause:n})}}async function ensureTemplate(e){let t=await e.loadSandboxModule(),r=await getNamedSandbox(t,e.templateKey),i=resolveVercelSandboxTags(e.createOptions.tags,e.tags);if(r===null){let n={...e.createOptions,name:e.templateKey,persistent:!1};i!==void 0&&(n.tags=i),r=await t.Sandbox.create(n)}else await ensureVercelSandboxTags(r,i);let a=extractAuthorSnapshotId(e.createOptions);if(typeof r.currentSnapshotId==`string`&&r.currentSnapshotId.length>0&&r.currentSnapshotId!==a)return{reused:!0,template:{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:e.templateKey}};await ensureSandboxWorkingDirectory(r,e.createOptions);let o=buildSandboxSession(createVercelInternalSandboxSession(r,e.templateKey),createVercelNetworkPolicySetter(r));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await r.update(e),o)});for(let t of e.seedFiles)typeof t.content==`string`?await o.writeTextFile({content:t.content,path:t.path}):await o.writeBinaryFile({content:t.content,path:t.path});let s=await r.snapshot();return{reused:!1,template:{sandboxName:r.name,snapshotId:s.snapshotId,templateKey:e.templateKey}}}async function ensureSession(e){let t=getVercelSandboxName(e.existingMetadata)??e.sessionKey,n=await getNamedSandbox(e.sandboxModule,t);if(n!==null)return await ensureVercelSandboxTags(n,e.tags),{created:!1,sandbox:n};let r=createSessionCreateParams(e,t);return e.tags!==void 0&&(r.tags=e.tags),{created:!0,sandbox:await e.sandboxModule.Sandbox.create(r)}}function createSessionCreateParams(e,t){if(e.snapshotId===void 0)return{...e.createOptions,name:t,persistent:!0};let{runtime:n,source:r,...i}=e.createOptions;return{...i,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}}}function createHandle(e,t){return{session:buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e)),useSessionFn:async r=>(r!==void 0&&await e.update(r),buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function createVercelNetworkPolicySetter(e){return async t=>{await e.update({networkPolicy:t})}}function createVercelInternalSandboxSession(e,n){return{id:n,resolvePath:resolveVercelSandboxPath,async spawn(n){return adaptVercelCommandToSandboxProcess(await e.runCommand({args:[`-lc`,n.command],cmd:`bash`,cwd:n.workingDirectory??WORKSPACE_ROOT,detached:!0,signal:n.abortSignal}))},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await streamToBuffer(t.content);await e.writeFiles([{content:n,path:t.path}])},async removePath(t){await e.fs.rm(t.path,{force:t.force,recursive:t.recursive,signal:t.abortSignal})}}}function adaptVercelCommandToSandboxProcess(e){let t=new TextEncoder,n,r,i=!1,a,o=new ReadableStream({start(e){n=e}}),s=new ReadableStream({start(e){r=e}});return(async()=>{try{for await(let i of e.logs()){let e=t.encode(i.data);i.stream===`stdout`?n?.enqueue(e):r?.enqueue(e)}}catch(e){a=e,n?.error(e),r?.error(e)}finally{i=!0,a===void 0&&(n?.close(),r?.close())}})(),{stdout:o,stderr:s,async wait(){let t=await e.wait();for(;!i;)await new Promise(e=>setTimeout(e,0));if(a!==void 0)throw a;return{exitCode:t.exitCode}},async kill(){await e.kill()}}}function resolveVercelSandboxPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}async function ensureSandboxWorkingDirectory(e,n){await runSandboxBootstrapStep(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${WORKSPACE_ROOT} && chown ${SANDBOX_USER}:${SANDBOX_USER} ${WORKSPACE_ROOT}`}),n.networkPolicy!==`deny-all`&&await runSandboxBootstrapStep(e,{failureMessage:`Failed to install ripgrep in Vercel sandbox.`,script:`command -v rg >/dev/null 2>&1 || { dnf install -y spal-release && dnf install -y ripgrep; }`})}async function runSandboxBootstrapStep(e,t){let n=await e.runCommand({args:[`-lc`,t.script],cmd:`bash`,sudo:!0});if(n.exitCode!==0){let e=await n.stderr();throw Error(`${t.failureMessage} ${e}`.trim())}}const SANDBOX_USER=`vercel-sandbox`;async function getNamedSandbox(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(isSandboxMissingError(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${errorMessage(e)}`,{cause:e})}}function isSandboxMissingError(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function extractAuthorSnapshotId(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function getVercelSandboxName(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function resolveVercelSandboxTags(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>VERCEL_SANDBOX_TAG_LIMIT)throw Error(`Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function ensureVercelSandboxTags(e,t){t===void 0||areVercelSandboxTagsEqual(e.tags,t)||await e.update({tags:t})}function areVercelSandboxTagsEqual(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function errorMessage(e){return e instanceof Error?e.message:String(e)}const DEFAULT_SANDBOX_TIMEOUT_MS=1800*1e3,VERCEL_SANDBOX_TAG_LIMIT=5;export{createVercelSandboxBackend};
|
|
1
|
+
import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{streamToBuffer}from"#execution/sandbox/stream-utils.js";function createVercelSandboxBackend(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:DEFAULT_SANDBOX_TIMEOUT_MS,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=resolveVercelSandboxTags(n.tags,e.tags),a=e.templateKey===null?null:await readTemplateForCreate({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey}),o;try{o=await ensureSession({createOptions:n,existingMetadata:e.existingMetadata,sandboxModule:await t(),sessionKey:e.sessionKey,snapshotId:a?.snapshotId,tags:i})}catch(t){throw Error(`Failed to create sandbox session "${e.sessionKey}": ${errorMessage(t)}`,{cause:t})}return a===null&&o.created&&await ensureSandboxWorkingDirectory(o.sandbox,n),createHandle(o.sandbox,e.sessionKey)},async prewarm(e){let i;try{i=await ensureTemplate({bootstrap:e.bootstrap,createOptions:n,loadSandboxModule:t,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${errorMessage(t)}. Run \`vercel login\` and \`vercel link\` so the SDK can authenticate, or set VERCEL_TOKEN.`,{cause:t})}return r.set(e.templateKey,i.template),{reused:i.reused}}}}async function readTemplate(t){let n=t.prewarmedTemplates.get(t.templateKey);if(n!==void 0)return n;let r=await getNamedSandbox(await t.loadSandboxModule(),t.templateKey);if(r===null||typeof r.currentSnapshotId!=`string`)throw new SandboxTemplateNotProvisionedError({backendName:`vercel`,templateKey:t.templateKey});return{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:t.templateKey}}async function readTemplateForCreate(t){try{return await readTemplate(t)}catch(n){throw SandboxTemplateNotProvisionedError.is(n)?n:Error(`Failed to read sandbox template "${t.templateKey}": ${errorMessage(n)}`,{cause:n})}}async function ensureTemplate(e){let t=await e.loadSandboxModule(),r=await getNamedSandbox(t,e.templateKey),i=resolveVercelSandboxTags(e.createOptions.tags,e.tags);if(r===null){let n={...e.createOptions,name:e.templateKey,persistent:!1};i!==void 0&&(n.tags=i),r=await t.Sandbox.create(n)}else await ensureVercelSandboxTags(r,i);let a=extractAuthorSnapshotId(e.createOptions);if(typeof r.currentSnapshotId==`string`&&r.currentSnapshotId.length>0&&r.currentSnapshotId!==a)return{reused:!0,template:{sandboxName:r.name,snapshotId:r.currentSnapshotId,templateKey:e.templateKey}};await ensureSandboxWorkingDirectory(r,e.createOptions);let o=buildSandboxSession(createVercelInternalSandboxSession(r,e.templateKey),createVercelNetworkPolicySetter(r));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await r.update(e),o)});for(let t of e.seedFiles)typeof t.content==`string`?await o.writeTextFile({content:t.content,path:t.path}):await o.writeBinaryFile({content:t.content,path:t.path});let s=await r.snapshot();return{reused:!1,template:{sandboxName:r.name,snapshotId:s.snapshotId,templateKey:e.templateKey}}}async function ensureSession(e){let t=getVercelSandboxName(e.existingMetadata)??e.sessionKey,n=await getNamedSandbox(e.sandboxModule,t);if(n!==null)return await ensureVercelSandboxTags(n,e.tags),{created:!1,sandbox:n};let r=createSessionCreateParams(e,t);return e.tags!==void 0&&(r.tags=e.tags),{created:!0,sandbox:await e.sandboxModule.Sandbox.create(r)}}function createSessionCreateParams(e,t){if(e.snapshotId===void 0)return{...e.createOptions,name:t,persistent:!0};let{runtime:n,source:r,...i}=e.createOptions;return{...i,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}}}function createHandle(e,t){return{session:buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e)),useSessionFn:async r=>(r!==void 0&&await e.update(r),buildSandboxSession(createVercelInternalSandboxSession(e,t),createVercelNetworkPolicySetter(e))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function createVercelNetworkPolicySetter(e){return async t=>{await e.update({networkPolicy:t})}}function createVercelInternalSandboxSession(e,n){return{id:n,resolvePath:resolveVercelSandboxPath,async spawn(n){return adaptVercelCommandToSandboxProcess(await e.runCommand({args:[`-lc`,n.command],cmd:`bash`,cwd:n.workingDirectory??WORKSPACE_ROOT,detached:!0,env:n.env,signal:n.abortSignal}))},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await streamToBuffer(t.content);await e.writeFiles([{content:n,path:t.path}])},async removePath(t){await e.fs.rm(t.path,{force:t.force,recursive:t.recursive,signal:t.abortSignal})}}}function adaptVercelCommandToSandboxProcess(e){let t=new TextEncoder,n,r,i=!1,a,o=new ReadableStream({start(e){n=e}}),s=new ReadableStream({start(e){r=e}});return(async()=>{try{for await(let i of e.logs()){let e=t.encode(i.data);i.stream===`stdout`?n?.enqueue(e):r?.enqueue(e)}}catch(e){a=e,n?.error(e),r?.error(e)}finally{i=!0,a===void 0&&(n?.close(),r?.close())}})(),{stdout:o,stderr:s,async wait(){let t=await e.wait();for(;!i;)await new Promise(e=>setTimeout(e,0));if(a!==void 0)throw a;return{exitCode:t.exitCode}},async kill(){await e.kill()}}}function resolveVercelSandboxPath(e){return e.startsWith(`/`)?e:`${WORKSPACE_ROOT}/${e}`}async function ensureSandboxWorkingDirectory(e,n){await runSandboxBootstrapStep(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${WORKSPACE_ROOT} && chown ${SANDBOX_USER}:${SANDBOX_USER} ${WORKSPACE_ROOT}`}),n.networkPolicy!==`deny-all`&&await runSandboxBootstrapStep(e,{failureMessage:`Failed to install ripgrep in Vercel sandbox.`,script:`command -v rg >/dev/null 2>&1 || { dnf install -y spal-release && dnf install -y ripgrep; }`})}async function runSandboxBootstrapStep(e,t){let n=await e.runCommand({args:[`-lc`,t.script],cmd:`bash`,sudo:!0});if(n.exitCode!==0){let e=await n.stderr();throw Error(`${t.failureMessage} ${e}`.trim())}}const SANDBOX_USER=`vercel-sandbox`;async function getNamedSandbox(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(isSandboxMissingError(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${errorMessage(e)}`,{cause:e})}}function isSandboxMissingError(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function extractAuthorSnapshotId(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function getVercelSandboxName(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function resolveVercelSandboxTags(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>VERCEL_SANDBOX_TAG_LIMIT)throw Error(`Vercel Sandbox supports at most ${VERCEL_SANDBOX_TAG_LIMIT} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function ensureVercelSandboxTags(e,t){t===void 0||areVercelSandboxTagsEqual(e.tags,t)||await e.update({tags:t})}function areVercelSandboxTagsEqual(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function errorMessage(e){return e instanceof Error?e.message:String(e)}const DEFAULT_SANDBOX_TIMEOUT_MS=1800*1e3,VERCEL_SANDBOX_TAG_LIMIT=5;export{createVercelSandboxBackend};
|
|
@@ -18,6 +18,7 @@ export declare function resolvePackageSourceFilePath(relativeSourcePath: string)
|
|
|
18
18
|
* Resolves one package-owned source directory from the currently executing Ash installation.
|
|
19
19
|
*/
|
|
20
20
|
export declare function resolvePackageSourceDirectoryPath(relativeSourcePath: string): string;
|
|
21
|
+
export declare function resolvePackageDependencyPath(specifier: string): string;
|
|
21
22
|
/**
|
|
22
23
|
* Resolves the installed Ash package identity from package.json.
|
|
23
24
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return`0.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return`0.63.0`}const FALLBACK_PACKAGE_INFO={name:ASH_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let t=e;for(;;){if(existsSync(join(t,`package.json`))&&!isBuildOutputPackageRoot(t))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve package root from "${e}".`);t=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),ASH_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${ASH_PACKAGE_NAME}/package.json`),ASH_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { McpClientConnectionDefinition } from "#public/definitions/connections/mcp.js";
|
|
2
|
+
import type { OpenAPIConnectionDefinition } from "#public/definitions/connections/openapi.js";
|
|
2
3
|
/**
|
|
3
4
|
* Validates one authored MCP client connection module export at build time
|
|
4
5
|
* and returns the public definition type. The module export is `unknown`
|
|
@@ -7,3 +8,11 @@ import type { McpClientConnectionDefinition } from "#public/definitions/connecti
|
|
|
7
8
|
* `ash build`.
|
|
8
9
|
*/
|
|
9
10
|
export declare function normalizeMcpClientConnectionDefinition(value: unknown, message: string): McpClientConnectionDefinition;
|
|
11
|
+
/**
|
|
12
|
+
* Validates one authored OpenAPI connection module export at build time
|
|
13
|
+
* and returns the public definition type. Mirrors
|
|
14
|
+
* {@link normalizeMcpClientConnectionDefinition} but validates the
|
|
15
|
+
* OpenAPI-specific `spec`/`baseUrl`/`operations` fields and reuses the
|
|
16
|
+
* shared auth and headers validation.
|
|
17
|
+
*/
|
|
18
|
+
export declare function normalizeOpenApiConnectionDefinition(value: unknown, message: string): OpenAPIConnectionDefinition;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";const KNOWN_TOP_LEVEL_KEYS=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],KNOWN_AUTHORIZATION_KEYS=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function normalizeMcpClientConnectionDefinition(n,i){let a=expectObjectRecord(n,i);expectOnlyKnownKeys(a,KNOWN_TOP_LEVEL_KEYS,i),validateUrl(a,i),validateDescription(a,i);let o=normalizeAuthorization(a,i),s=normalizeHeaders(a,i),c=normalizeToolFilter(a,i);if(o!==void 0&&s!==void 0&&typeof s!=`function`&&Object.keys(s).some(e=>e.toLowerCase()===`authorization`))throw Error(`${i} "headers" must not include an "Authorization" key when "auth" is also provided.`);let l={description:a.description,url:a.url};if(o!==void 0&&(l.auth=o),s!==void 0&&(l.headers=s),c!==void 0&&(l.tools=c),a.approval!==void 0){if(typeof a.approval!=`function`)throw Error(`${i} The "approval" field must be a function when provided.`);l.approval=a.approval}return l}function validateUrl(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function validateDescription(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function normalizeAuthorization(r,
|
|
1
|
+
import{expectObjectRecord,expectOnlyKnownKeys}from"#internal/authored-module.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";const KNOWN_TOP_LEVEL_KEYS=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],KNOWN_OPENAPI_TOP_LEVEL_KEYS=[`approval`,`auth`,`baseUrl`,`description`,`headers`,`operations`,`spec`],KNOWN_AUTHORIZATION_KEYS=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function normalizeMcpClientConnectionDefinition(n,i){let a=expectObjectRecord(n,i);expectOnlyKnownKeys(a,KNOWN_TOP_LEVEL_KEYS,i),validateUrl(a,i),validateDescription(a,i);let o=normalizeAuthorization(a,i),s=normalizeHeaders(a,i),c=normalizeToolFilter(a,i);if(o!==void 0&&s!==void 0&&typeof s!=`function`&&Object.keys(s).some(e=>e.toLowerCase()===`authorization`))throw Error(`${i} "headers" must not include an "Authorization" key when "auth" is also provided.`);let l={description:a.description,url:a.url};if(o!==void 0&&(l.auth=o),s!==void 0&&(l.headers=s),c!==void 0&&(l.tools=c),a.approval!==void 0){if(typeof a.approval!=`function`)throw Error(`${i} The "approval" field must be a function when provided.`);l.approval=a.approval}return l}function normalizeOpenApiConnectionDefinition(n,r){let a=expectObjectRecord(n,r);expectOnlyKnownKeys(a,KNOWN_OPENAPI_TOP_LEVEL_KEYS,r),validateSpec(a,r),validateBaseUrl(a,r),validateDescription(a,r);let o=normalizeAuthorization(a,r),s=normalizeHeaders(a,r),c=normalizeFilterField(a,`operations`,r);if(o!==void 0&&s!==void 0&&typeof s!=`function`&&Object.keys(s).some(e=>e.toLowerCase()===`authorization`))throw Error(`${r} "headers" must not include an "Authorization" key when "auth" is also provided.`);let l={description:a.description,spec:a.spec};if(a.baseUrl!==void 0&&(l.baseUrl=a.baseUrl),o!==void 0&&(l.auth=o),s!==void 0&&(l.headers=s),c!==void 0&&(l.operations=c),a.approval!==void 0){if(typeof a.approval!=`function`)throw Error(`${r} The "approval" field must be a function when provided.`);l.approval=a.approval}return l}function validateSpec(e,t){let n=e.spec;if(typeof n==`string`){if(!URL.canParse(n))throw Error(`${t} The "spec" field must be a valid URL when provided as a string.`);let e=new URL(n);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`${t} The "spec" URL must use the http or https protocol, got "${e.protocol}".`);return}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`${t} The "spec" field must be a URL string or an inline OpenAPI document object.`)}function validateBaseUrl(e,t){if(e.baseUrl===void 0)return;if(typeof e.baseUrl!=`string`||!URL.canParse(e.baseUrl))throw Error(`${t} The "baseUrl" field must be a valid URL when provided.`);let n=new URL(e.baseUrl);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "baseUrl" field must use the http or https protocol, got "${n.protocol}".`)}function validateUrl(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function validateDescription(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function normalizeAuthorization(r,i){if(r.auth===void 0)return;let o=expectObjectRecord(r.auth,`${i} The "auth" field must be an object with a "getToken" method.`);return expectOnlyKnownKeys(o,KNOWN_AUTHORIZATION_KEYS,`${i} The "auth" field`),normalizeAuthorizationSpec(o,i)}function normalizeHeaders(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function normalizeToolFilter(e,t){return normalizeFilterField(e,`tools`,t)}function normalizeFilterField(e,t,n){let r=e[t];if(r===void 0)return;if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);let i=r,a=`allow`in i,o=`block`in i;if(a&&o)throw Error(`${n} The "${t}" field must specify either "allow" or "block", not both.`);if(!a&&!o)throw Error(`${n} The "${t}" field must specify either "allow" or "block".`);return a?(validateStringArray(i.allow,`${n} The "${t}.allow"`),{allow:i.allow}):(validateStringArray(i.block,`${n} The "${t}.block"`),{block:i.block})}function validateStringArray(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}export{normalizeMcpClientConnectionDefinition,normalizeOpenApiConnectionDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroSurfaceOutputDirectory}from"#internal/application/paths.js";import{resolvePackageRoot}from"#internal/application/package.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareAshVersionedCacheDirectory,writeAshVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeAshVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function
|
|
1
|
+
import{dirname,join,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroSurfaceOutputDirectory}from"#internal/application/paths.js";import{resolvePackageRoot}from"#internal/application/package.js";import{build,copyPublicAssets,prepare,prerender}from"nitro/builder";import{prepareAshVersionedCacheDirectory,writeAshVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{normalizeAshVercelFunctionOutput}from"#internal/workflow-bundle/vercel-workflow-output.js";import{createApplicationNitro}from"#internal/nitro/host/create-application-nitro.js";import{emitVercelAgentSummary}from"#internal/nitro/host/build-vercel-agent-summary.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{runVercelBuildPrewarm}from"#internal/nitro/host/vercel-build-prewarm.js";import{findClosestVercelOutputDirectory}from"#shared/vercel-output-directory.js";function trimTrailingSlash(e){return e.replace(/[\\/]+$/,``)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function normalizeEntrypoint(e,t){return typeof t!=`string`||t.trim().length===0?null:resolve(e,t)}function normalizeServicePrefix(e){return typeof e.routePrefix==`string`?e.routePrefix.trim():typeof e.mount==`string`?e.mount.trim():isRecord(e.mount)&&typeof e.mount.path==`string`&&e.mount.path.trim().length>0?e.mount.path.trim():``}function resolveCoDeployedAshServicePrefix(e){if(!isRecord(e.config)||!isRecord(e.config.experimentalServices))return;let t=!1,n;for(let r of Object.values(e.config.experimentalServices)){if(!isRecord(r))continue;if(r.framework!==`ash`){t=!0;continue}let i=normalizeEntrypoint(e.configRoot,r.entrypoint),a=normalizeServicePrefix(r);i===e.appRoot&&a.length>0&&a!==`/`&&(n=a)}return t?n:void 0}async function resolveCoDeployedAshServicePrefixForVercelFunctionOutput(n){let i=await findClosestVercelOutputDirectory(n);if(i!==void 0)try{let e=resolveCoDeployedAshServicePrefix({appRoot:n,configRoot:n,config:JSON.parse(await readFile(join(i,`config.json`),`utf8`))});if(e!==void 0)return e}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let a=n;for(;;){for(let e of[join(a,`vercel.json`),join(a,`.vercel`,`output`,`config.json`)])try{let t=JSON.parse(await readFile(e,`utf8`)),i=resolveCoDeployedAshServicePrefix({appRoot:n,configRoot:e.endsWith(`vercel.json`)?a:n,config:t});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let i=dirname(a);if(i===a)return;a=i}}async function readVercelServerRuntime(e){try{return JSON.parse(await readFile(join(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function emitVercelWorkflowFunctions(e){let t=new WorkflowBundleBuilder({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:resolvePackageRoot(),watch:!1}),n=await readVercelServerRuntime(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function buildNitroOutput(e){let t=trimTrailingSlash(e.options.output.dir);return await prepareAshVersionedCacheDirectory(t),await prepare(e),await copyPublicAssets(e),await prerender(e),await build(e),await writeAshVersionedCacheMetadata(t),t}async function buildVercelNitroSurface(e,t){let n=await createApplicationNitro(e,!1,{outputDir:resolveNitroSurfaceOutputDirectory(e.appRoot,t),surface:t});try{return await buildNitroOutput(n)}finally{await n.close()}}async function buildApplication(e){let t=await prepareApplicationHost(e);if(!process.env.VERCEL){let e=await createApplicationNitro(t,!1);try{let n=await buildNitroOutput(e);return await emitVercelAgentSummary({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await resolveCoDeployedAshServicePrefixForVercelFunctionOutput(t.appRoot),r=await createApplicationNitro(t,!1,{surface:`app`});try{let e=await buildNitroOutput(r);await runVercelBuildPrewarm({appRoot:t.appRoot,log(e){console.log(e)}});let i=await buildVercelNitroSurface(t,`flow`);return await emitVercelWorkflowFunctions({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:i,outputDir:e,workflowBuildDir:t.workflowBuildDir}),n!==void 0&&await normalizeAshVercelFunctionOutput(e,{servicePrefix:n}),await emitVercelAgentSummary({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await r.close()}}export{buildApplication};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,join}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{VERCEL_ASH_AGENT_SUMMARY_KIND,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH,VERCEL_ASH_AGENT_SUMMARY_VERSION,normalizeChannelKindForDisplay}from"#internal/vercel-agent-summary.js";function buildVercelAgentSummary(e){let{manifest:t}=e;return{kind:VERCEL_ASH_AGENT_SUMMARY_KIND,schemaVersion:VERCEL_ASH_AGENT_SUMMARY_VERSION,generatorVersion:e.generatorVersion??resolveInstalledPackageInfo().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?toInstructionsEntry(t.instructions):null,schedules:t.schedules.map(toScheduleEntry),tools:t.tools.map(toToolEntry),skills:t.skills.map(toSkillEntry),connections:t.connections.map(toConnectionEntry),channels:t.channels.filter(isActiveChannel).map(toChannelEntry),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(toSubagentEntry),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function emitVercelAgentSummary(n){let r=buildVercelAgentSummary({generatorVersion:n.generatorVersion,manifest:n.manifest}),i=join(n.appRoot,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH);return await mkdir(dirname(i),{recursive:!0}),await writeFile(i,`${JSON.stringify(r,null,2)}\n`),i}function isActiveChannel(e){return e.kind===`channel`}function toInstructionsEntry(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function toScheduleEntry(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function toToolEntry(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function toSkillEntry(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function toConnectionEntry(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type
|
|
1
|
+
import{dirname,join}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{VERCEL_ASH_AGENT_SUMMARY_KIND,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH,VERCEL_ASH_AGENT_SUMMARY_VERSION,normalizeChannelKindForDisplay}from"#internal/vercel-agent-summary.js";function buildVercelAgentSummary(e){let{manifest:t}=e;return{kind:VERCEL_ASH_AGENT_SUMMARY_KIND,schemaVersion:VERCEL_ASH_AGENT_SUMMARY_VERSION,generatorVersion:e.generatorVersion??resolveInstalledPackageInfo().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?toInstructionsEntry(t.instructions):null,schedules:t.schedules.map(toScheduleEntry),tools:t.tools.map(toToolEntry),skills:t.skills.map(toSkillEntry),connections:t.connections.map(toConnectionEntry),channels:t.channels.filter(isActiveChannel).map(toChannelEntry),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(toSubagentEntry),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function emitVercelAgentSummary(n){let r=buildVercelAgentSummary({generatorVersion:n.generatorVersion,manifest:n.manifest}),i=join(n.appRoot,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH);return await mkdir(dirname(i),{recursive:!0}),await writeFile(i,`${JSON.stringify(r,null,2)}\n`),i}function isActiveChannel(e){return e.kind===`channel`}function toInstructionsEntry(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function toScheduleEntry(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function toToolEntry(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function toSkillEntry(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function toConnectionEntry(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type:e.protocol};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function toChannelEntry(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:normalizeChannelKindForDisplay(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function toSubagentEntry(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}export{buildVercelAgentSummary,emitVercelAgentSummary};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";const ASH_CHANNEL_VIRTUAL_ID_PREFIX=`#ash-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,
|
|
2
|
-
`);return}
|
|
1
|
+
import{resolvePackageDependencyPath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";const ASH_CHANNEL_VIRTUAL_ID_PREFIX=`#ash-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,n=new Set,a=[],o=new Set,s=getAllFrameworkChannelNames();for(let e of t){if(e.kind===`disabled`){if(!s.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...s].sort().join(`, `)}.`);o.add(e.name);continue}n.add(e.name),a.push({method:e.method,route:e.urlPath})}let c=getFrameworkChannelDefinitions().filter(e=>!n.has(e.name)&&!o.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),l=new Set,u=[];for(let e of[...c,...a]){let t=createChannelRouteKey(e);l.has(t)||(l.add(t),u.push(e))}return u}function registerChannelVirtualHandlers(e,t){for(let n of t.registrations)addChannelVirtualHandler(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function syncChannelVirtualHandlers(e,t){return areChannelRouteRegistrationsEqual(t.previous,t.next)?!1:(removeChannelVirtualHandlers(e),registerChannelVirtualHandlers(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function createChannelRouteKey(e){return`${e.method.toUpperCase()} ${e.route}`}function addChannelVirtualHandler(r,i){let o=createChannelRouteKey(i),s=`${ASH_CHANNEL_VIRTUAL_ID_PREFIX}${o}`,c=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/nitro/routes/channel-dispatch.ts`)),l=stringifyEsmImportSpecifier(resolvePackageDependencyPath(`nitro`));if(i.method===`WEBSOCKET`){r.options.handlers.push({handler:s,route:i.route}),r.options.virtual[s]=[`import { defineWebSocketHandler } from ${l};`,`import { dispatchChannelWebSocketRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,`export default defineWebSocketHandler((event) => dispatchChannelWebSocketRequest(event, ${JSON.stringify(o)}, config));`].join(`
|
|
2
|
+
`);return}r.options.handlers.push({handler:s,method:i.method,route:i.route}),r.options.virtual[s]=[`import { dispatchChannelRequest } from ${c};`,`const config = ${JSON.stringify(i.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(o)}, config);`].join(`
|
|
3
3
|
`)}function removeChannelVirtualHandlers(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&isChannelVirtualHandler(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(ASH_CHANNEL_VIRTUAL_ID_PREFIX)&&delete e.options.virtual[t]}function isChannelVirtualHandler(e){return e.handler.startsWith(ASH_CHANNEL_VIRTUAL_ID_PREFIX)}function areChannelRouteRegistrationsEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route)return!1}return!0}export{computeChannelRouteRegistrations,registerChannelVirtualHandlers,syncChannelVirtualHandlers};
|
|
@@ -99,11 +99,13 @@ export interface VercelAshToolEntry {
|
|
|
99
99
|
readonly logicalPath: string;
|
|
100
100
|
}
|
|
101
101
|
/**
|
|
102
|
-
*
|
|
103
|
-
* `
|
|
104
|
-
*
|
|
102
|
+
* Wire protocol the authored connection speaks, mirrored from the
|
|
103
|
+
* compiled connection's `protocol` discriminator. `"mcp"` is a
|
|
104
|
+
* {@link defineMcpClientConnection} server; `"openapi"` is a
|
|
105
|
+
* {@link defineOpenAPIConnection} REST API. New primitives extend this
|
|
106
|
+
* union when they ship.
|
|
105
107
|
*/
|
|
106
|
-
export type VercelAshConnectionType = "mcp";
|
|
108
|
+
export type VercelAshConnectionType = "mcp" | "openapi";
|
|
107
109
|
export interface VercelAshConnectionEntry {
|
|
108
110
|
readonly name: string;
|
|
109
111
|
readonly description: string;
|
|
@@ -29,7 +29,7 @@ if (!globalThis[PATCH_SYMBOL]) {
|
|
|
29
29
|
globalThis[PATCH_SYMBOL] = true;
|
|
30
30
|
const originalEmit = Server.prototype.emit;
|
|
31
31
|
Server.prototype.emit = function patchedEmit(event, request, ...args) {
|
|
32
|
-
if (event === "request" && request && typeof request.url === "string") {
|
|
32
|
+
if ((event === "request" || event === "upgrade") && request && typeof request.url === "string") {
|
|
33
33
|
request.url = stripServiceRoutePrefix(request.url);
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -40,5 +40,15 @@ if (!globalThis[PATCH_SYMBOL]) {
|
|
|
40
40
|
const originalModule = await import("./index.mjs");
|
|
41
41
|
const entrypoint = originalModule?.default ?? originalModule;
|
|
42
42
|
|
|
43
|
+
export const handleUpgrade = originalModule.handleUpgrade
|
|
44
|
+
? (request, socket, head) => {
|
|
45
|
+
if (request && typeof request.url === "string") {
|
|
46
|
+
request.url = stripServiceRoutePrefix(request.url);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return originalModule.handleUpgrade(request, socket, head);
|
|
50
|
+
}
|
|
51
|
+
: undefined;
|
|
52
|
+
|
|
43
53
|
export default entrypoint;
|
|
44
54
|
`.trimStart()}function normalizeServiceRoutePrefix(e){let t=(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``);return t.length===0?`/`:t}export{ASH_SHARED_SERVER_FUNCTION_PATH,applyAshServiceRoutePrefixWrapper,isAshVercelFunctionPath,normalizeAshVercelRoutes};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import{PNPM_WORKSPACE_PATH,ensurePnpmWorkspacePolicy}from"./pnpm-workspace.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"./web-template.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},ash:{buildCommand:`ash build`,entrypoint:`.`,framework:`ash`,routePrefix:`/_ash_internal/ash`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,t){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,t)}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{ashPackageVersion:e?.ashPackageVersion??`0.
|
|
1
|
+
import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import{PNPM_WORKSPACE_PATH,ensurePnpmWorkspacePolicy}from"./pnpm-workspace.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"./web-template.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},ash:{buildCommand:`ash build`,entrypoint:`.`,framework:`ash`,routePrefix:`/_ash_internal/ash`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,t){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,t)}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{ashPackageVersion:e?.ashPackageVersion??`0.63.0`,aiPackageVersion:e?.aiPackageVersion??`7.0.0-canary.165`,nextPackageVersion:e?.nextPackageVersion??`16.2.6`,reactPackageVersion:e?.reactPackageVersion??`19.2.6`,reactDomPackageVersion:e?.reactDomPackageVersion??`19.2.6`,streamdownPackageVersion:e?.streamdownPackageVersion??`2.5.0`,zodPackageVersion:e?.zodPackageVersion??`4.4.3`,tsgoPackageVersion:e?.tsgoPackageVersion??`7.0.0-dev.20260523.1`,typesNodePackageVersion:e?.typesNodePackageVersion??`25.9.1`,typesReactPackageVersion:e?.typesReactPackageVersion??`19.2.15`,typesReactDomPackageVersion:e?.typesReactDomPackageVersion??`19.2.3`}}function formatAshDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}async function patchWebPackageJson(e,t){if(!await pathExists(e))return[];assertStampedVersion(`ashPackageVersion`,t.ashPackageVersion),assertStampedVersion(`aiPackageVersion`,t.aiPackageVersion),assertStampedVersion(`nextPackageVersion`,t.nextPackageVersion),assertStampedVersion(`reactPackageVersion`,t.reactPackageVersion),assertStampedVersion(`reactDomPackageVersion`,t.reactDomPackageVersion),assertStampedVersion(`streamdownPackageVersion`,t.streamdownPackageVersion),assertStampedVersion(`zodPackageVersion`,t.zodPackageVersion),assertStampedVersion(`tsgoPackageVersion`,t.tsgoPackageVersion),assertStampedVersion(`typesNodePackageVersion`,t.typesNodePackageVersion),assertStampedVersion(`typesReactPackageVersion`,t.typesReactPackageVersion),assertStampedVersion(`typesReactDomPackageVersion`,t.typesReactDomPackageVersion);let r={...WEB_APP_TEMPLATE_PACKAGE_JSON.dependencies,ai:t.aiPackageVersion,"experimental-ash":formatAshDependencySpecifier(t.ashPackageVersion),next:t.nextPackageVersion,react:t.reactPackageVersion,"react-dom":t.reactDomPackageVersion,streamdown:t.streamdownPackageVersion,zod:t.zodPackageVersion},i={...WEB_APP_TEMPLATE_PACKAGE_JSON.devDependencies,"@types/node":t.typesNodePackageVersion,"@types/react":t.typesReactPackageVersion,"@types/react-dom":t.typesReactDomPackageVersion,"@typescript/native-preview":t.tsgoPackageVersion},a=WEB_APP_TEMPLATE_PACKAGE_JSON.scripts;return await patchPackageJson(e,{dependencies:r,devDependencies:i,scripts:a}),[{path:e,dependencies:Object.keys(r),devDependencies:Object.keys(i),scripts:Object.keys(a)}]}function normalizeSlackConnectorSlug(e){return toSlackConnectorSlug((e.trim().replace(/^@/,``).split(`/`).at(-1)??``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^[^a-z0-9]+/,``).replace(/[^a-z0-9]+$/,``).slice(0,100).replace(/[^a-z0-9]+$/,``)||`my-agent`)}async function deriveSlackConnectorSlug(e,t){if(t!==void 0&&t.length>0&&t!==`.`)return normalizeSlackConnectorSlug(t);try{let t=await readFile(join(e,`package.json`),`utf8`),n=JSON.parse(t);if(typeof n.name==`string`&&n.name.length>0)return normalizeSlackConnectorSlug(n.name)}catch{}return normalizeSlackConnectorSlug(basename(resolve(e))||`my-agent`)}function buildSlackTemplate(e){return`import { connectSlackCredentials } from "@vercel/connect/ash";
|
|
2
2
|
import { slackChannel } from "experimental-ash/channels/slack";
|
|
3
3
|
|
|
4
4
|
export default slackChannel({
|
|
@@ -168,7 +168,7 @@ export declare function createUnauthorizedResponse(opts?: UnauthorizedResponseOp
|
|
|
168
168
|
* the final entry — it returns a synthetic anonymous
|
|
169
169
|
* {@link SessionAuthContext} that terminates the walk.
|
|
170
170
|
*/
|
|
171
|
-
export type AuthFn<TEvent> = (event: TEvent) => SessionAuthContext | null | undefined | Promise<SessionAuthContext | null | undefined>;
|
|
171
|
+
export type AuthFn<TEvent = Request> = (event: TEvent) => SessionAuthContext | null | undefined | Promise<SessionAuthContext | null | undefined>;
|
|
172
172
|
/**
|
|
173
173
|
* Walks an `AuthFn` (or array of them) in order against `request`. The
|
|
174
174
|
* first entry returning a {@link SessionAuthContext} wins. Entries that
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type Channel, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/defineChannel.js";
|
|
2
|
+
export { createWebSocketUpgradeServer, type WebSocketUpgradeServerBridge, } from "#channel/websocket-upgrade-server.js";
|
|
2
3
|
import type { Channel } from "#public/definitions/defineChannel.js";
|
|
3
4
|
/**
|
|
4
5
|
* Base channel metadata shape used by framework channel kinds.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{DELETE,GET,PATCH,POST,PUT,WS,defineChannel}from"#public/definitions/defineChannel.js";function isChannel(e,t){return e.kind===getChannelInstrumentationKind(t)}export{DELETE,GET,PATCH,POST,PUT,WS,defineChannel,isChannel};
|
|
1
|
+
import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{DELETE,GET,PATCH,POST,PUT,WS,defineChannel}from"#public/definitions/defineChannel.js";import{createWebSocketUpgradeServer}from"#channel/websocket-upgrade-server.js";function isChannel(e,t){return e.kind===getChannelInstrumentationKind(t)}export{DELETE,GET,PATCH,POST,PUT,WS,createWebSocketUpgradeServer,defineChannel,isChannel};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Connection authoring helpers for `agent/connections/*.ts` files.
|
|
3
3
|
*/
|
|
4
|
-
export type { AuthorizationCallbackRequest, AuthorizationDefinition, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#runtime/connections/types.js";
|
|
4
|
+
export type { AuthorizationCallbackRequest, AuthorizationDefinition, ConnectionAuthDefinition, ConnectionPrincipal, HeadersDefinition, InteractiveAuthorizationDefinition, NonInteractiveAuthorizationDefinition, TokenResult, ToolFilterDefinition, } from "#runtime/connections/types.js";
|
|
5
5
|
export { defineInteractiveAuthorization } from "#runtime/connections/types.js";
|
|
6
6
|
export type { JsonValue } from "#public/types/json.js";
|
|
7
|
-
export { defineMcpClientConnection, type
|
|
7
|
+
export { defineMcpClientConnection, type McpClientConnectionDefinition, } from "#public/definitions/connections/mcp.js";
|
|
8
|
+
export { defineOpenAPIConnection, type OpenAPIConnectionDefinition, type OpenAPISpecSource, } from "#public/definitions/connections/openapi.js";
|
|
8
9
|
export { type ConnectionAuthorizationChallenge, ConnectionAuthorizationFailedError, type ConnectionAuthorizationFailedErrorOptions, ConnectionAuthorizationRequiredError, type ConnectionAuthorizationRequiredErrorOptions, isConnectionAuthorizationFailedError, isConnectionAuthorizationRequiredError, } from "#public/connections/errors.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{defineInteractiveAuthorization}from"#runtime/connections/types.js";import{defineMcpClientConnection}from"#public/definitions/connections/mcp.js";export{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,defineInteractiveAuthorization,defineMcpClientConnection,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError};
|
|
1
|
+
import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{defineInteractiveAuthorization}from"#runtime/connections/types.js";import{defineMcpClientConnection}from"#public/definitions/connections/mcp.js";import{defineOpenAPIConnection}from"#public/definitions/connections/openapi.js";export{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,defineInteractiveAuthorization,defineMcpClientConnection,defineOpenAPIConnection,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError};
|
|
@@ -1,12 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ConnectionAuthDefinition, HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
|
|
2
2
|
import type { NeedsApprovalContext } from "#public/definitions/tool.js";
|
|
3
|
-
/**
|
|
4
|
-
* Auth strategy for the MCP server. Static-token definitions may omit
|
|
5
|
-
* `principalType`; Ash defaults them to `"app"`.
|
|
6
|
-
*/
|
|
7
|
-
export type McpClientAuthDefinition = (Omit<NonInteractiveAuthorizationDefinition, "principalType"> & {
|
|
8
|
-
readonly principalType?: NonInteractiveAuthorizationDefinition["principalType"];
|
|
9
|
-
}) | AuthorizationDefinition;
|
|
10
3
|
/**
|
|
11
4
|
* Public definition for an MCP client connection authored in
|
|
12
5
|
* `connections/*.ts`.
|
|
@@ -48,7 +41,7 @@ export interface McpClientConnectionDefinition {
|
|
|
48
41
|
*
|
|
49
42
|
* Optional when `headers` is provided for non-Bearer auth schemes.
|
|
50
43
|
*/
|
|
51
|
-
auth?:
|
|
44
|
+
auth?: ConnectionAuthDefinition;
|
|
52
45
|
/**
|
|
53
46
|
* Optional per-connection approval gate for connection tool calls.
|
|
54
47
|
*
|
|
@@ -80,10 +73,9 @@ export interface McpClientConnectionDefinition {
|
|
|
80
73
|
/**
|
|
81
74
|
* Defines an MCP client connection.
|
|
82
75
|
*
|
|
83
|
-
* Validates the {@link
|
|
76
|
+
* Validates the {@link ConnectionAuthDefinition} shape at
|
|
84
77
|
* definition time, in particular the "both-or-neither" constraint
|
|
85
|
-
* for
|
|
86
|
-
* {@link McpClientAuthDefinition.completeAuthorization}: providing
|
|
78
|
+
* for `startAuthorization` and `completeAuthorization`: providing
|
|
87
79
|
* exactly one is a definition error. `getToken` alone is valid and
|
|
88
80
|
* selects the non-interactive flow; providing both opts into
|
|
89
81
|
* interactive OAuth authorization.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{stampDefinitionKey}from"#public/tool-result-narrowing.js";function defineMcpClientConnection(e){return e.auth!==void 0&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineMcpClientConnection:`)),stampDefinitionKey(e,`connection:${e.url}`),e}export{defineMcpClientConnection};
|
|
1
|
+
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{stampDefinitionKey}from"#public/tool-result-narrowing.js";function defineMcpClientConnection(e){return e.auth!==void 0&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineMcpClientConnection:`)),stampDefinitionKey(e,`connection:${e.url}`),stampConnectionProtocol(e,`mcp`),e}export{defineMcpClientConnection};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { ConnectionAuthDefinition, HeadersDefinition, ToolFilterDefinition } from "#runtime/connections/types.js";
|
|
2
|
+
import type { NeedsApprovalContext } from "#public/definitions/tool.js";
|
|
3
|
+
/**
|
|
4
|
+
* The OpenAPI document backing the connection: either an HTTPS URL the
|
|
5
|
+
* runtime fetches on first use, or an already-parsed OpenAPI 3.x object.
|
|
6
|
+
*/
|
|
7
|
+
export type OpenAPISpecSource = string | Record<string, unknown>;
|
|
8
|
+
/**
|
|
9
|
+
* Public definition for an OpenAPI connection authored in
|
|
10
|
+
* `connections/*.ts`.
|
|
11
|
+
*
|
|
12
|
+
* The connection's runtime name is derived from its filename (the slug
|
|
13
|
+
* under `agent/connections/`, without the extension). A connection
|
|
14
|
+
* authored at `agent/connections/vercel.ts` is registered as
|
|
15
|
+
* `"vercel"`.
|
|
16
|
+
*
|
|
17
|
+
* Each operation in the document becomes a connection tool the model can
|
|
18
|
+
* discover via `connection_search` and call by its qualified name (e.g.
|
|
19
|
+
* `connection__vercel__getProjects`). The tool name is the operation's
|
|
20
|
+
* `operationId`; operations without one get a deterministic synthesized
|
|
21
|
+
* name (`<method>_<sanitized-path>`).
|
|
22
|
+
*
|
|
23
|
+
* Both `auth` and `headers` are optional — omit both for public APIs
|
|
24
|
+
* that require no authentication.
|
|
25
|
+
*/
|
|
26
|
+
export interface OpenAPIConnectionDefinition {
|
|
27
|
+
/**
|
|
28
|
+
* The OpenAPI 3.x document. Pass an HTTPS URL to fetch and parse at
|
|
29
|
+
* runtime, or an inline parsed object.
|
|
30
|
+
*/
|
|
31
|
+
readonly spec: OpenAPISpecSource;
|
|
32
|
+
/**
|
|
33
|
+
* Base URL that operation paths are resolved against (e.g.
|
|
34
|
+
* `https://api.example.com`).
|
|
35
|
+
*
|
|
36
|
+
* Optional: when omitted, the document's first usable `servers` entry
|
|
37
|
+
* is used ({@link OpenAPISpecSource} `{var}` placeholders are filled
|
|
38
|
+
* from each variable's `default`, and a relative server URL is
|
|
39
|
+
* resolved against the spec's URL). Provide `baseUrl` when the
|
|
40
|
+
* document has no absolute `servers` entry, or to override it.
|
|
41
|
+
*/
|
|
42
|
+
readonly baseUrl?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Human-readable summary of the connection and the operations it
|
|
45
|
+
* provides.
|
|
46
|
+
*
|
|
47
|
+
* Used in the system prompt layer to describe the connection to the
|
|
48
|
+
* model, and in `connection_search` results so the model can choose
|
|
49
|
+
* which connection to query.
|
|
50
|
+
*/
|
|
51
|
+
readonly description: string;
|
|
52
|
+
/**
|
|
53
|
+
* Auth strategy for the API. The resolved token is sent as
|
|
54
|
+
* `Authorization: Bearer <token>`.
|
|
55
|
+
*
|
|
56
|
+
* - `getToken`-only: simplest form. Covers static API keys,
|
|
57
|
+
* pre-provisioned tokens, and out-of-band OAuth. Defaults to
|
|
58
|
+
* `principalType: "app"` when omitted.
|
|
59
|
+
* - Three-method form: provide `startAuthorization` and
|
|
60
|
+
* `completeAuthorization` together to opt into interactive OAuth.
|
|
61
|
+
*
|
|
62
|
+
* Optional when `headers` is provided for non-Bearer auth schemes.
|
|
63
|
+
*/
|
|
64
|
+
auth?: ConnectionAuthDefinition;
|
|
65
|
+
/**
|
|
66
|
+
* Optional per-connection approval gate for connection tool calls.
|
|
67
|
+
*
|
|
68
|
+
* Use the helpers from `experimental-ash/tools/approval`:
|
|
69
|
+
* - `never()` — allow all tool calls without approval
|
|
70
|
+
* - `once()` — require approval only the first time per session
|
|
71
|
+
* - `always()` — require approval for every tool call
|
|
72
|
+
*/
|
|
73
|
+
approval?: (ctx: NeedsApprovalContext) => boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Arbitrary HTTP headers sent with every request to the API.
|
|
76
|
+
*
|
|
77
|
+
* Use for non-Bearer auth (e.g. API key headers) or configuration
|
|
78
|
+
* headers. Can be combined with `auth`.
|
|
79
|
+
*/
|
|
80
|
+
headers?: HeadersDefinition;
|
|
81
|
+
/**
|
|
82
|
+
* Operation filter keyed on `operationId`. When set, only operations
|
|
83
|
+
* whose id passes the filter are surfaced to the model. All other
|
|
84
|
+
* operations are silently excluded from `connection_search` results.
|
|
85
|
+
*
|
|
86
|
+
* Specify exactly one of `allow` or `block`. Mirrors `tools` on MCP
|
|
87
|
+
* connections, but names operations rather than tools.
|
|
88
|
+
*/
|
|
89
|
+
operations?: ToolFilterDefinition;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Defines an OpenAPI connection.
|
|
93
|
+
*
|
|
94
|
+
* Validates the auth shape at definition time, in particular the
|
|
95
|
+
* "both-or-neither" constraint for `startAuthorization` and
|
|
96
|
+
* `completeAuthorization`: providing exactly one is a definition error.
|
|
97
|
+
* `getToken` alone is valid and selects the non-interactive flow;
|
|
98
|
+
* providing both opts into interactive OAuth.
|
|
99
|
+
*/
|
|
100
|
+
export declare function defineOpenAPIConnection(definition: OpenAPIConnectionDefinition): OpenAPIConnectionDefinition;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stampConnectionProtocol}from"#public/definitions/connections/protocol.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{stampDefinitionKey}from"#public/tool-result-narrowing.js";function defineOpenAPIConnection(e){return e.auth!==void 0&&(e.auth=normalizeAuthorizationSpec(e.auth,`defineOpenAPIConnection:`)),stampDefinitionKey(e,`connection:${e.baseUrl??(typeof e.spec==`string`?e.spec:e.description)}`),stampConnectionProtocol(e,`openapi`),e}export{defineOpenAPIConnection};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ConnectionProtocol } from "#runtime/connections/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Stamps the wire protocol on a connection definition. Called by the
|
|
4
|
+
* `define*` factory that produced it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function stampConnectionProtocol(definition: object, protocol: ConnectionProtocol): void;
|
|
7
|
+
/**
|
|
8
|
+
* Reads the stamped protocol from a connection definition, defaulting
|
|
9
|
+
* to `"mcp"` when unstamped so connection modules authored before the
|
|
10
|
+
* marker existed continue to compile as MCP connections.
|
|
11
|
+
*/
|
|
12
|
+
export declare function readConnectionProtocol(definition: unknown): ConnectionProtocol;
|