experimental-ash 0.22.0 → 0.22.1
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 +11 -0
- package/dist/src/chunks/{dev-authored-source-watcher-DKDaaPea.js → dev-authored-source-watcher-Bj0TDis0.js} +1 -1
- package/dist/src/chunks/host-BDf7A9G7.js +22 -0
- package/dist/src/chunks/{paths-DZTgjrW-.js → paths-DxgjK2PI.js} +25 -25
- package/dist/src/chunks/{prewarm-BELT37PI.js → prewarm-xQtl6kAD.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/harness/action-result-helpers.d.ts +9 -6
- package/dist/src/harness/action-result-helpers.js +23 -16
- package/dist/src/harness/model-call-error.d.ts +16 -0
- package/dist/src/harness/model-call-error.js +71 -0
- package/dist/src/harness/provider-tools.d.ts +33 -2
- package/dist/src/harness/provider-tools.js +81 -0
- package/dist/src/harness/step-hooks.d.ts +21 -0
- package/dist/src/harness/step-hooks.js +7 -2
- package/dist/src/harness/tool-loop.js +284 -143
- package/dist/src/harness/tools.d.ts +12 -0
- package/dist/src/harness/tools.js +23 -5
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/build-application.js +65 -1
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.d.ts +15 -0
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +156 -1
- package/dist/src/public/definitions/connections/mcp.js +2 -0
- package/dist/src/public/definitions/tool.js +2 -0
- package/dist/src/public/tool-result-narrowing.d.ts +10 -7
- package/dist/src/public/tool-result-narrowing.js +42 -13
- package/dist/src/runtime/resolve-connection.js +5 -2
- package/dist/src/runtime/resolve-tool.js +5 -2
- package/package.json +1 -1
- package/dist/src/chunks/host-Btr4S69C.js +0 -22
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
3
|
import { build as buildNitro, copyPublicAssets, prepare, prerender } from "nitro/builder";
|
|
4
4
|
import { resolvePackageRoot } from "#internal/application/package.js";
|
|
5
5
|
import { prepareAshVersionedCacheDirectory, writeAshVersionedCacheMetadata, } from "#internal/application/cache-metadata.js";
|
|
6
6
|
import { resolveNitroSurfaceOutputDirectory } from "#internal/application/paths.js";
|
|
7
7
|
import { WorkflowBundleBuilder } from "#internal/workflow-bundle/builder.js";
|
|
8
|
+
import { normalizeAshVercelFunctionOutput } from "#internal/workflow-bundle/vercel-workflow-output.js";
|
|
8
9
|
import { createApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";
|
|
9
10
|
import { emitVercelAgentSummary } from "#internal/nitro/host/build-vercel-agent-summary.js";
|
|
10
11
|
import { prepareApplicationHost } from "#internal/nitro/host/prepare-application-host.js";
|
|
@@ -12,6 +13,66 @@ import { runVercelBuildPrewarm } from "#internal/nitro/host/vercel-build-prewarm
|
|
|
12
13
|
function trimTrailingSlash(path) {
|
|
13
14
|
return path.replace(/[\\/]+$/, "");
|
|
14
15
|
}
|
|
16
|
+
function isRecord(value) {
|
|
17
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function normalizeEntrypoint(rootDir, entrypoint) {
|
|
20
|
+
if (typeof entrypoint !== "string" || entrypoint.trim().length === 0) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return resolve(rootDir, entrypoint);
|
|
24
|
+
}
|
|
25
|
+
function isNextAshExperimentalServicesConfig(input) {
|
|
26
|
+
if (!isRecord(input.config) || !isRecord(input.config.experimentalServices)) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
let hasNextService = false;
|
|
30
|
+
let hasMatchingAshService = false;
|
|
31
|
+
for (const service of Object.values(input.config.experimentalServices)) {
|
|
32
|
+
if (!isRecord(service)) {
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (service.framework === "nextjs") {
|
|
36
|
+
hasNextService = true;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (service.framework !== "ash") {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const ashEntrypoint = normalizeEntrypoint(input.configRoot, service.entrypoint);
|
|
43
|
+
const routePrefix = typeof service.routePrefix === "string" ? service.routePrefix.trim() : "";
|
|
44
|
+
if (ashEntrypoint === input.appRoot && routePrefix.length > 0 && routePrefix !== "/") {
|
|
45
|
+
hasMatchingAshService = true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return hasNextService && hasMatchingAshService;
|
|
49
|
+
}
|
|
50
|
+
async function shouldNormalizeVercelFunctionOutputForNextService(appRoot) {
|
|
51
|
+
let currentDir = appRoot;
|
|
52
|
+
while (true) {
|
|
53
|
+
try {
|
|
54
|
+
const configPath = join(currentDir, "vercel.json");
|
|
55
|
+
const config = JSON.parse(await readFile(configPath, "utf8"));
|
|
56
|
+
if (isNextAshExperimentalServicesConfig({
|
|
57
|
+
appRoot,
|
|
58
|
+
configRoot: currentDir,
|
|
59
|
+
config,
|
|
60
|
+
})) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const parentDir = dirname(currentDir);
|
|
70
|
+
if (parentDir === currentDir) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
currentDir = parentDir;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
15
76
|
async function readVercelServerRuntime(outputDir) {
|
|
16
77
|
try {
|
|
17
78
|
const config = JSON.parse(await readFile(join(outputDir, "functions", "__server.func", ".vc-config.json"), "utf8"));
|
|
@@ -99,6 +160,9 @@ export async function buildApplication(rootDir) {
|
|
|
99
160
|
outputDir: outputDirectory,
|
|
100
161
|
workflowBuildDir: preparedHost.workflowBuildDir,
|
|
101
162
|
});
|
|
163
|
+
if (await shouldNormalizeVercelFunctionOutputForNextService(preparedHost.appRoot)) {
|
|
164
|
+
await normalizeAshVercelFunctionOutput(outputDirectory);
|
|
165
|
+
}
|
|
102
166
|
await emitVercelAgentSummary({
|
|
103
167
|
manifest: preparedHost.compileResult.manifest,
|
|
104
168
|
appRoot: preparedHost.appRoot,
|
|
@@ -26,6 +26,21 @@ export declare function copyNitroFunctionDirectory(input: {
|
|
|
26
26
|
sourcePath: string;
|
|
27
27
|
targetPath: string;
|
|
28
28
|
}): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Keeps only Ash-owned Vercel function output and rewrites Ash route function
|
|
31
|
+
* symlinks to a shared Ash-owned server function.
|
|
32
|
+
*
|
|
33
|
+
* Nitro emits generic app routes such as `index.func -> ./__server.func` for
|
|
34
|
+
* Ash's standalone landing page. In a multi-service Next.js deployment those
|
|
35
|
+
* root aliases collide with Next's own functions. The Next integration only
|
|
36
|
+
* proxies Ash's `/ash/v1/**` transport routes, so Vercel output should expose
|
|
37
|
+
* those route functions and workflow trigger functions, not Ash's root page.
|
|
38
|
+
*
|
|
39
|
+
* Nitro also dedupes every route function through `__server.func`. Preserve
|
|
40
|
+
* that model by copying the shared target once into the Ash-owned tree and
|
|
41
|
+
* repointing Ash route aliases at it before pruning the root target.
|
|
42
|
+
*/
|
|
43
|
+
export declare function normalizeAshVercelFunctionOutput(outputDir: string): Promise<void>;
|
|
29
44
|
/**
|
|
30
45
|
* Bundles one package-owned workflow handler into a standalone Vercel function
|
|
31
46
|
* directory without inheriting Nitro's hosted server chunks.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { cp, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
1
|
+
import { cp, mkdir, readdir, readFile, realpath, rename, rm, symlink, writeFile, } from "node:fs/promises";
|
|
2
2
|
import { basename, dirname, extname, join, relative } from "node:path";
|
|
3
3
|
import { buildWithNitroRolldown, getSingleRolldownChunk, } from "#internal/bundler/nitro-rolldown.js";
|
|
4
4
|
// just-bash exposes native optional codecs for xz/zstd support. Those packages
|
|
@@ -12,6 +12,8 @@ export const WORKFLOW_STEP_EXTERNAL_PACKAGES = ["@mongodb-js/zstd", "node-liblzm
|
|
|
12
12
|
*/
|
|
13
13
|
export const WORKFLOW_BUILDER_DEFERRED_PACKAGES = ["@chat-adapter/slack", "chat"];
|
|
14
14
|
const WORKFLOW_FUNCTION_NODE_OPTIONS = "--experimental-require-module";
|
|
15
|
+
const ASH_VERCEL_FUNCTION_PREFIXES = ["ash/", ".well-known/workflow/"];
|
|
16
|
+
const ASH_SHARED_SERVER_FUNCTION_PATH = "ash/__server.func";
|
|
15
17
|
/**
|
|
16
18
|
* Builds the environment block every generated Vercel workflow function needs.
|
|
17
19
|
*/
|
|
@@ -63,6 +65,159 @@ export async function copyNitroFunctionDirectory(input) {
|
|
|
63
65
|
recursive: true,
|
|
64
66
|
});
|
|
65
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Keeps only Ash-owned Vercel function output and rewrites Ash route function
|
|
70
|
+
* symlinks to a shared Ash-owned server function.
|
|
71
|
+
*
|
|
72
|
+
* Nitro emits generic app routes such as `index.func -> ./__server.func` for
|
|
73
|
+
* Ash's standalone landing page. In a multi-service Next.js deployment those
|
|
74
|
+
* root aliases collide with Next's own functions. The Next integration only
|
|
75
|
+
* proxies Ash's `/ash/v1/**` transport routes, so Vercel output should expose
|
|
76
|
+
* those route functions and workflow trigger functions, not Ash's root page.
|
|
77
|
+
*
|
|
78
|
+
* Nitro also dedupes every route function through `__server.func`. Preserve
|
|
79
|
+
* that model by copying the shared target once into the Ash-owned tree and
|
|
80
|
+
* repointing Ash route aliases at it before pruning the root target.
|
|
81
|
+
*/
|
|
82
|
+
export async function normalizeAshVercelFunctionOutput(outputDir) {
|
|
83
|
+
const functionsDir = join(outputDir, "functions");
|
|
84
|
+
const sharedFunctionPath = await prepareSharedAshServerFunction(functionsDir);
|
|
85
|
+
if (sharedFunctionPath !== null) {
|
|
86
|
+
await repointAshFunctionSymlinksInDirectory(functionsDir, sharedFunctionPath);
|
|
87
|
+
}
|
|
88
|
+
await pruneNonAshFunctionEntries(functionsDir, functionsDir);
|
|
89
|
+
await pruneNonAshVercelRoutes(outputDir);
|
|
90
|
+
}
|
|
91
|
+
async function prepareSharedAshServerFunction(functionsDir) {
|
|
92
|
+
const rootServerFunctionPath = join(functionsDir, "__server.func");
|
|
93
|
+
const sharedFunctionPath = join(functionsDir, ASH_SHARED_SERVER_FUNCTION_PATH);
|
|
94
|
+
let sourcePath;
|
|
95
|
+
try {
|
|
96
|
+
sourcePath = await realpath(rootServerFunctionPath);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
const stagingPath = `${sharedFunctionPath}.ash-staging`;
|
|
105
|
+
await mkdir(dirname(sharedFunctionPath), {
|
|
106
|
+
recursive: true,
|
|
107
|
+
});
|
|
108
|
+
await rm(stagingPath, {
|
|
109
|
+
force: true,
|
|
110
|
+
recursive: true,
|
|
111
|
+
});
|
|
112
|
+
await cp(sourcePath, stagingPath, {
|
|
113
|
+
dereference: true,
|
|
114
|
+
recursive: true,
|
|
115
|
+
});
|
|
116
|
+
await rm(sharedFunctionPath, {
|
|
117
|
+
force: true,
|
|
118
|
+
recursive: true,
|
|
119
|
+
});
|
|
120
|
+
await rename(stagingPath, sharedFunctionPath);
|
|
121
|
+
return sharedFunctionPath;
|
|
122
|
+
}
|
|
123
|
+
async function repointAshFunctionSymlinksInDirectory(directoryPath, sharedFunctionPath, functionsDir = directoryPath) {
|
|
124
|
+
let entries;
|
|
125
|
+
try {
|
|
126
|
+
entries = await readdir(directoryPath, { withFileTypes: true });
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
await Promise.all(entries.map(async (entry) => {
|
|
135
|
+
const entryPath = join(directoryPath, entry.name);
|
|
136
|
+
const relativeFunctionPath = normalizeVercelOutputPath(relative(functionsDir, entryPath));
|
|
137
|
+
if (entry.isSymbolicLink()) {
|
|
138
|
+
if (entry.name.endsWith(".func") && isAshVercelFunctionPath(relativeFunctionPath)) {
|
|
139
|
+
await repointFunctionSymlink(entryPath, sharedFunctionPath);
|
|
140
|
+
}
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (entry.isDirectory() && !entry.name.endsWith(".func")) {
|
|
144
|
+
await repointAshFunctionSymlinksInDirectory(entryPath, sharedFunctionPath, functionsDir);
|
|
145
|
+
}
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
async function repointFunctionSymlink(functionPath, sharedFunctionPath) {
|
|
149
|
+
await rm(functionPath, {
|
|
150
|
+
force: true,
|
|
151
|
+
recursive: true,
|
|
152
|
+
});
|
|
153
|
+
await symlink(normalizeVercelOutputPath(relative(dirname(functionPath), sharedFunctionPath)), functionPath, "dir");
|
|
154
|
+
}
|
|
155
|
+
async function pruneNonAshFunctionEntries(functionsDir, directoryPath) {
|
|
156
|
+
let entries;
|
|
157
|
+
try {
|
|
158
|
+
entries = await readdir(directoryPath, { withFileTypes: true });
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
await Promise.all(entries.map(async (entry) => {
|
|
167
|
+
const entryPath = join(directoryPath, entry.name);
|
|
168
|
+
const relativeFunctionPath = normalizeVercelOutputPath(relative(functionsDir, entryPath));
|
|
169
|
+
if (entry.name.endsWith(".func")) {
|
|
170
|
+
if (!isAshVercelFunctionPath(relativeFunctionPath)) {
|
|
171
|
+
await rm(entryPath, {
|
|
172
|
+
force: true,
|
|
173
|
+
recursive: true,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (entry.isDirectory()) {
|
|
179
|
+
await pruneNonAshFunctionEntries(functionsDir, entryPath);
|
|
180
|
+
}
|
|
181
|
+
}));
|
|
182
|
+
}
|
|
183
|
+
async function pruneNonAshVercelRoutes(outputDir) {
|
|
184
|
+
const configPath = join(outputDir, "config.json");
|
|
185
|
+
let parsed;
|
|
186
|
+
try {
|
|
187
|
+
parsed = JSON.parse(await readFile(configPath, "utf8"));
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
if (!isRecord(parsed) || !Array.isArray(parsed.routes)) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
parsed.routes = parsed.routes.filter(isAshVercelRoute);
|
|
199
|
+
await writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`);
|
|
200
|
+
}
|
|
201
|
+
function normalizeVercelOutputPath(path) {
|
|
202
|
+
return path.replaceAll("\\", "/");
|
|
203
|
+
}
|
|
204
|
+
function isAshVercelFunctionPath(path) {
|
|
205
|
+
return ASH_VERCEL_FUNCTION_PREFIXES.some((prefix) => path.startsWith(prefix));
|
|
206
|
+
}
|
|
207
|
+
function isAshVercelRoute(route) {
|
|
208
|
+
if (!isRecord(route)) {
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
if ("handle" in route) {
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
const src = typeof route.src === "string" ? route.src : "";
|
|
215
|
+
const dest = typeof route.dest === "string" ? route.dest : "";
|
|
216
|
+
return isAshVercelRoutePath(src) || isAshVercelRoutePath(dest);
|
|
217
|
+
}
|
|
218
|
+
function isAshVercelRoutePath(path) {
|
|
219
|
+
return path.includes("/ash/v1") || path.includes("/.well-known/workflow/");
|
|
220
|
+
}
|
|
66
221
|
/**
|
|
67
222
|
* Bundles one package-owned workflow handler into a standalone Vercel function
|
|
68
223
|
* directory without inheriting Nitro's hosted server chunks.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
|
|
2
|
+
import { stampDefinitionKey } from "#public/tool-result-narrowing.js";
|
|
2
3
|
/**
|
|
3
4
|
* Defines an MCP client connection.
|
|
4
5
|
*
|
|
@@ -14,5 +15,6 @@ export function defineMcpClientConnection(definition) {
|
|
|
14
15
|
if (definition.auth !== undefined) {
|
|
15
16
|
definition.auth = normalizeAuthorizationSpec(definition.auth, "defineMcpClientConnection:");
|
|
16
17
|
}
|
|
18
|
+
stampDefinitionKey(definition, `connection:${definition.url}`);
|
|
17
19
|
return definition;
|
|
18
20
|
}
|
|
@@ -39,14 +39,17 @@ export type DefinitionSourceEntry = {
|
|
|
39
39
|
readonly name: string;
|
|
40
40
|
};
|
|
41
41
|
/**
|
|
42
|
-
* Stamps
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
42
|
+
* Stamps a stable content-derived key on the definition so it can be
|
|
43
|
+
* identified across module instances. Called by `defineTool` and
|
|
44
|
+
* `defineMcpClientConnection` at definition time.
|
|
45
|
+
*/
|
|
46
|
+
export declare function stampDefinitionKey(definition: object, key: string): void;
|
|
47
|
+
/**
|
|
48
|
+
* Registers a definition key → source entry mapping in the global
|
|
49
|
+
* registry. Called by the resolution pipeline after loading the
|
|
50
|
+
* authored module.
|
|
48
51
|
*/
|
|
49
|
-
export declare function
|
|
52
|
+
export declare function registerDefinitionSource(key: string, entry: DefinitionSourceEntry): void;
|
|
50
53
|
/**
|
|
51
54
|
* Overloaded signature for {@link toolResultFrom}.
|
|
52
55
|
*/
|
|
@@ -1,21 +1,47 @@
|
|
|
1
|
-
const DEFINITION_SOURCE = Symbol("ash.definitionSource");
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
* Cross-instance symbol for reading the stable definition key stamped
|
|
3
|
+
* by `defineTool` / `defineMcpClientConnection`. `Symbol.for` ensures
|
|
4
|
+
* both the resolution pipeline's module copy and the user's import
|
|
5
|
+
* share the same property key.
|
|
6
|
+
*/
|
|
7
|
+
const DEFINITION_KEY = Symbol.for("experimental-ash.definition-source-key");
|
|
8
|
+
/**
|
|
9
|
+
* Global registry mapping definition keys to their resolved runtime
|
|
10
|
+
* names. Rooted on `globalThis` via `Symbol.for` so every module
|
|
11
|
+
* copy shares one registry — same pattern as `context/key.ts`
|
|
12
|
+
* (`KEY_REGISTRY_GLOBAL_KEY`).
|
|
13
|
+
*/
|
|
14
|
+
const REGISTRY_SYMBOL = Symbol.for("experimental-ash.definition-source-registry");
|
|
15
|
+
const registryContainer = globalThis;
|
|
16
|
+
if (registryContainer[REGISTRY_SYMBOL] === undefined) {
|
|
17
|
+
registryContainer[REGISTRY_SYMBOL] = new Map();
|
|
18
|
+
}
|
|
19
|
+
const definitionSourceRegistry = registryContainer[REGISTRY_SYMBOL];
|
|
20
|
+
/**
|
|
21
|
+
* Stamps a stable content-derived key on the definition so it can be
|
|
22
|
+
* identified across module instances. Called by `defineTool` and
|
|
23
|
+
* `defineMcpClientConnection` at definition time.
|
|
9
24
|
*/
|
|
10
|
-
export function
|
|
11
|
-
Object.defineProperty(definition,
|
|
25
|
+
export function stampDefinitionKey(definition, key) {
|
|
26
|
+
Object.defineProperty(definition, DEFINITION_KEY, { value: key });
|
|
12
27
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Reads the stable key from a definition, or `undefined` if unstamped.
|
|
30
|
+
*/
|
|
31
|
+
function readDefinitionKey(definition) {
|
|
32
|
+
if (DEFINITION_KEY in definition) {
|
|
33
|
+
return definition[DEFINITION_KEY];
|
|
16
34
|
}
|
|
17
35
|
return undefined;
|
|
18
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Registers a definition key → source entry mapping in the global
|
|
39
|
+
* registry. Called by the resolution pipeline after loading the
|
|
40
|
+
* authored module.
|
|
41
|
+
*/
|
|
42
|
+
export function registerDefinitionSource(key, entry) {
|
|
43
|
+
definitionSourceRegistry.set(key, entry);
|
|
44
|
+
}
|
|
19
45
|
const CONNECTION_TOOL_SEPARATOR = "__";
|
|
20
46
|
/**
|
|
21
47
|
* Narrows a {@link RuntimeActionResult} to a typed tool or connection
|
|
@@ -34,7 +60,10 @@ function toolResultFromImpl(result, source) {
|
|
|
34
60
|
return undefined;
|
|
35
61
|
if (result.isError === true)
|
|
36
62
|
return undefined;
|
|
37
|
-
const
|
|
63
|
+
const key = readDefinitionKey(source);
|
|
64
|
+
if (key === undefined)
|
|
65
|
+
return undefined;
|
|
66
|
+
const entry = definitionSourceRegistry.get(key);
|
|
38
67
|
if (entry === undefined)
|
|
39
68
|
return undefined;
|
|
40
69
|
if (entry.kind === "tool") {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { expectObjectRecord } from "#internal/authored-module.js";
|
|
2
|
-
import {
|
|
2
|
+
import { registerDefinitionSource } from "#public/tool-result-narrowing.js";
|
|
3
3
|
import { toErrorMessage } from "#shared/errors.js";
|
|
4
4
|
import { normalizeAuthorizationSpec } from "#runtime/connections/validate-authorization.js";
|
|
5
5
|
import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
|
|
@@ -23,7 +23,10 @@ export async function resolveConnectionDefinition(definition, moduleMap, nodeId)
|
|
|
23
23
|
nodeId,
|
|
24
24
|
});
|
|
25
25
|
const resolvedRecord = expectObjectRecord(resolvedExportValue, `Expected the connection export "${definition.exportName ?? "default"}" from "${definition.logicalPath}" to return an object.`);
|
|
26
|
-
|
|
26
|
+
registerDefinitionSource(`connection:${resolvedRecord.url}`, {
|
|
27
|
+
kind: "connection",
|
|
28
|
+
name: definition.connectionName,
|
|
29
|
+
});
|
|
27
30
|
const hasAuth = resolvedRecord.auth !== undefined;
|
|
28
31
|
const hasHeaders = resolvedRecord.headers !== undefined;
|
|
29
32
|
const result = {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
|
|
2
|
-
import {
|
|
2
|
+
import { registerDefinitionSource } from "#public/tool-result-narrowing.js";
|
|
3
3
|
import { toErrorMessage } from "#shared/errors.js";
|
|
4
4
|
import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";
|
|
5
5
|
/**
|
|
@@ -21,7 +21,10 @@ export async function resolveToolDefinition(definition, moduleMap, nodeId) {
|
|
|
21
21
|
nodeId,
|
|
22
22
|
});
|
|
23
23
|
const resolvedRecord = expectObjectRecord(resolvedExportValue, describe(definition, "to return an object"));
|
|
24
|
-
|
|
24
|
+
registerDefinitionSource(`tool:${resolvedRecord.description}`, {
|
|
25
|
+
kind: "tool",
|
|
26
|
+
name: definition.name,
|
|
27
|
+
});
|
|
25
28
|
const execute = expectFunction(resolvedRecord.execute, describe(definition, "to provide an execute function"));
|
|
26
29
|
return {
|
|
27
30
|
description: definition.description,
|
package/package.json
CHANGED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-8L7ocgPr.js";import{C as t,T as n,i as r,r as i,w as a}from"./paths-DZTgjrW-.js";import{a as o,i as s,n as c,r as l}from"./authored-module-loader-XcFLnl49.js";import{a as u,i as d,n as f,o as p,r as m,t as h}from"./package-DmsQgn4v.js";import{g,m as ee,p as te}from"./types-MZUhN0Zy.js";import{a as ne,c as re,n as ie,o as ae,r as oe,t as se}from"./prewarm-BELT37PI.js";import{builtinModules as ce}from"node:module";import{dirname as _,extname as le,isAbsolute as ue,join as v,relative as y,resolve as b,sep as de}from"node:path";import{cp as x,mkdir as S,readFile as C,readdir as fe,realpath as pe,rename as w,rm as T,writeFile as E}from"node:fs/promises";import{randomUUID as me}from"node:crypto";import{existsSync as D,readFileSync as he}from"node:fs";import{fileURLToPath as ge}from"node:url";import{Buffer as _e}from"node:buffer";import{build as ve,copyPublicAssets as ye,createDevServer as be,createNitro as xe,prepare as Se,prerender as Ce}from"nitro/builder";const we=`ash-cache.json`;async function Te(e){let t=await Ee(e),n=h().version;t!==null&&t===n||await T(e,{force:!0,recursive:!0})}async function O(e){await S(e,{recursive:!0}),await E(v(e,we),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Ee(e){try{let t=JSON.parse(await C(v(e,we),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const De=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Oe(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await ke(e.filename,e.source),n=je(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Ke(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=qe(r,t.name);i.steps??={};let c=i.steps[e.filename]??={};if(c[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;a.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(s=!0,o.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):o.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${r}//${t.name}`;i.workflows??={};let c=i.workflows[e.filename]??={};c[t.name]={workflowId:n},e.mode===`workflow`?(a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),o.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(a.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let c=`/**__internal_workflows${JSON.stringify(i)}*/;`,l=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!l)return{code:`${c}\n${Ae(e.source,t,n,r)}`,workflowManifest:i};let u=Ie(e.source,a),d=e.mode===`workflow`?await Le(e.filename,u):u;return{code:`${s?`import { registerStepFunction } from "workflow/internal/private";\n${c}\n`:`${c}\n`}${d}${o.length>0?`\n${o.join(`
|
|
2
|
-
`)}\n`:``}`,workflowManifest:i}}async function ke(e,t){let{parseAst:n}=await o();return n(t,{astType:`ts`,lang:Ge(e),range:!0,sourceType:`module`},e)}function Ae(e,t,n,r){let i=Re(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=qe(r,e.name);return`${t}var ${e.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`}),o=[...i,...a];return o.length>0?`${o.join(`
|
|
3
|
-
`)}\n`:``}function je(e){let t=[];for(let n of e.body??[]){let e=Me(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Pe(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Fe(a[0]);o!==null&&t.push({directive:o.value,directiveEnd:o.end,directiveStart:o.start,exportPrefix:e.exported?`export `:``,name:i,rangeEnd:e.end,rangeStart:e.start})}return t}function Me(e){return e.type===`FunctionDeclaration`?Ne(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Ne(e.declaration,!0,e)}function Ne(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function Pe(e){return e===void 0||Array.isArray(e)?e:e.body}function Fe(e){let t=e?.directive??(e?.type===`ExpressionStatement`&&e.expression?.type===`Literal`?e.expression.value:void 0);return t!==`use workflow`&&t!==`use step`||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function Ie(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}async function Le(e,t){let n=await ke(e,t),r=He(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=Ve(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:We(t,e.end),start:e.start,text:``})}return i.length>0?Ie(t,i):t}function Re(e,t){let n=[];for(let r of t.body??[])r.type===`ExportNamedDeclaration`&&r.declaration?.type===`VariableDeclaration`&&r.declaration.kind===`const`&&r.start!==void 0&&r.end!==void 0&&(r.declaration.declarations??[]).every(ze)&&n.push(e.slice(r.start,r.end).trim());return n}function ze(e){return Be(e.init)}function Be(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?Be(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function Ve(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function He(e){let t=new Set;return k(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function k(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Ue(e)&&k(e,t);else Ue(n)&&k(n,t)}}function Ue(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function We(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
|
|
4
|
-
`?n+2:e[n]===`
|
|
5
|
-
`?n+1:n}function Ge(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}function Ke(e){return e.replace(/\.(?:[cm]?[jt]sx?)$/,``)}function qe(e,t){return De.has(t)?t:`step//${e}//${t}`}const Je={type:`queue/v2beta`,topic:`__wkf_workflow_*`,consumer:`default`,retryAfterSeconds:5,initialDelaySeconds:0},A=new Map,Ye=new Map;async function j(e,t,n,r,i){let a=i??process.cwd(),{moduleSpecifier:o}=Qe(r===void 0?ue(e)?e:v(a,e):r,a);return Oe({filename:e,mode:n,moduleSpecifier:o,source:t})}function Xe(e){return{hasSerde:e.includes(`workflow.serde`)||e.includes(`@serde`)||e.includes(`workflowSerde`)||e.includes(`__workflow_serde`),hasUseStep:/["']use step["']/.test(e),hasUseWorkflow:/["']use workflow["']/.test(e)}}function Ze(e,t){let n=P(e),r=!n&&nt(e,t);if(n||r){let n=M(e);if(n!==null){let i=tt(t).has(n.name);if(!(r||i))return{importPath:F(e,t),isPackage:!1};let a=$e(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:at(e,n)?{importPath:n.name,isPackage:!0}:{importPath:F(e,t),isPackage:!1}}}return{importPath:F(e,t),isPackage:!1}}function Qe(e,t){let n=P(e),r=!n&&nt(e,t);if(!n&&!r)return{moduleSpecifier:void 0};let i=M(e);if(i===null)return{moduleSpecifier:void 0};let a=$e(e,i);return{moduleSpecifier:a?`${i.name}${a}@${i.version}`:`${i.name}@${i.version}`}}function M(e){let t=_(e),n=[];for(;t!==_(t);){let e=A.get(t);if(e!==void 0){for(let t of n)A.set(t,e);return e}n.push(t);let r=v(t,`package.json`);if(D(r))try{let e=JSON.parse(he(r,`utf8`));if(typeof e.name==`string`&&typeof e.version==`string`){let r={dir:t,exports:e.exports,main:e.main,module:e.module,name:e.name,version:e.version};A.set(t,r);for(let e of n)A.set(e,r);return r}}catch{}t=_(t)}for(let e of n)A.set(e,null);return null}function $e(e,t){if(t.exports===null||typeof t.exports!=`object`||Array.isArray(t.exports))return``;let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`),i=n.startsWith(`${r}/`)?`./${n.substring(r.length+1)}`:null;if(i===null)return``;for(let[e,n]of Object.entries(t.exports)){let t=N(n);if(t!==null&&et(t)===i)return e===`.`?``:e.substring(1)}return``}function N(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=N(t);if(e!==null)return e}return null}if(typeof e==`object`&&e)for(let t of[`workflow`,`default`,`require`,`import`,`node`]){let n=e[t],r=N(n);if(r!==null)return r}return null}function et(e){return e.startsWith(`./`)?e:`./${e}`}function P(e){return e.split(de).join(`/`).includes(`/node_modules/`)}function tt(e){let t=Ye.get(e);if(t!==void 0)return t;let n=new Set,r=v(e,`package.json`);if(D(r))try{let e=JSON.parse(he(r,`utf8`));for(let t of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let r=e[t];if(typeof r==`object`&&r&&!Array.isArray(r))for(let e of Object.keys(r))n.add(e)}}catch{}return Ye.set(e,n),n}function nt(e,t){if(P(e))return!1;let n=M(e);return n===null||b(n.dir)===b(t)?!1:tt(t).has(n.name)}function F(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),i=r.startsWith(`${n}/`)?r.substring(n.length+1):y(t,e).replace(/\\/g,`/`);return i.startsWith(`.`)||(i=`./${i}`),i}function rt(e){if(typeof e==`string`||Array.isArray(e))return!0;if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>!e.startsWith(`.`))?!0:`.`in e}function it(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function at(e,t){let n=e.replace(/\\/g,`/`),r=t.dir.replace(/\\/g,`/`);if(!n.startsWith(`${r}/`))return!1;let i=n.substring(r.length+1);if(t.exports!==void 0){let e;if(t.exports!==null&&typeof t.exports==`object`&&`.`in t.exports)e=t.exports[`.`];else if(rt(t.exports))e=t.exports;else return!1;let n=N(e);return n!==null&&it(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[it(e)]:[]).includes(i)}const ot=`\0ash-workflow-entry`,st=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]);new Set([...ce,...ce.map(e=>`node:${e}`)]);const ct=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),lt=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function ut(e){let t=[];async function n(e){let r;try{r=await fe(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}for(let i of r){if(i.isDirectory()){lt.has(i.name)||await n(v(e,i.name));continue}if(!i.isFile())continue;let r=i.name.match(/\.[^.]+$/)?.[0];r!==void 0&&ct.has(r)&&t.push(v(e,i.name))}}return await n(e),t}function dt(e,t){let{importPath:n,isPackage:r}=Ze(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(bt(t,e))};`}function ft(e){return{name:`ash-workflow-virtual-entry`,resolveId(e){if(e===`\0ash-workflow-entry`)return{id:e}},load(t){if(t===`\0ash-workflow-entry`)return{code:e,moduleSideEffects:!0,moduleType:`js`}}}}function pt(){return{name:`ash-workflow-pseudo-packages`,resolveId(e){if(st.has(e))return{id:`\0ash-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0ash-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function mt(e,t={}){return{name:`ash-package-imports`,resolveId(n){let r=n.match(/^#compiled\/(.+)$/)?.[1];if(r!==void 0)return t.workflowCondition===!0&&r===`@workflow/core/index.js`?I([v(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),v(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):I([v(e,`.generated`,`compiled`,r),v(e,`dist`,`src`,`compiled`,r)]);let i=n.match(/^#(.+)\.js$/)?.[1];if(i!==void 0)return I([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[v(e,`src`,`${i}${t}`),v(e,`dist`,`src`,`${i}${t}`)]))}}}function ht(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`ash-workflow-transform`,async load(n){if(!wt(n))return;let r=await C(n,`utf8`),i=await j(Ct(e.workingDir,n),r.replace(/require\(\s*(['"])server-only\1\s*\)/g,`void 0`).replace(/require\(\s*(['"])client-only\1\s*\)/g,`void 0`),e.mode??`workflow`,n,e.projectRoot);return St(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function gt(e){let t=`// biome-ignore-all lint: generated file
|
|
6
|
-
/* eslint-disable */
|
|
7
|
-
import { workflowEntrypoint } from 'workflow/runtime';
|
|
8
|
-
|
|
9
|
-
const workflowCode = \`${(e.code.endsWith(`
|
|
10
|
-
`)?e.code:`${e.code}\n`).replace(/[\\`$]/g,`\\$&`)}\`;
|
|
11
|
-
|
|
12
|
-
export const POST = workflowEntrypoint(workflowCode);`;if(!e.bundleFinalOutput){await xt(e.outfile,t);return}let n=s(await l({cwd:e.workingDir,input:ot,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[ft(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await xt(e.outfile,n.code)}function _t(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function vt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function yt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function bt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function I(e){for(let t of e)if(D(t))return{id:b(t)}}async function xt(e,t){await S(_(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await E(n,t),await w(n,e)}function St(e,t){e.steps=L(e.steps,t.steps),e.workflows=L(e.workflows,t.workflows),e.classes=L(e.classes,t.classes)}function L(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function Ct(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function wt(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function R(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await E(n,t),await Tt(n,e)}async function Tt(e,t){if(process.platform!==`win32`){await w(e,t);return}for(let n=0;n<10;n+=1)try{await w(e,t);return}catch(e){if(!(e instanceof Error&&`code`in e&&(e.code===`EPERM`||e.code===`EACCES`||e.code===`EBUSY`))||n===9)throw e;await new Promise(e=>setTimeout(e,10*(n+1)))}}async function Et(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=await Ot({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=_(e.outfile),o=[`// Generated by Ash. Do not edit by hand.`,...Dt({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:z({outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,targetPath:e.builtinsPath}),outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,serdeOnlyFiles:r,stepFiles:t}),`export const __steps_registered = true;`,``].join(`
|
|
13
|
-
`);return await S(a,{recursive:!0}),await Mt(e.outfile)!==o&&await E(e.outfile,o),i}function Dt(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function z(e){return e.preferAbsoluteFileImports?t(e.targetPath):jt(e.outfileDirectory,e.targetPath)}async function Ot(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await C(r,`utf8`);kt(t,(await j(At(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function kt(e,t){e.steps=B(e.steps,t.steps),e.workflows=B(e.workflows,t.workflows),e.classes=B(e.classes,t.classes)}function B(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function At(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function jt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Mt(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const Nt=[`@mongodb-js/zstd`,`node-liblzma`],Pt=[`@chat-adapter/slack`,`chat`];function Ft(e){let t={};return It(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Lt(e){await T(e,{force:!0,recursive:!0}),await S(e,{recursive:!0})}async function Rt(e){try{return await pe(e.sourcePath)}catch{return await pe(e.fallbackPath)}}async function zt(e){let t=await Rt({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await Lt(e.targetPath),await x(t,e.targetPath,{dereference:!0,recursive:!0})}function Bt(e){let t=y(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function Vt(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
|
|
14
|
-
`)}async function Ht(e){try{let t=JSON.parse(await C(v(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function Ut(e){let t=await Ht(e.functionDirectoryPath),n=v(e.functionDirectoryPath,t),r=_(n),i=le(t),a=v(r,`__ash_nitro_handler__${i.length>0?i:`.mjs`}`),o=Bt({fromDirectoryPath:r,toFilePath:a});await w(n,a),await E(n,Vt({delegateImportPath:o,workflowRoutePath:e.workflowRoutePath}))}const Wt=new Map;var Gt=class{#e;#t;config;#n=new WeakMap;constructor(e){this.config={buildTarget:`standalone`,dirs:[m(`src/execution`)],externalPackages:[...Nt,...Pt],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.compiledArtifactsBootstrapPath,this.#t=e.outDir}async build(e={}){let t=(Wt.get(this.#t)??Promise.resolve()).then(()=>this.#r(e));Wt.set(this.#t,t.catch(()=>{})),await t}async#r(e){await Te(this.#t);let t=await this.#i();if(t.length===0)throw Error(`Expected the execution workflow source file under "${m(`src/execution`)}".`);let n=await this.findTsConfigPath();await S(this.#t,{recursive:!0});let r=await this.discoverEntries(t,this.#t,n),i=v(this.#t,`workflows.mjs`),{manifest:a}=await this.createWorkflowsBundle({discoveredEntries:r,keepInterimBundleContext:!1,outfile:i,bundleFinalOutput:!1,format:`esm`,inputFiles:t,tsconfigPath:n}),o=v(this.#t,`steps.mjs`),s=await Et({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:o,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),c=e.nitroStepOutfile;c!==void 0&&c!==o&&await Et({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:c,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),await Kt(i,o),await qt(i),await Jt(i);let l=e.nitroWorkflowOutfile;l!==void 0&&l!==i&&(await S(_(l),{recursive:!0}),await tn(i,l),c!==void 0&&(await Kt(l,c),await qt(l),await Jt(l))),await this.createManifest({workflowBundlePath:v(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...s.steps,...a.steps},workflows:{...s.workflows,...a.workflows},classes:{...s.classes,...a.classes}}}),await O(this.#t)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=v(e,t);try{return await C(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=_(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>b(this.config.workingDir,e));return(await Promise.all(e.map(e=>ut(e)))).flat()}async discoverEntries(e,t,n){let r=this.#n.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=Xe(await C(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#n.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:n=`cjs`,inputFiles:r,keepInterimBundleContext:i=this.config.watch,outfile:a,tsconfigPath:o}){let c=t??await this.discoverEntries(r,_(a),o),u=[...c.discoveredWorkflows].sort(),d=new Set(u),f=[...c.discoveredSerdeFiles].sort().filter(e=>!d.has(e)),p={},m=[...u.map(e=>dt(e,this.config.workingDir)),...f.map(e=>dt(e,this.config.workingDir))].join(`
|
|
15
|
-
`);return await gt({bundleFinalOutput:e,code:s(await l({cwd:this.config.workingDir,input:ot,platform:`neutral`,plugins:[ft(m),pt(),mt(this.config.workingDir,{workflowCondition:!0}),ht({manifest:p,projectRoot:this.transformProjectRoot,sideEffectFiles:[...u,...f],workingDir:this.config.workingDir})],resolve:{conditionNames:[`ash-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:o??!1,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${a}"`).code,format:n,outfile:a,workingDir:this.config.workingDir}),i?{bundleFinal:async t=>{await gt({bundleFinalOutput:e,code:t,format:n,outfile:a,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:p}:{manifest:p}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:_t(e.steps),workflows:vt(e.workflows),classes:yt(e.classes)},r=JSON.stringify(n,null,2);return await S(t,{recursive:!0}),await E(v(t,`manifest.json`),r),r}async buildVercelOutput(e){await this.build();let t=v(this.#t,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=v(t,`flow.func`),r=v(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),i=v(e.flowNitroOutputDir,`functions`,`__server.func`),a=v(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),o=v(r,`flow.func`),s=v(r,`step.func`),c=v(r,`webhook`,`[token].func`);await zt({fallbackPath:i,sourcePath:a,targetPath:n}),await Promise.all([this.#a(n,{experimentalTriggers:Array.from([Je]),maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),x(v(this.#t,`manifest.json`),v(t,`manifest.json`))]),await Ut({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([T(o,{force:!0,recursive:!0}),T(s,{force:!0,recursive:!0}),T(c,{force:!0,recursive:!0})]),await S(r,{recursive:!0}),await Promise.all([x(n,o,{recursive:!0}),x(v(t,`manifest.json`),v(r,`manifest.json`))])}async#i(){return[...await this.getInputFiles(),this.#e]}async#a(e,t){let n=v(e,`.vc-config.json`),r=await this.#o(n),i={...r};i.environment=Ft(r.environment),t.runtime!==null&&(i.runtime=t.runtime),t.maxDuration!==void 0&&(i.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(i.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(i.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(i.experimentalTriggers=[...t.experimentalTriggers]),await E(n,`${JSON.stringify(i,null,2)}\n`)}async#o(e){try{let t=JSON.parse(await C(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function Kt(e,t){let n=await V(e);if(n===null||n.includes(`__ashWorkflowStepsRegistered`))return;let r=$t(_(e),t),i=[`import { __steps_registered as __ashWorkflowStepsRegistered } from ${JSON.stringify(r)};`,`void __ashWorkflowStepsRegistered;`,``].join(`
|
|
16
|
-
`),a=n.match(/^import\s.+?;\n/m);if(a===null||a.index===void 0){await R(e,`${i}${n}`);return}let o=a.index+a[0].length;await R(e,`${n.slice(0,o)}${i}${n.slice(o)}`)}async function qt(e){let t=await V(e);if(t===null)return;let n=t;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let t=Qt(u(e));n=Zt(n,e,t)}n!==t&&await R(e,n)}async function Jt(e){let t=await V(e);if(t===null)return;let n=t.indexOf(`const workflowCode = `),r=t.lastIndexOf(`;
|
|
17
|
-
|
|
18
|
-
export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)return;let i=n+21,a=t.slice(i,r);if(!a.trimStart().startsWith("`"))return;let o=Xt(a,e),s=`${t.slice(0,i)}${Yt(o)}${t.slice(r)}`;s!==t&&await R(e,s)}function Yt(e){let t=_e.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function Xt(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function Zt(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function Qt(e){return t(e)}function $t(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function V(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function en(e){try{return await C(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function tn(e,t){let n=await C(e),r=await en(t);r!==null&&r.equals(n)||await R(t,n)}const nn=`\0ash-pruned-local-sandbox-backend`,rn=/[/\\]bindings[/\\]local\.js$/;function an(){return{name:`ash-hosted-sandbox-backend-prune`,load(e){return e===nn?[`export function createLocalSandboxBackend() {`,` throw new Error("The local sandbox backend is pruned from hosted server bundles.");`,`}`,``].join(`
|
|
19
|
-
`):null},resolveId(e){return rn.test(e)?nn:null}}}const on=`${g}/runs`,sn=`${g}/runs/:runId`,cn=`${g}/runs/:runId/steps`,ln=`${g}/runs/:runId/events`;function un(e){return e===`all`||e===`app`}function dn(e){return H(e)}function H(e){return e===`all`||e===`flow`}function U(e,t){let r=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,i=n(t.handlerPath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import handler from ${i};`,`export default handler;`].join(`
|
|
20
|
-
`)}function W(e){return v(e.options.buildDir,`workflow`)}function fn(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function pn(e,t){let n=v(W(e),`${t.bundleName}-handler.mjs`),r=_(n),i=fn(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=fn(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await E(n,mn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function mn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = await __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
21
|
-
`)}function hn(e,t){let r=`#ash-route${t.route}`,i=n(t.modulePath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import { ${t.handlerExport} } from ${i};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
22
|
-
`)}async function gn(e,n,r){if(dn(r.surface)){let t=f(),i=new Gt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:H(r.surface)?v(W(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&H(r.surface)?v(W(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});un(r.surface)&&(U(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),U(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),hn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:on}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:sn}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:cn}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:ln}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=W(e),o=H(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await pn(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function _n(){return`${g}/cron/${me()}`}function vn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=_n())}function yn(e){return{plugins:[c(),...e]}}function bn(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const xn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function Sn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const Cn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],wn=Symbol(`ash.workflow-transform-patched`),Tn=[`@napi-rs/keyring`];function En(){let e={};for(let t of Cn)e[t]=u(t);return e}function Dn(e){if(!e&&process.env.VERCEL)return`vercel`}function On(e){return e===`all`||e===`app`}function G(e){return e===`all`||e===`flow`}function K(e){return G(e)}function kn(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function An(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Tn,...xn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function q(e){return e.replaceAll(`\\`,`/`)}function jn(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Mn(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function J(e,t){return t.startsWith(`file://`)?q(Mn(jn(ge(t)))):ue(t)?q(Mn(jn(t))):q(Mn(jn(b(e,t))))}function Nn(e,t){let n=q(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function Pn(e){let t=q(e);return process.platform===`win32`?t.toLowerCase():t}function Fn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function Y(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?J(n===void 0?e:_(J(e,n)),t):null}async function In(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of Fn(n)){let n=Y(t,i,e);n!==null&&r.add(Pn(n))}return r}async function Ln(e,t){if(e.options.noExternals===!0)return;let n;try{n=await In(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Rn(e,t){let n=q(e).replace(/\/$/,``),r=q(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function zn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>J(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=Y(e.options.rootDir,t,r)??J(e.options.rootDir,t);return n.some(e=>Nn(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Bn(e,t){let n=null,r=async()=>(n===null&&(n=await In(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=Y(e.options.rootDir,t,n);return i===null||!(await r()).has(Pn(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Vn(e,t){let n=null,r=async()=>(n===null&&(n=await In(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=J(e.options.rootDir,n);return i.has(Pn(a))?{code:(await j(Rn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function Hn(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return q(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Un(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[wn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return Nn(t,n)?null:r.call(this,e,t,...i)},t[wn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&On(r)&&e.scheduleRegistrations.length>0,o=Dn(t),s=o===`vercel`?an():null,c=s===null?[]:[s],l=yn(c),u=yn(c),f=An(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Te(p);let g=await xe({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:K(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:Sn(o===`vercel`&&On(r))},t?{watch:!0}:void 0);if(await O(p),bn(g),G(r)){let t=En();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;zn(g,e.workflowBuildDir),Un(g,e.workflowBuildDir)}if(K(r)){let t=kn(g,e);Bn(g,{stepEntrypointPath:t}),Vn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&Hn(g,e.compiledArtifacts.instrumentationSourcePath),t&&G(r)){let t=e.workflowBuildDir,n=new Set([q(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(q(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(vn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await gn(g,e,{surface:r}),K(r)&&await Ln(g,kn(g,e)),g}function Wn(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}function Gn(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:2,generatorVersion:e.generatorVersion??h().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?Jn(t.instructions):null,schedules:t.schedules.map(Yn),tools:t.tools.map(Xn),skills:t.skills.map(Zn),connections:t.connections.map(Qn),channels:t.channels.filter(qn).map($n),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(er),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Kn(e){let t=Gn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await E(n,`${JSON.stringify(t,null,2)}\n`),n}function qn(e){return e.kind===`channel`}function Jn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Yn(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Xn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Zn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Qn(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type:`mcp`};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function $n(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Wn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function er(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function tr(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function nr(e){return tr()?(await se(e),!0):!1}function rr(e){return e.replace(/[\\/]+$/,``)}async function ir(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function ar(e){let t=new Gt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await ir(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function or(e){let t=rr(e.options.output.dir);return await Te(t),await Se(e),await ye(e),await Ce(e),await ve(e),await O(t),t}async function sr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await or(n)}finally{await n.close()}}async function cr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await or(e);return await Kn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await or(n);await nr({appRoot:t.appRoot,log(e){console.log(e)}});let r=await sr(t,`flow`);return await ar({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Kn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,lr=new Set([`[::]`,`::`,`0.0.0.0`]);function ur(e){let t=new URL(e);return lr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function dr(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function fr(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function pr(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function mr(e){let t=fr(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function hr(e){let t=process.env[Q],n=process.env[$],r=new URL(ur(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function gr(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function _r(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=gr(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function vr(e){let t=mr({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!dr(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function yr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=be(i);_r(a);let o=t.host??i.options.devServer.hostname,s=t.port??pr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await vr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=hr(e.url),await Se(i),await ve(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-DKDaaPea.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:ur(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var br=e({buildHost:()=>xr,startHost:()=>Sr});async function xr(e){return await cr(e)}async function Sr(e,t={}){return await yr(e,t)}export{Sr as n,br as t};
|