experimental-ash 0.25.0 → 0.25.2

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/src/channel/routes.d.ts +6 -1
  3. package/dist/src/channel/send.js +5 -2
  4. package/dist/src/channel/session-callback.d.ts +10 -0
  5. package/dist/src/channel/session-callback.js +65 -0
  6. package/dist/src/channel/types.d.ts +19 -0
  7. package/dist/src/chunks/{client-BShLWzR6.js → client-ZqNLLMZB.js} +3 -3
  8. package/dist/src/chunks/{compile-agent-75wLLW-E.js → compile-agent-C4OrJW6C.js} +1 -1
  9. package/dist/src/chunks/{dev-authored-source-watcher-DqoJsDup.js → dev-authored-source-watcher-PwAxalwl.js} +1 -1
  10. package/dist/src/chunks/host-F-DkwYJK.js +70 -0
  11. package/dist/src/chunks/paths-DnlVBqHu.js +85 -0
  12. package/dist/src/chunks/{token-BOkIxJeV.js → token-YW4VSeBB.js} +1 -1
  13. package/dist/src/chunks/types-BJSR0JNV.js +1 -0
  14. package/dist/src/cli/commands/info.js +1 -1
  15. package/dist/src/cli/dev/repl.js +3 -3
  16. package/dist/src/cli/run.js +1 -1
  17. package/dist/src/client/index.d.ts +1 -1
  18. package/dist/src/client/message-reducer.js +6 -0
  19. package/dist/src/context/keys.d.ts +1 -1
  20. package/dist/src/context/keys.js +1 -1
  21. package/dist/src/context/seed-keys.d.ts +5 -1
  22. package/dist/src/context/seed-keys.js +4 -0
  23. package/dist/src/evals/cli/eval.js +1 -1
  24. package/dist/src/execution/await-authorization-orchestrator.d.ts +0 -2
  25. package/dist/src/execution/await-authorization-orchestrator.js +12 -20
  26. package/dist/src/execution/connection-auth-steps.js +1 -4
  27. package/dist/src/execution/node-step.js +13 -0
  28. package/dist/src/execution/remote-agent-dispatch.d.ts +15 -0
  29. package/dist/src/execution/remote-agent-dispatch.js +79 -0
  30. package/dist/src/execution/runtime-context.js +4 -1
  31. package/dist/src/execution/session-callback-step.d.ts +16 -0
  32. package/dist/src/execution/session-callback-step.js +72 -0
  33. package/dist/src/execution/subagent-invocation.d.ts +16 -0
  34. package/dist/src/execution/subagent-invocation.js +16 -0
  35. package/dist/src/execution/subagent-tool.js +5 -8
  36. package/dist/src/execution/turn-workflow.js +0 -1
  37. package/dist/src/execution/workflow-entry.js +21 -1
  38. package/dist/src/execution/workflow-steps.d.ts +6 -3
  39. package/dist/src/execution/workflow-steps.js +79 -37
  40. package/dist/src/harness/execute-tool.d.ts +3 -3
  41. package/dist/src/harness/runtime-actions.d.ts +1 -0
  42. package/dist/src/harness/runtime-actions.js +18 -1
  43. package/dist/src/internal/application/package.js +1 -1
  44. package/dist/src/protocol/message.d.ts +6 -0
  45. package/dist/src/protocol/message.js +1 -0
  46. package/dist/src/protocol/routes.d.ts +11 -0
  47. package/dist/src/protocol/routes.js +13 -0
  48. package/dist/src/public/channels/ash.js +25 -1
  49. package/dist/src/runtime/actions/keys.js +2 -0
  50. package/dist/src/runtime/actions/types.d.ts +47 -1
  51. package/dist/src/runtime/actions/types.js +23 -0
  52. package/dist/src/runtime/connections/callback-route.d.ts +1 -1
  53. package/dist/src/runtime/connections/callback-route.js +1 -1
  54. package/dist/src/runtime/connections/mcp-client.d.ts +1 -2
  55. package/dist/src/runtime/connections/mcp-client.js +69 -3
  56. package/dist/src/runtime/framework-channels/index.js +7 -2
  57. package/dist/src/runtime/framework-tools/connection-search.d.ts +0 -46
  58. package/dist/src/runtime/framework-tools/connection-search.js +3 -78
  59. package/dist/src/runtime/framework-tools/connection-tools.d.ts +3 -6
  60. package/dist/src/runtime/framework-tools/connection-tools.js +6 -13
  61. package/dist/src/runtime/session-callback-route.d.ts +6 -0
  62. package/dist/src/runtime/session-callback-route.js +87 -0
  63. package/package.json +1 -1
  64. package/dist/src/chunks/host-JVy7fewA.js +0 -70
  65. package/dist/src/chunks/paths-DNjq5JOy.js +0 -85
  66. package/dist/src/chunks/types-CjIyrcYo.js +0 -1
@@ -1,7 +1,4 @@
1
- import { type AshContext } from "#context/container.js";
2
1
  import { ContextKey } from "#context/key.js";
3
- import { createConnectionAuthorizationRequiredEvent } from "#protocol/message.js";
4
- import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
5
2
  import { type ConnectionRegistry, type ConnectionToolMetadata } from "#runtime/connections/types.js";
6
3
  import type { ResolvedToolDefinition } from "#runtime/types.js";
7
4
  import { CONNECTION_AUTHORIZATION_PLACEHOLDER } from "#runtime/framework-tools/pending-connection-tool-calls.js";
@@ -24,24 +21,6 @@ export declare const ConnectionRegistryKey: ContextKey<ConnectionRegistry>;
24
21
  export interface DiscoveredConnectionToolsState {
25
22
  readonly byConnection: Readonly<Record<string, readonly ConnectionToolMetadata[]>>;
26
23
  }
27
- /**
28
- * One connection that requires user authorization before its tools
29
- * can be used.
30
- */
31
- export interface PendingConnectionAuthorization {
32
- readonly connectionName: string;
33
- readonly description: string;
34
- readonly authorization?: ConnectionAuthorizationChallenge;
35
- }
36
- /**
37
- * Durable context key for connections awaiting user authorization.
38
- *
39
- * Written by `connection_search` when a connection throws
40
- * {@link ConnectionAuthorizationRequiredError}. Read by the harness after
41
- * the step completes to emit `connection.authorization_required`
42
- * events and optionally suspend the workflow on a webhook.
43
- */
44
- export declare const PendingConnectionAuthorizationsKey: ContextKey<readonly PendingConnectionAuthorization[]>;
45
24
  /**
46
25
  * Durable context key for discovered connection tools.
47
26
  *
@@ -73,29 +52,4 @@ export declare function executeConnectionSearch(input: ConnectionSearchInput, me
73
52
  }): Promise<ConnectionSearchResultItem[] | typeof CONNECTION_AUTHORIZATION_PLACEHOLDER>;
74
53
  export declare function tokenize(text: string): string[];
75
54
  export declare function scoreMatch(queryTokens: string[], tool: ConnectionToolMetadata): number;
76
- /** Emit function passed to {@link drainPendingConnectionAuthorizations}. */
77
- type ConnectionAuthorizationEmitFn = (event: ReturnType<typeof createConnectionAuthorizationRequiredEvent>) => Promise<void>;
78
- /**
79
- * Emits queued non-interactive authorization-required events and clears
80
- * the drained entries.
81
- */
82
- export declare function drainPendingConnectionAuthorizations(params: {
83
- readonly ctx: AshContext;
84
- readonly emit: ConnectionAuthorizationEmitFn;
85
- readonly state: {
86
- readonly sequence: number;
87
- readonly stepIndex: number;
88
- readonly turnId: string;
89
- };
90
- }): Promise<void>;
91
- /**
92
- * Adds `pending` to {@link PendingConnectionAuthorizationsKey} if no
93
- * entry for the same `connectionName` already exists on the context.
94
- *
95
- * Single source of truth for the dedup-by-name rule: called from
96
- * `wrapConnectionToolExecute` (single connection per pending call) and
97
- * from the fan-out loop inside {@link executeConnectionSearch} (many
98
- * connections per search call).
99
- */
100
- export declare function recordPendingAuthorization(ctx: AshContext, pending: PendingConnectionAuthorization): void;
101
55
  export {};
@@ -1,7 +1,6 @@
1
1
  import { loadContext } from "#context/container.js";
2
2
  import { ContextKey } from "#context/key.js";
3
3
  import { createLogger } from "#internal/logging.js";
4
- import { createConnectionAuthorizationRequiredEvent } from "#protocol/message.js";
5
4
  import { isConnectionAuthorizationFailedError, isConnectionAuthorizationRequiredError, } from "#public/connections/errors.js";
6
5
  import { supportsInteractiveAuthorization, } from "#runtime/connections/types.js";
7
6
  import { qualifiedConnectionToolName } from "#runtime/framework-tools/connection-tools.js";
@@ -15,15 +14,6 @@ const logger = createLogger("framework.connection-search");
15
14
  * The `connectionProvider` reconstructs it each step.
16
15
  */
17
16
  export const ConnectionRegistryKey = new ContextKey("ash.connectionRegistry");
18
- /**
19
- * Durable context key for connections awaiting user authorization.
20
- *
21
- * Written by `connection_search` when a connection throws
22
- * {@link ConnectionAuthorizationRequiredError}. Read by the harness after
23
- * the step completes to emit `connection.authorization_required`
24
- * events and optionally suspend the workflow on a webhook.
25
- */
26
- export const PendingConnectionAuthorizationsKey = new ContextKey("ash.pendingConnectionAuthorizations");
27
17
  /**
28
18
  * Durable context key for discovered connection tools.
29
19
  *
@@ -70,7 +60,6 @@ export const CONNECTION_SEARCH_TOOL_DEFINITION = {
70
60
  name: "connection_search",
71
61
  onCompact({ ctx }) {
72
62
  ctx.set(DiscoveredConnectionToolsKey, { byConnection: {} });
73
- ctx.set(PendingConnectionAuthorizationsKey, []);
74
63
  ctx.set(PendingConnectionToolCallsKey, []);
75
64
  return {};
76
65
  },
@@ -96,7 +85,7 @@ export async function executeConnectionSearch(input, meta) {
96
85
  const discoveredByConnection = {
97
86
  ...previouslyDiscovered?.byConnection,
98
87
  };
99
- const pendingAuthorizations = [];
88
+ const authRequiredConnections = [];
100
89
  for (const conn of targetConnections) {
101
90
  let tools;
102
91
  try {
@@ -105,10 +94,7 @@ export async function executeConnectionSearch(input, meta) {
105
94
  }
106
95
  catch (err) {
107
96
  if (isConnectionAuthorizationRequiredError(err)) {
108
- pendingAuthorizations.push({
109
- connectionName: conn.connectionName,
110
- description: conn.description,
111
- });
97
+ authRequiredConnections.push(conn.connectionName);
112
98
  failedConnections.push({
113
99
  connection: conn.connectionName,
114
100
  description: conn.description,
@@ -169,17 +155,7 @@ export async function executeConnectionSearch(input, meta) {
169
155
  // Persist discovered tools so they materialize as first-class
170
156
  // AI SDK tools on the next step.
171
157
  ctx.set(DiscoveredConnectionToolsKey, { byConnection: discoveredByConnection });
172
- let interactiveConnectionNames = [];
173
- if (pendingAuthorizations.length > 0) {
174
- for (const auth of pendingAuthorizations) {
175
- recordPendingAuthorization(ctx, auth);
176
- }
177
- // Only connections with `startAuthorization` can suspend on a
178
- // framework-owned webhook.
179
- interactiveConnectionNames = pendingAuthorizations
180
- .map((a) => a.connectionName)
181
- .filter((name) => isInteractive(registry, name));
182
- }
158
+ const interactiveConnectionNames = authRequiredConnections.filter((name) => isInteractive(registry, name));
183
159
  // Suspend the entire tool call when at least one auth-required
184
160
  // connection has the full interactive-OAuth surface. The
185
161
  // connection-discover retry re-runs this search after tokens land,
@@ -240,60 +216,9 @@ export function scoreMatch(queryTokens, tool) {
240
216
  }
241
217
  return score;
242
218
  }
243
- /**
244
- * Emits queued non-interactive authorization-required events and clears
245
- * the drained entries.
246
- */
247
- export async function drainPendingConnectionAuthorizations(params) {
248
- const pending = params.ctx.get(PendingConnectionAuthorizationsKey);
249
- if (pending === undefined || pending.length === 0) {
250
- return;
251
- }
252
- const registry = params.ctx.get(ConnectionRegistryKey);
253
- const drained = [];
254
- const deferred = [];
255
- for (const auth of pending) {
256
- if (isInteractive(registry, auth.connectionName)) {
257
- deferred.push(auth);
258
- }
259
- else {
260
- drained.push(auth);
261
- }
262
- }
263
- for (const auth of drained) {
264
- const payload = {
265
- connectionName: auth.connectionName,
266
- description: auth.description,
267
- sequence: params.state.sequence,
268
- stepIndex: params.state.stepIndex,
269
- turnId: params.state.turnId,
270
- };
271
- if (auth.authorization !== undefined) {
272
- payload.authorization = auth.authorization;
273
- }
274
- await params.emit(createConnectionAuthorizationRequiredEvent(payload));
275
- }
276
- params.ctx.set(PendingConnectionAuthorizationsKey, deferred);
277
- }
278
219
  function isInteractive(registry, connectionName) {
279
220
  if (registry === undefined)
280
221
  return false;
281
222
  const def = registry.getConnections().find((c) => c.connectionName === connectionName);
282
223
  return supportsInteractiveAuthorization(def?.authorization);
283
224
  }
284
- /**
285
- * Adds `pending` to {@link PendingConnectionAuthorizationsKey} if no
286
- * entry for the same `connectionName` already exists on the context.
287
- *
288
- * Single source of truth for the dedup-by-name rule: called from
289
- * `wrapConnectionToolExecute` (single connection per pending call) and
290
- * from the fan-out loop inside {@link executeConnectionSearch} (many
291
- * connections per search call).
292
- */
293
- export function recordPendingAuthorization(ctx, pending) {
294
- const existing = ctx.get(PendingConnectionAuthorizationsKey) ?? [];
295
- if (existing.some((entry) => entry.connectionName === pending.connectionName)) {
296
- return;
297
- }
298
- ctx.set(PendingConnectionAuthorizationsKey, [...existing, pending]);
299
- }
@@ -24,12 +24,9 @@ export declare function resolveConnectionToolsFromState(registry: ConnectionRegi
24
24
  */
25
25
  type ToolExecuteFn = (args: unknown, options: unknown) => Promise<unknown>;
26
26
  /**
27
- * Wraps one connection tool's `execute` to translate
28
- * {@link ConnectionAuthorizationRequiredError} into the
29
- * await-authorization-and-splice protocol.
30
- *
31
- * Interactive auth records a pending retry and returns a placeholder
32
- * result; non-interactive auth returns a model-visible retryable error.
27
+ * Wraps one connection tool's `execute` to record a pending retry and
28
+ * return a placeholder when interactive auth is required. Non-interactive
29
+ * connections let the error propagate — the model sees the failure.
33
30
  */
34
31
  export declare function wrapConnectionToolExecute(params: {
35
32
  readonly connectionDefinition: ResolvedConnectionDefinition | undefined;
@@ -2,7 +2,7 @@ import { loadContext } from "#context/container.js";
2
2
  import { isConnectionAuthorizationRequiredError } from "#public/connections/errors.js";
3
3
  import { isObject } from "#shared/guards.js";
4
4
  import { supportsInteractiveAuthorization, } from "#runtime/connections/types.js";
5
- import { recordPendingAuthorization, } from "#runtime/framework-tools/connection-search.js";
5
+ import {} from "#runtime/framework-tools/connection-search.js";
6
6
  import { appendPendingConnectionToolCalls, CONNECTION_AUTHORIZATION_PLACEHOLDER, PendingConnectionToolCallsKey, } from "#runtime/framework-tools/pending-connection-tool-calls.js";
7
7
  /**
8
8
  * Builds the qualified tool name for a connection tool.
@@ -59,12 +59,9 @@ export async function resolveConnectionToolsFromState(registry, discovered, inpu
59
59
  return result;
60
60
  }
61
61
  /**
62
- * Wraps one connection tool's `execute` to translate
63
- * {@link ConnectionAuthorizationRequiredError} into the
64
- * await-authorization-and-splice protocol.
65
- *
66
- * Interactive auth records a pending retry and returns a placeholder
67
- * result; non-interactive auth returns a model-visible retryable error.
62
+ * Wraps one connection tool's `execute` to record a pending retry and
63
+ * return a placeholder when interactive auth is required. Non-interactive
64
+ * connections let the error propagate — the model sees the failure.
68
65
  */
69
66
  export function wrapConnectionToolExecute(params) {
70
67
  const { connectionDefinition, connectionName, originalExecute, toolName } = params;
@@ -80,12 +77,8 @@ export function wrapConnectionToolExecute(params) {
80
77
  }
81
78
  const toolCallId = readToolCallId(options);
82
79
  const isInteractive = supportsInteractiveAuthorization(connectionDefinition?.authorization);
83
- const ctx = loadContext();
84
- recordPendingAuthorization(ctx, {
85
- connectionName,
86
- description: connectionDefinition?.description ?? connectionName,
87
- });
88
80
  if (isInteractive && toolCallId !== undefined) {
81
+ const ctx = loadContext();
89
82
  const existing = ctx.get(PendingConnectionToolCallsKey);
90
83
  ctx.set(PendingConnectionToolCallsKey, appendPendingConnectionToolCalls(existing, [
91
84
  {
@@ -98,7 +91,7 @@ export function wrapConnectionToolExecute(params) {
98
91
  ]));
99
92
  return CONNECTION_AUTHORIZATION_PLACEHOLDER;
100
93
  }
101
- return { error: "authorization_required", retryable: true };
94
+ throw err;
102
95
  }
103
96
  };
104
97
  }
@@ -0,0 +1,6 @@
1
+ import type { RouteContext } from "#public/definitions/channel.js";
2
+ import type { ResolvedChannelDefinition } from "#runtime/types.js";
3
+ export declare const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "ash/v1/callback";
4
+ export declare function getSessionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[];
5
+ export declare function getSessionCallbackChannelNames(): ReadonlySet<string>;
6
+ export declare function handleSessionCallbackRequest(request: Request, ctx: RouteContext): Promise<Response>;
@@ -0,0 +1,87 @@
1
+ import { resumeHook } from "#compiled/@workflow/core/runtime.js";
2
+ import { ASH_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";
3
+ export const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "ash/v1/callback";
4
+ const HANDLED_METHODS = ["POST"];
5
+ export function getSessionCallbackChannelDefinitions() {
6
+ return HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method));
7
+ }
8
+ export function getSessionCallbackChannelNames() {
9
+ return new Set(HANDLED_METHODS.map(channelNameForMethod));
10
+ }
11
+ function buildCallbackChannelDefinition(method) {
12
+ const name = channelNameForMethod(method);
13
+ return {
14
+ name,
15
+ method,
16
+ urlPath: ASH_CALLBACK_ROUTE_PATTERN,
17
+ fetch: handleSessionCallbackRequest,
18
+ logicalPath: `framework://channels/${name}`,
19
+ sourceId: `ash:framework:session-callback-${method.toLowerCase()}`,
20
+ sourceKind: "module",
21
+ };
22
+ }
23
+ function channelNameForMethod(method) {
24
+ return `${HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX}/${method.toLowerCase()}`;
25
+ }
26
+ export async function handleSessionCallbackRequest(request, ctx) {
27
+ const token = ctx.params.token;
28
+ if (typeof token !== "string" || token.length === 0) {
29
+ return Response.json({ error: "Missing callback token.", ok: false }, { status: 400 });
30
+ }
31
+ let body;
32
+ try {
33
+ body = await request.json();
34
+ }
35
+ catch {
36
+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
37
+ }
38
+ const result = projectSessionCallbackResult(body);
39
+ if (result instanceof Response) {
40
+ return result;
41
+ }
42
+ try {
43
+ await resumeHook(token, {
44
+ kind: "runtime-action-result",
45
+ results: [result],
46
+ });
47
+ }
48
+ catch {
49
+ return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });
50
+ }
51
+ return Response.json({ ok: true }, { status: 202 });
52
+ }
53
+ function projectSessionCallbackResult(value) {
54
+ if (value === null || typeof value !== "object") {
55
+ return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
56
+ }
57
+ const payload = value;
58
+ if (typeof payload.callId !== "string" || payload.callId.length === 0) {
59
+ return Response.json({ error: "Missing callback callId.", ok: false }, { status: 400 });
60
+ }
61
+ if (typeof payload.subagentName !== "string" || payload.subagentName.length === 0) {
62
+ return Response.json({ error: "Missing callback subagentName.", ok: false }, { status: 400 });
63
+ }
64
+ if (payload.kind === "session.completed") {
65
+ return {
66
+ callId: payload.callId,
67
+ kind: "subagent-result",
68
+ output: typeof payload.output === "string" ? payload.output : "",
69
+ subagentName: payload.subagentName,
70
+ };
71
+ }
72
+ if (payload.kind === "session.failed") {
73
+ return {
74
+ callId: payload.callId,
75
+ isError: true,
76
+ kind: "subagent-result",
77
+ output: payload.error === undefined
78
+ ? {
79
+ code: "REMOTE_AGENT_FAILED",
80
+ message: "Remote agent failed.",
81
+ }
82
+ : payload.error,
83
+ subagentName: payload.subagentName,
84
+ };
85
+ }
86
+ return Response.json({ error: "Unsupported callback kind.", ok: false }, { status: 400 });
87
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "experimental-ash",
3
- "version": "0.25.0",
3
+ "version": "0.25.2",
4
4
  "bin": {
5
5
  "ash": "./bin/ash.js",
6
6
  "experimental-ash": "./bin/ash.js"
@@ -1,70 +0,0 @@
1
- import{n as e}from"./chunk-DSjMdhoD.js";import{A as t,C as n,D as r,E as i,M as a,O as o,S as s,T as c,_ as l,a as u,c as d,d as f,f as p,g as m,h as ee,i as te,j as h,k as g,l as ne,m as re,o as ie,r as ae,u as oe,v as se,w as ce,x as le}from"./paths-DNjq5JOy.js";import{a as ue,i as de,n as fe,r as pe,t as me}from"./authored-module-loader-DcCfCiBm.js";import{n as he}from"./compile-agent-75wLLW-E.js";import{t as ge}from"./errors-HYWjHxV6.js";import{f as _e,h as _,p as ve}from"./types-CjIyrcYo.js";import{loadDevelopmentEnvironmentFiles as ye}from"../cli/dev/environment.js";import{builtinModules as be}from"node:module";import{dirname as v,extname as xe,isAbsolute as Se,join as y,posix as Ce,relative as b,resolve as x,sep as we}from"node:path";import{cp as S,mkdir as C,readFile as w,readdir as T,realpath as E,rename as D,rm as O,symlink as Te,writeFile as k}from"node:fs/promises";import{createHash as Ee,randomUUID as De}from"node:crypto";import{existsSync as A,readFileSync as Oe}from"node:fs";import{fileURLToPath as ke}from"node:url";import{Buffer as Ae}from"node:buffer";import{build as je,copyPublicAssets as Me,createDevServer as Ne,createNitro as Pe,prepare as Fe,prerender as Ie}from"nitro/builder";const Le=`ash-cache.json`;async function Re(e){let t=await Be(e),n=r().version;t!==null&&t===n||await O(e,{force:!0,recursive:!0})}async function ze(e){await C(e,{recursive:!0}),await k(y(e,Le),`${JSON.stringify({ashVersion:r().version},null,2)}\n`)}async function Be(e){try{let t=JSON.parse(await w(y(e,Le),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const Ve=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function He(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await Ue(e.filename,e.source),n=Ge(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${ot(e.filename)}`,i=e.stableModuleSpecifier??r,a={},o=[],s=[],c=!1;for(let t of n){if(t.directive===`use step`){let n=st(r,t.name);a.steps??={};let i=a.steps[e.filename]??={};if(i[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;o.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else o.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(c=!0,s.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):s.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${e.stableWorkflowNames?.has(t.name)===!0?i:r}//${t.name}`;a.workflows??={};let l=a.workflows[e.filename]??={};l[t.name]={workflowId:n},e.mode===`workflow`?(o.push({end:t.directiveEnd,start:t.directiveStart,text:``}),s.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),s.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(o.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`)});`}),s.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let l=`/**__internal_workflows${JSON.stringify(a)}*/;`,u=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!u)return{code:`${l}\n${We(e.source,t,n,r)}`,workflowManifest:a};let d=Xe(e.source,o),f=e.mode===`workflow`?await Ze(e.filename,d):d;return{code:`${c?`import { registerStepFunction } from "workflow/internal/private";\n${l}\n`:`${l}\n`}${f}${s.length>0?`\n${s.join(`
2
- `)}\n`:``}`,workflowManifest:a}}async function Ue(e,t){let{parseAst:n}=await ue();return n(t,{astType:`ts`,lang:at(e),range:!0,sourceType:`module`},e)}function We(e,t,n,r){let i=Qe(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=st(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 Ge(e){let t=[];for(let n of e.body??[]){let e=Ke(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Je(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Ye(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 Ke(e){return e.type===`FunctionDeclaration`?qe(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:qe(e.declaration,!0,e)}function qe(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 Je(e){return e===void 0||Array.isArray(e)?e:e.body}function Ye(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 Xe(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 Ze(e,t){let n=await Ue(e,t),r=nt(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=tt(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:it(t,e.end),start:e.start,text:``})}return i.length>0?Xe(t,i):t}function Qe(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($e)&&n.push(e.slice(r.start,r.end).trim());return n}function $e(e){return et(e.init)}function et(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`?et(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function tt(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function nt(e){let t=new Set;return j(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function j(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)rt(e)&&j(e,t);else rt(n)&&j(n,t)}}function rt(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function it(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 at(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:/\.[cm]?ts$/.test(e)?`ts`:`js`}function ot(e){return e.replace(/\.(?:[cm]?[jt]sx?)$/,``)}function st(e,t){return Ve.has(t)?t:`step//${e}//${t}`}const ct={type:`queue/v2beta`,topic:`__wkf_workflow_*`,consumer:`default`,retryAfterSeconds:5,initialDelaySeconds:0},M=new Map,lt=new Map;async function N(e,t,n,r,i,a=ie){let o=i??process.cwd(),{moduleSpecifier:s,stableModuleSpecifier:c}=ft(r===void 0?Se(e)?e:y(o,e):r,o);return He({filename:e,mode:n,moduleSpecifier:s,source:t,stableModuleSpecifier:c,stableWorkflowNames:a})}function ut(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 dt(e,t){let n=gt(e),r=!n&&vt(e,t);if(n||r){let n=pt(e);if(n!==null){let i=_t(t).has(n.name);if(!(r||i))return{importPath:yt(e,t),isPackage:!1};let a=mt(e,n);return a?{importPath:`${n.name}${a}`,isPackage:!0}:St(e,n)?{importPath:n.name,isPackage:!0}:{importPath:yt(e,t),isPackage:!1}}}return{importPath:yt(e,t),isPackage:!1}}function ft(e,t){let n=gt(e),r=!n&&vt(e,t);if(!n&&!r)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let i=pt(e);if(i===null)return{moduleSpecifier:void 0,stableModuleSpecifier:void 0};let a=mt(e,i),o=a?`${i.name}${a}`:i.name;return{moduleSpecifier:`${o}@${i.version}`,stableModuleSpecifier:o}}function pt(e){let t=v(e),n=[];for(;t!==v(t);){let e=M.get(t);if(e!==void 0){for(let t of n)M.set(t,e);return e}n.push(t);let r=y(t,`package.json`);if(A(r))try{let e=JSON.parse(Oe(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};M.set(t,r);for(let e of n)M.set(e,r);return r}}catch{}t=v(t)}for(let e of n)M.set(e,null);return null}function mt(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=P(n);if(t!==null&&ht(t)===i)return e===`.`?``:e.substring(1)}return``}function P(e){if(typeof e==`string`)return e;if(Array.isArray(e)){for(let t of e){let e=P(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=P(n);if(r!==null)return r}return null}function ht(e){return e.startsWith(`./`)?e:`./${e}`}function gt(e){return e.split(we).join(`/`).includes(`/node_modules/`)}function _t(e){let t=lt.get(e);if(t!==void 0)return t;let n=new Set,r=y(e,`package.json`);if(A(r))try{let e=JSON.parse(Oe(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 lt.set(e,n),n}function vt(e,t){if(gt(e))return!1;let n=pt(e);return n===null||x(n.dir)===x(t)?!1:_t(t).has(n.name)}function yt(e,t){let n=t.replace(/\\/g,`/`),r=e.replace(/\\/g,`/`),i=r.startsWith(`${n}/`)?r.substring(n.length+1):b(t,e).replace(/\\/g,`/`);return i.startsWith(`.`)||(i=`./${i}`),i}function bt(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 xt(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.substring(2):t.startsWith(`/`)?t.substring(1):t}function St(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(bt(t.exports))e=t.exports;else return!1;let n=P(e);return n!==null&&xt(n)===i}return[t.module,t.main,`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`].flatMap(e=>typeof e==`string`?[xt(e)]:[]).includes(i)}const Ct=`\0ash-workflow-entry`,wt=new Set([`server-only`,`client-only`,`next/dist/compiled/server-only`,`next/dist/compiled/client-only`]);new Set([...be,...be.map(e=>`node:${e}`)]);const Tt=new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),Et=new Set([`node_modules`,`.git`,`.next`,`.nuxt`,`.output`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`.well-known`,`.svelte-kit`,`.turbo`,`.cache`,`.yarn`,`.pnpm-store`]);async function Dt(e){let t=[];async function n(e){let r;try{r=await T(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()){Et.has(i.name)||await n(y(e,i.name));continue}if(!i.isFile())continue;let r=i.name.match(/\.[^.]+$/)?.[0];r!==void 0&&Tt.has(r)&&t.push(y(e,i.name))}}return await n(e),t}function Ot(e,t){let{importPath:n,isPackage:r}=dt(e,t);return r?`import ${JSON.stringify(n)};`:`import ${JSON.stringify(Lt(t,e))};`}function kt(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 At(){return{name:`ash-workflow-pseudo-packages`,resolveId(e){if(wt.has(e))return{id:`\0ash-workflow-pseudo-package:${e}`}},load(e){if(e.startsWith(`\0ash-workflow-pseudo-package:`))return{code:``,moduleType:`js`}}}}function jt(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`?Rt([y(e,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.ts`),y(e,`dist`,`src`,`internal`,`workflow-bundle`,`workflow-core-shim.js`)]):Rt([y(e,`.generated`,`compiled`,r),y(e,`dist`,`src`,`compiled`,r)]);let i=n.match(/^#(.+)\.js$/)?.[1];if(i!==void 0)return Rt([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`].flatMap(t=>[y(e,`src`,`${i}${t}`),y(e,`dist`,`src`,`${i}${t}`)]))}}}function Mt(e){let t=new Set(e.sideEffectFiles?.map(e=>e.replaceAll(`\\`,`/`))??[]);return{name:`ash-workflow-transform`,async load(n){if(!Ut(n))return;let r=await w(n,`utf8`),i=await N(Ht(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 Bt(e.manifest,i.workflowManifest),{code:i.code,map:null,moduleSideEffects:t.has(n.replaceAll(`\\`,`/`))||void 0}}}}async function Nt(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 zt(e.outfile,t);return}let n=de(await pe({cwd:e.workingDir,input:Ct,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[kt(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await zt(e.outfile,n.code)}function Pt(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 Ft(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 It(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 Lt(e,t){let n=b(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function Rt(e){for(let t of e)if(A(t))return{id:x(t)}}async function zt(e,t){await C(v(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await k(n,t),await D(n,e)}function Bt(e,t){e.steps=Vt(e.steps,t.steps),e.workflows=Vt(e.workflows,t.workflows),e.classes=Vt(e.classes,t.classes)}function Vt(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 Ht(e,t){let n=t.replaceAll(`\\`,`/`),r=b(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function Ut(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function F(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await k(n,t),await D(n,e)}async function Wt(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=await qt({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=v(e.outfile),o=[`// Generated by Ash. Do not edit by hand.`,...Gt({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:Kt({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 C(a,{recursive:!0}),await Qt(e.outfile)!==o&&await k(e.outfile,o),i}function Gt(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>Kt({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>Kt({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function Kt(e){return e.preferAbsoluteFileImports?n(e.targetPath):Zt(e.outfileDirectory,e.targetPath)}async function qt(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await w(r,`utf8`);Jt(t,(await N(Xt(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function Jt(e,t){e.steps=Yt(e.steps,t.steps),e.workflows=Yt(e.workflows,t.workflows),e.classes=Yt(e.classes,t.classes)}function Yt(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 Xt(e,t){let n=t.replaceAll(`\\`,`/`),r=b(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function Zt(e,t){let n=b(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Qt(e){try{return await w(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const $t=`index.__ash_service_route_prefix.mjs`,en=[`ash/`,`.well-known/workflow/`];function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tn(e){return en.some(t=>e.startsWith(t))}function nn(e,t){return e.filter(rn).map(e=>on(e,t))}function rn(e){if(!I(e)||`handle`in e)return!0;let t=typeof e.src==`string`?e.src:``,n=typeof e.dest==`string`?e.dest:``;return L(t)||L(n)}function L(e){return e.includes(`/ash/v1`)||e.includes(`/.well-known/workflow/`)}function an(e){return e.includes(`/ash/v1`)}function on(e,t){if(!I(e)||`handle`in e||typeof e.src!=`string`)return e;let n=an(e.src)||typeof e.dest==`string`&&an(e.dest),r={...e,src:sn(e.src,t)};return n&&(r.dest=`/ash/__server`),r}function sn(e,t){if(t===void 0||t===`/`||!L(e)||e.includes(t))return e;let n=t.endsWith(`/`)?t.slice(0,-1):t,r=n.replaceAll(`/`,`\\/`);return e.includes(r)?e:e.startsWith(`^(?:/`)?`^(?:${n}${e.slice(4)}`:e.startsWith(`^/`)?`^${n}${e.slice(1)}`:e.startsWith(`/`)?`${n}${e}`:e}async function cn(e,t){let n=y(e,`.vc-config.json`),r=y(e,$t),i=JSON.parse(await w(n,`utf8`)),a=I(i)?i:{};await k(r,ln(t)),await k(n,`${JSON.stringify({...a,handler:$t},null,2)}\n`)}function ln(e){return`
14
- import { Server } from "node:http";
15
-
16
- const SERVICE_PREFIX = ${JSON.stringify(un(e))};
17
- const PATCH_SYMBOL = Symbol.for("ash.service.route-prefix-strip.patch");
18
-
19
- function stripServiceRoutePrefix(requestUrl) {
20
- if (typeof requestUrl !== "string" || requestUrl === "*") {
21
- return requestUrl;
22
- }
23
-
24
- const queryIndex = requestUrl.indexOf("?");
25
- const rawPath = queryIndex === -1 ? requestUrl : requestUrl.slice(0, queryIndex);
26
- const query = queryIndex === -1 ? "" : requestUrl.slice(queryIndex);
27
- const path = rawPath.startsWith("/") ? rawPath : \`/\${rawPath}\`;
28
-
29
- if (path === SERVICE_PREFIX) {
30
- return \`/\${query}\`;
31
- }
32
-
33
- if (path.startsWith(\`\${SERVICE_PREFIX}/\`)) {
34
- return path.slice(SERVICE_PREFIX.length) + query;
35
- }
36
-
37
- return path + query;
38
- }
39
-
40
- if (!globalThis[PATCH_SYMBOL]) {
41
- globalThis[PATCH_SYMBOL] = true;
42
- const originalEmit = Server.prototype.emit;
43
- Server.prototype.emit = function patchedEmit(event, request, ...args) {
44
- if (event === "request" && request && typeof request.url === "string") {
45
- request.url = stripServiceRoutePrefix(request.url);
46
- }
47
-
48
- return originalEmit.call(this, event, request, ...args);
49
- };
50
- }
51
-
52
- const originalModule = await import("./index.mjs");
53
- const entrypoint = originalModule?.default ?? originalModule;
54
-
55
- export default entrypoint;
56
- `.trimStart()}function un(e){let t=(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``);return t.length===0?`/`:t}const dn=[`@mongodb-js/zstd`,`node-liblzma`],fn=[`@chat-adapter/slack`,`chat`];function pn(e){let t={};return mn(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function hn(e){await O(e,{force:!0,recursive:!0}),await C(e,{recursive:!0})}async function gn(e){try{return await E(e.sourcePath)}catch{return await E(e.fallbackPath)}}async function _n(e){let t=await gn({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await hn(e.targetPath),await S(t,e.targetPath,{dereference:!0,recursive:!0})}async function vn(e,t={}){let n=y(e,`functions`),r=await yn(n);r!==null&&(t.servicePrefix!==void 0&&await cn(r,t.servicePrefix),await bn(n,r)),await Sn(n,n),await Cn(e,t.servicePrefix)}async function yn(e){let t=y(e,`__server.func`),n=y(e,`ash/__server.func`),r;try{r=await E(t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let i=`${n}.ash-staging`;return await C(v(n),{recursive:!0}),await O(i,{force:!0,recursive:!0}),await S(r,i,{dereference:!0,recursive:!0}),await O(n,{force:!0,recursive:!0}),await D(i,n),n}async function bn(e,t,n=e){let r;try{r=await T(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(r.map(async r=>{let i=y(e,r.name),a=R(b(n,i));if(r.isSymbolicLink()){r.name.endsWith(`.func`)&&tn(a)&&await xn(i,t);return}r.isDirectory()&&!r.name.endsWith(`.func`)&&await bn(i,t,n)}))}async function xn(e,t){await O(e,{force:!0,recursive:!0}),await Te(R(b(v(e),t)),e,`dir`)}async function Sn(e,t){let n;try{n=await T(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let r=y(t,n.name),i=R(b(e,r));if(n.name.endsWith(`.func`)){tn(i)||await O(r,{force:!0,recursive:!0});return}n.isDirectory()&&await Sn(e,r)}))}async function Cn(e,t){let n=y(e,`config.json`),r;try{r=JSON.parse(await w(n,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!mn(r)||!Array.isArray(r.routes)||(r.routes=nn(r.routes,t),await k(n,`${JSON.stringify(r,null,2)}\n`))}function R(e){return e.replaceAll(`\\`,`/`)}function wn(e){let t=b(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function Tn(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(`
57
- `)}async function En(e){try{let t=JSON.parse(await w(y(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function Dn(e){let t=await En(e.functionDirectoryPath),n=y(e.functionDirectoryPath,t),r=v(n),i=xe(t),a=y(r,`__ash_nitro_handler__${i.length>0?i:`.mjs`}`),o=wn({fromDirectoryPath:r,toFilePath:a});await D(n,a),await k(n,Tn({delegateImportPath:o,workflowRoutePath:e.workflowRoutePath}))}const On=new Map;var kn=class{#e;#t;config;#n=new WeakMap;constructor(e){this.config={buildTarget:`standalone`,dirs:[g(`src/execution`)],externalPackages:[...dn,...fn],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.compiledArtifactsBootstrapPath,this.#t=e.outDir}async build(e={}){let t=(On.get(this.#t)??Promise.resolve()).then(()=>this.#r(e));On.set(this.#t,t.catch(()=>{})),await t}async#r(e){await Re(this.#t);let t=await this.#i();if(t.length===0)throw Error(`Expected the execution workflow source file under "${g(`src/execution`)}".`);let n=await this.findTsConfigPath();await C(this.#t,{recursive:!0});let r=await this.discoverEntries(t,this.#t,n),i=y(this.#t,`workflows.mjs`),{manifest:a}=await this.createWorkflowsBundle({discoveredEntries:r,keepInterimBundleContext:!1,outfile:i,bundleFinalOutput:!1,format:`esm`,inputFiles:t,tsconfigPath:n}),o=y(this.#t,`steps.mjs`),s=await Wt({builtinsPath:h(`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 Wt({builtinsPath:h(`workflow/internal/builtins`),discoveredEntries:r,outfile:c,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),await An(i,o),await jn(i),await Mn(i);let l=e.nitroWorkflowOutfile;l!==void 0&&l!==i&&(await C(v(l),{recursive:!0}),await zn(i,l),c!==void 0&&(await An(l,c),await jn(l),await Mn(l))),await this.createManifest({workflowBundlePath:y(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...s.steps,...a.steps},workflows:{...s.workflows,...a.workflows},classes:{...s.classes,...a.classes}}}),await ze(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=y(e,t);try{return await w(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=v(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>x(this.config.workingDir,e));return(await Promise.all(e.map(e=>Dt(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=ut(await w(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 s=t??await this.discoverEntries(r,v(a),o),c=[...s.discoveredWorkflows].sort(),l=new Set(c),u=[...s.discoveredSerdeFiles].sort().filter(e=>!l.has(e)),d={},f=[...c.map(e=>Ot(e,this.config.workingDir)),...u.map(e=>Ot(e,this.config.workingDir))].join(`
58
- `);return await Nt({bundleFinalOutput:e,code:de(await pe({cwd:this.config.workingDir,input:Ct,platform:`neutral`,plugins:[kt(f),At(),jt(this.config.workingDir,{workflowCondition:!0}),Mt({manifest:d,projectRoot:this.transformProjectRoot,sideEffectFiles:[...c,...u],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 Nt({bundleFinalOutput:e,code:t,format:n,outfile:a,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:d}:{manifest:d}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:Pt(e.steps),workflows:Ft(e.workflows),classes:It(e.classes)},r=JSON.stringify(n,null,2);return await C(t,{recursive:!0}),await k(y(t,`manifest.json`),r),r}async buildVercelOutput(e){await this.build();let t=y(this.#t,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=y(t,`flow.func`),r=y(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),i=y(e.flowNitroOutputDir,`functions`,`__server.func`),a=y(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),o=y(r,`flow.func`),s=y(r,`step.func`),c=y(r,`webhook`,`[token].func`);await _n({fallbackPath:i,sourcePath:a,targetPath:n}),await Promise.all([this.#a(n,{experimentalTriggers:Array.from([ct]),maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),S(y(this.#t,`manifest.json`),y(t,`manifest.json`))]),await Dn({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([O(o,{force:!0,recursive:!0}),O(s,{force:!0,recursive:!0}),O(c,{force:!0,recursive:!0})]),await C(r,{recursive:!0}),await Promise.all([S(n,o,{recursive:!0}),S(y(t,`manifest.json`),y(r,`manifest.json`))])}async#i(){return[...await this.getInputFiles(),this.#e]}async#a(e,t){let n=y(e,`.vc-config.json`),r=await this.#o(n),i={...r};i.environment=pn(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 k(n,`${JSON.stringify(i,null,2)}\n`)}async#o(e){try{let t=JSON.parse(await w(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function An(e,t){let n=await z(e);if(n===null||n.includes(`__ashWorkflowStepsRegistered`))return;let r=Ln(v(e),t),i=[`import { __steps_registered as __ashWorkflowStepsRegistered } from ${JSON.stringify(r)};`,`void __ashWorkflowStepsRegistered;`,``].join(`
59
- `),a=n.match(/^import\s.+?;\n/m);if(a===null||a.index===void 0){await F(e,`${i}${n}`);return}let o=a.index+a[0].length;await F(e,`${n.slice(0,o)}${i}${n.slice(o)}`)}async function jn(e){let t=await z(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=In(h(e));n=Fn(n,e,t)}n!==t&&await F(e,n)}async function Mn(e){let t=await z(e);if(t===null)return;let n=t.indexOf(`const workflowCode = `),r=t.lastIndexOf(`;
60
-
61
- 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=Pn(a,e),s=`${t.slice(0,i)}${Nn(o)}${t.slice(r)}`;s!==t&&await F(e,s)}function Nn(e){let t=Ae.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function Pn(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 Fn(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function In(e){return n(e)}function Ln(e,t){let n=b(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function z(e){try{return await w(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function Rn(e){try{return await w(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function zn(e,t){let n=await w(e),r=await Rn(t);r!==null&&r.equals(n)||await F(t,n)}function B(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:t(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const Bn=`\0ash-pruned-local-sandbox-backend`,Vn=/[/\\]bindings[/\\]local\.js$/;function Hn(){return{name:`ash-hosted-sandbox-backend-prune`,load(e){return e===Bn?[`export function createLocalSandboxBackend() {`,` throw new Error("The local sandbox backend is pruned from hosted server bundles.");`,`}`,``].join(`
62
- `):null},resolveId(e){return Vn.test(e)?Bn:null}}}const Un=`${_}/runs`,Wn=`${_}/runs/:runId`,Gn=`${_}/runs/:runId/steps`,Kn=`${_}/runs/:runId/events`,V=`#ash-channel/`;function qn(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,a=ne();for(let e of t){if(e.kind===`disabled`){if(!a.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: ${[...a].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let o=oe().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),s=new Set,c=[];for(let e of[...o,...r]){let t=Xn(e);s.has(t)||(s.add(t),c.push(e))}return c}function Jn(e,t){for(let n of t.registrations)Zn(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function Yn(e,t){return er(t.previous,t.next)?!1:(Qn(e),Jn(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function Xn(e){return`${e.method.toUpperCase()} ${e.route}`}function Zn(e,n){let r=Xn(n),i=`${V}${r}`,a=c(t(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:n.method,route:n.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(n.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
63
- `)}function Qn(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&$n(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(V)&&delete e.options.virtual[t]}function $n(e){return e.handler.startsWith(V)}function er(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}function tr(e){return e===`all`||e===`app`}function nr(e){return H(e)}function H(e){return e===`all`||e===`flow`}function U(e,t){let n=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,r=c(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
64
- `)}function W(e){return y(e.options.buildDir,`workflow`)}function rr(e,t){let n=b(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function ir(e,t){let n=y(W(e),`${t.bundleName}-handler.mjs`),r=v(n),i=rr(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=rr(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await C(r,{recursive:!0}),await k(n,ar({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function ar(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(`
65
- `)}function or(e,t){let n=`#ash-route${t.route}`,r=c(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
66
- `)}async function sr(e,r,i){if(nr(i.surface)){let t=o(),n=new kn({appRoot:r.appRoot,compiledArtifactsBootstrapPath:r.compiledArtifacts.bootstrapPath,outDir:r.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),s=async()=>{await n.build({nitroStepOutfile:H(i.surface)?y(W(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&H(i.surface)?y(W(e),`workflows.mjs`):void 0})},c=async()=>{let e=a.then(s);a=e.catch(()=>{}),await e},l=!0;await c(),e.hooks.hook(`build:before`,async()=>{if(l){l=!1;return}await c()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await c()})}let a=B({appRoot:r.appRoot,dev:e.options.dev});tr(i.surface)&&(U(e,{handlerPath:t(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),U(e,{handlerPath:t(`src/internal/nitro/routes/health.ts`),method:`GET`,route:_e}),or(e,{args:JSON.stringify({appRoot:a.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:t(`src/internal/nitro/routes/info.ts`),route:ve}),U(e,{handlerPath:t(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:Un}),U(e,{handlerPath:t(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:Wn}),U(e,{handlerPath:t(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:Gn}),U(e,{handlerPath:t(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:Kn}),Jn(e,{artifactsConfig:a,registrations:qn(r)}));let s=W(e),c=H(i.surface)?e.options.dev?y(s,`workflows.mjs`):y(r.workflowBuildDir,`workflows.mjs`):void 0,l=e.options.dev&&c!==void 0?[{bundlePath:c,queuePrefix:`__wkf_workflow_`}]:[],u=l.length>0?n(h(`workflow/runtime`)):void 0;c&&await ir(e,{bundleName:`workflows`,bundlePath:c,directHandlers:l,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:u}),e.routing.sync()}function cr(){return`${_}/cron/${De()}`}function lr(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=cr())}function ur(e){return{plugins:[fe(),...e]}}function dr(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=ce(e);return n===e?null:{code:n,map:null}}})})}const fr=`ash.schedule.`;var pr=class extends Error{scheduleId;sourceId;taskName;constructor(e,t={}){super(e),this.name=`ScheduleRegistrationError`,t.scheduleId!==void 0&&(this.scheduleId=t.scheduleId),t.sourceId!==void 0&&(this.sourceId=t.sourceId),t.taskName!==void 0&&(this.taskName=t.taskName)}};function mr(e){let t=e.map(e=>({cron:e.cron,description:`Run Ash schedule "${e.name}" from "${e.logicalPath}".`,logicalPath:e.logicalPath,scheduleId:e.name,sourceId:e.sourceId,taskName:gr(e.sourceId)})).sort((e,t)=>e.sourceId.localeCompare(t.sourceId));return hr(t),t}function hr(e){let t=new Map;for(let n of e){let e=t.get(n.scheduleId);if(e===void 0){t.set(n.scheduleId,n);continue}throw new pr(`Duplicate authored schedule id "${n.scheduleId}" found in "${e.logicalPath}" and "${n.logicalPath}".`,{scheduleId:n.scheduleId,sourceId:n.sourceId,taskName:n.taskName})}}function gr(e){return`${fr}${Buffer.from(e,`utf8`).toString(`base64url`)}`}const _r=`#ash-schedule-task/`;function vr(e,t){if(t.registrations.length!==0){e.options.experimental.tasks=!0;for(let n of t.registrations)xr(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registration:n})}}function yr(e,t){let n=!wr(t.previous,t.next);return br(e),vr(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registrations:t.next}),n}function br(e){for(let t of Object.keys(e.options.tasks))t.startsWith(`ash.schedule.`)&&delete e.options.tasks[t];for(let t of Object.keys(e.options.virtual))t.startsWith(_r)&&delete e.options.virtual[t];for(let[t,n]of Object.entries(e.options.scheduledTasks)){let r=Cr(n).filter(e=>!e.startsWith(fr));if(r.length===0){delete e.options.scheduledTasks[t];continue}if(r.length===1){let[n]=r;n!==void 0&&(e.options.scheduledTasks[t]=n);continue}e.options.scheduledTasks[t]=r}}function xr(e,t){let n=`${_r}${t.registration.taskName}`,r=c(t.dispatchModulePath);e.options.tasks[t.registration.taskName]={description:t.registration.description,handler:n},e.options.virtual[n]=[`import { dispatchScheduleTask } from ${r};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default {`,` meta: { description: ${JSON.stringify(t.registration.description)} },`,` async run(event) {`,` return { result: await dispatchScheduleTask(event.name, config) };`,` },`,`};`].join(`
67
- `),Sr(e,t.registration.cron,t.registration.taskName)}function Sr(e,t,n){let r=e.options.scheduledTasks[t];if(r===void 0){e.options.scheduledTasks[t]=n;return}if(typeof r==`string`){e.options.scheduledTasks[t]=[r,n];return}r.includes(n)||r.push(n)}function Cr(e){return typeof e==`string`?[e]:[...e]}function wr(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.cron!==i.cron||r.description!==i.description||r.logicalPath!==i.logicalPath||r.scheduleId!==i.scheduleId||r.sourceId!==i.sourceId||r.taskName!==i.taskName)return!1}return!0}const Tr=`@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 Er(e){if(e)return{config:{version:3,framework:{version:r().version}}}}const Dr=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],Or=Symbol(`ash.workflow-transform-patched`),kr=[`@napi-rs/keyring`];function Ar(){let e={};for(let t of Dr)e[t]=h(t);return e}function jr(e){if(!e&&process.env.VERCEL)return`vercel`}function Mr(e){return e===`all`||e===`app`}function G(e){return e===`all`||e===`flow`}function Nr(e){return G(e)}function Pr(e,t){return e.options.dev?y(e.options.buildDir,`workflow`,`steps.mjs`):y(t.workflowBuildDir,`steps.mjs`)}function Fr(e){let t=e.compileResult.manifest.config.build;return[...new Set([...kr,...Tr,...t?.externalDependencies??[]])].filter(e=>e!==a)}function K(e){return e.replaceAll(`\\`,`/`)}function Ir(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 Lr(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?K(Lr(Ir(ke(t)))):Se(t)?K(Lr(Ir(t))):K(Lr(Ir(x(e,t))))}function Rr(e,t){let n=K(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function zr(e){let t=K(e);return process.platform===`win32`?t.toLowerCase():t}function Br(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 Vr(e,t,n){return t.startsWith(`workflow`)?h(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:v(q(e,n)),t):null}async function Hr(e,t){let n=await w(e,`utf8`),r=new Set;for(let i of Br(n)){let n=Vr(t,i,e);n!==null&&r.add(zr(n))}return r}async function Ur(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Hr(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 Wr(e,t){let n=K(e).replace(/\/$/,``),r=K(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=b(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 Gr(e,t){let n=[t,y(e.options.buildDir,`workflow`)].map(t=>q(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=Vr(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>Rr(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Kr(e,t){let n=null,r=async()=>(n===null&&(n=await Hr(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=Vr(e.options.rootDir,t,n);return i===null||!(await r()).has(zr(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function qr(e,t){let n=null,r=async()=>(n===null&&(n=await Hr(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=q(e.options.rootDir,n);return i.has(zr(a))?{code:(await N(Wr(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function Jr(e,t){let n=K(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return K(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Yr(e,t){let n=K(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[Or]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return Rr(t,n)?null:r.call(this,e,t,...i)},t[Or]=!0}})}async function J(e,n,r={}){let i=r.surface??`all`,a=(!n||r.schedules===!0)&&Mr(i)&&e.scheduleRegistrations.length>0,o=jr(n),s=o===`vercel`?Hn():null,c=s===null?[]:[s],l=ur(c),u=ur(c),d=Fr(e),f=ae(e.appRoot,i),p=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Re(f);let m=await Pe({_cli:{command:n?`dev`:`build`},buildDir:f,dev:n,logLevel:n?1:void 0,output:r.outputDir===void 0?void 0:{dir:r.outputDir},preset:o,plugins:p,publicAssets:[],scanDirs:Nr(i)?[g(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:d,vercel:Er(o===`vercel`&&Mr(i))},n?{watch:!0}:void 0);if(await ze(f),dr(m),G(i)){let t=Ar();for(let[e,n]of Object.entries(t))m.options.alias[e]=n;Gr(m,e.workflowBuildDir),Yr(m,e.workflowBuildDir)}if(Nr(i)){let t=Pr(m,e);Kr(m,{stepEntrypointPath:t}),qr(m,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&Jr(m,e.compiledArtifacts.instrumentationSourcePath),n&&G(i)){let t=e.workflowBuildDir,n=new Set([K(y(t,`workflows.mjs`))]);m.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(K(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(lr(m),vr(m,{artifactsConfig:B({appRoot:e.appRoot,dev:m.options.dev}),dispatchModulePath:t(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await sr(m,e,{surface:i}),Nr(i)&&await Ur(m,Pr(m,e)),m}function Xr(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 Zr(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:2,generatorVersion:e.generatorVersion??r().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?ei(t.instructions):null,schedules:t.schedules.map(ti),tools:t.tools.map(ni),skills:t.skills.map(ri),connections:t.connections.map(ii),channels:t.channels.filter($r).map(ai),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(oi),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Qr(e){let t=Zr({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=y(e.appRoot,`.ash/agent-summary.json`);return await C(v(n),{recursive:!0}),await k(n,`${JSON.stringify(t,null,2)}\n`),n}function $r(e){return e.kind===`channel`}function ei(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function ti(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function ni(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function ri(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function ii(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 ai(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Xr(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function oi(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}async function si(e){return[...e.manifest.schedules].map(e=>{let t={cron:e.cron,hasRun:e.hasRun,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.markdown===void 0?t:{...t,markdown:e.markdown}})}async function ci(e){return await si({manifest:await p({compiledArtifactsSource:e.compiledArtifactsSource})})}async function li(e){let n=y(e.outDir,`compiled-artifacts-bootstrap.mjs`),r=y(e.outDir,`compiled-artifacts-instrumentation.mjs`),i=di(e.compileResult.manifest.agentRoot);await C(e.outDir,{recursive:!0}),await k(n,await pi({compileResult:e.compileResult,installModulePath:t(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:n,metadata:e.compileResult.metadata})),i!==void 0&&await k(r,mi({agentName:e.compileResult.manifest.config.name,instrumentationPath:i,registerConfigPath:t(`src/harness/instrumentation-config.ts`)}));let a={bootstrapPath:n};return i!==void 0&&(a.instrumentationPluginPath=r,a.instrumentationSourcePath=i),a}const ui=[`.ts`,`.mts`,`.js`,`.mjs`];function di(e){for(let t of ui){let n=y(e,`instrumentation${t}`);if(A(n))return n}}function fi(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
68
- `)}async function pi(e){let t=fi(s({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Ash. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${c(e.installModulePath)};`,``,t,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __ashInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
69
- `)}function mi(e){return[`// Generated by Ash. Do not edit by hand.`,`import * as instrumentationModule from ${c(e.instrumentationPath)};`,`import { registerInstrumentationConfig } from ${c(e.registerConfigPath)};`,``,`if (instrumentationModule.default != null) {`,` registerInstrumentationConfig(instrumentationModule.default, { agentName: ${JSON.stringify(e.agentName)} });`,`}`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installInstrumentationPlugin() {}`,``].join(`
70
- `)}function hi(e){return m(e,{moduleMapLoaderPath:t(`src/internal/authored-module-map-loader.ts`)})}async function gi(e){let t=await he({startPath:e}),n=await ci({compiledArtifactsSource:hi(t.project.appRoot)}),r=mr(n),i=u(t.project.appRoot),a=await li({compileResult:t,outDir:t.paths.compileDirectoryPath});return{appRoot:t.project.appRoot,compileResult:t,compiledArtifacts:a,scheduleRegistrations:r,schedules:n,workflowBuildDir:i}}async function _i(e){return await vi(await p({compiledArtifactsSource:e.compiledArtifactsSource}))}async function vi(e){let t={},n=[{agentRoot:e.agentRoot,manifest:e,nodeId:i},...[...e.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>({agentRoot:e.agent.agentRoot,manifest:e.agent,nodeId:e.nodeId}))];for(let e of n)t[e.nodeId]={modules:await yi({agentRoot:e.agentRoot,manifest:e.manifest})};return{nodes:t}}async function yi(e){let t=le(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)),n={};for(let r of t){let t=y(e.agentRoot,r.logicalPath);n[r.sourceId]=await me(t)}return n}async function bi(e){let t=await xi(e.backendName,e.compiledArtifactsSource),n=await Si({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId,sourceId:e.sourceId}),i=Y(`${r().version}:2:${n}`).slice(0,20);return Ci(`ash-sbx-tpl-${e.backendName}-${t}-${i}`)}async function xi(e,t){if(e===`vercel`){let e=process.env.VERCEL_DEPLOYMENT_ID?.trim();if(e!==void 0&&e.length>0)return Y(e).slice(0,16)}let n=l(t);return n===void 0?Y(se(t)).slice(0,16):Y(await E(n)).slice(0,16)}async function Si(e){return Y(`${(await re({compiledArtifactsSource:e.compiledArtifactsSource}))?.discovery.sourceGraphHash??se(e.compiledArtifactsSource)}:${e.nodeId}:${e.sourceId}`)}function Y(e){return Ee(`sha256`).update(e).digest(`hex`)}function Ci(e){return e.replaceAll(/[^a-zA-Z0-9._-]+/g,`-`).slice(0,120)}async function wi(e){let t=[];return await Ti({files:t,logicalDirectoryPath:`.`,sourceDirectoryPath:e}),t.sort((e,t)=>e.path.localeCompare(t.path)),t}async function Ti(e){let t=await T(e.sourceDirectoryPath,{withFileTypes:!0});for(let n of t){if(!n.isDirectory()&&!n.isFile())continue;let t=y(e.sourceDirectoryPath,n.name),r=Ce.join(e.logicalDirectoryPath,n.name);if(n.isDirectory()){await Ti({files:e.files,logicalDirectoryPath:r,sourceDirectoryPath:t});continue}e.files.push({content:await w(t),path:Ce.join(f,r)})}}async function Ei(e){let t=await Oi(e);if(t.length===0)return;e.log?.(`Ash: initializing ${t.length} sandbox ${Mi(t.length,`template`)}...`);let n=e.dispatch??(async({backend:e,input:t})=>{await e.prewarm(t)});await Promise.all(t.map(async({backend:t,label:r,input:i})=>{e.log?.(`Ash: initializing sandbox template "${r}"...`);try{await n({backend:t,input:i})}catch(n){throw e.log?.(`Ash: failed to initialize sandbox template "${r}" on backend "${t.name}": ${ge(n)}`),n}e.log?.(`Ash: sandbox template "${r}" initialized.`)})),e.log?.(`Ash: initialized ${t.length} sandbox ${Mi(t.length,`template`)}.`)}async function Di(e){let t=hi(e.appRoot),n=await(e.loadAgentGraph??Ai)({compiledArtifactsSource:t});await Ei({compiledArtifactsSource:t,dispatch:e.dispatch,graph:n,log:e.log})}async function Oi(e){let t=ee(e.compiledArtifactsSource.appRoot).compileDirectoryPath,n={appRoot:e.compiledArtifactsSource.appRoot};return[...await Promise.all(ji(e.graph).map(async({definition:r,nodeId:i,workspaceResourceRoot:a})=>{let o=await bi({backendName:r.backend.name,compiledArtifactsSource:e.compiledArtifactsSource,nodeId:i,sourceId:r.sourceId});return{backend:r.backend,label:Ni(i),input:{bootstrap:r.bootstrap,seedFiles:await ki({compileDirectoryPath:t,workspaceResourceRoot:a}),runtimeContext:n,templateKey:o}}}))].sort((e,t)=>e.label.localeCompare(t.label))}async function ki(e){return e.workspaceResourceRoot.rootEntries.length===0?[]:(await wi(`${e.compileDirectoryPath}/${e.workspaceResourceRoot.logicalPath}`)).map(e=>({content:e.content,path:e.path}))}async function Ai(e){let[t,n]=await Promise.all([p({compiledArtifactsSource:e.compiledArtifactsSource}),_i({compiledArtifactsSource:e.compiledArtifactsSource})]);return await d({manifest:t,moduleMap:n})}function ji(e){return[...e.nodesByNodeId.entries()].flatMap(([e,t])=>{let n=t.sandboxRegistry.sandbox;return n===null?[]:[{...n,nodeId:e}]})}function Mi(e,t){return e===1?t:`${t}s`}function Ni(e){return e===`__root__`?`root`:e}function Pi(){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 Fi(e){return Pi()?(await Di(e),!0):!1}function Ii(e){return e.replace(/[\\/]+$/,``)}function Li(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ri(e,t){return typeof t!=`string`||t.trim().length===0?null:x(e,t)}function zi(e){if(!Li(e.config)||!Li(e.config.experimentalServices))return;let t=!1,n;for(let r of Object.values(e.config.experimentalServices)){if(!Li(r))continue;if(r.framework===`nextjs`){t=!0;continue}if(r.framework!==`ash`)continue;let i=Ri(e.configRoot,r.entrypoint),a=typeof r.routePrefix==`string`?r.routePrefix.trim():``;i===e.appRoot&&a.length>0&&a!==`/`&&(n=a)}return t?n:void 0}async function Bi(e){let t=e;for(;;){try{let n=y(t,`vercel.json`),r=JSON.parse(await w(n,`utf8`)),i=zi({appRoot:e,configRoot:t,config:r});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let n=v(t);if(n===t)return;t=n}}async function Vi(e){try{return JSON.parse(await w(y(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function Hi(e){let t=new kn({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:o(),watch:!1}),n=await Vi(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function X(e){let t=Ii(e.options.output.dir);return await Re(t),await Fe(e),await Me(e),await Ie(e),await je(e),await ze(t),t}async function Ui(e,t){let n=await J(e,!1,{outputDir:te(e.appRoot,t),surface:t});try{return await X(n)}finally{await n.close()}}async function Wi(e){let t=await gi(e);if(!process.env.VERCEL){let e=await J(t,!1);try{let n=await X(e);return await Qr({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await J(t,!1,{surface:`app`});try{let e=await X(n);await Fi({appRoot:t.appRoot,log(e){console.log(e)}});let r=await Ui(t,`flow`);await Hi({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir});let i=await Bi(t.appRoot);return i!==void 0&&await vn(e,{servicePrefix:i}),await Qr({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,Gi=new Set([`[::]`,`::`,`0.0.0.0`]);function Ki(e){let t=new URL(e);return Gi.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function qi(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function Ji(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 Yi(){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 Xi(e){let t=Ji(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 Zi(e){let t=process.env[Q],n=process.env[$],r=new URL(Ki(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 Qi(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function $i(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=Qi(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function ea(e){let t=Xi({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(()=>{}),!qi(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 ta(e,t={}){let n=t.schedules===!0;ye(e);let r=await gi(e);await Di({appRoot:r.appRoot,log:e=>console.log(e)});let i=await J(r,!0,{schedules:n}),a=Ne(i);$i(a);let o=t.host??i.options.devServer.hostname,s=t.port??Yi(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await ea({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=Zi(e.url),await Fe(i),await je(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-DqoJsDup.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:Ki(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var na=e({buildApplication:()=>Wi,startDevelopmentServer:()=>ta});export{yr as a,B as c,gi as i,ta as n,qn as o,Di as r,Yn as s,na as t};