experimental-ash 0.16.0 → 0.16.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 (30) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/docs/public/agent-ts.md +6 -23
  3. package/dist/docs/public/context-control.md +2 -2
  4. package/dist/docs/public/evals.md +2 -15
  5. package/dist/docs/public/project-layout.md +1 -1
  6. package/dist/docs/public/skills.md +3 -4
  7. package/dist/docs/public/subagents.md +1 -1
  8. package/dist/docs/public/tools.md +0 -1
  9. package/dist/docs/public/typescript-api.md +4 -3
  10. package/dist/src/channel/send.js +13 -3
  11. package/dist/src/chunks/{dev-authored-source-watcher-BmtpQdvr.js → dev-authored-source-watcher-D2Lz_4ud.js} +1 -1
  12. package/dist/src/chunks/{host-q4jM7D0h.js → host-B2D2qXsD.js} +2 -2
  13. package/dist/src/chunks/{paths-ByH5Mnvt.js → paths-BYA-Yank.js} +1 -1
  14. package/dist/src/chunks/{prewarm-BsHOevz0.js → prewarm-C4x0CPRP.js} +1 -1
  15. package/dist/src/cli/commands/info.js +1 -1
  16. package/dist/src/cli/run.js +1 -1
  17. package/dist/src/evals/cli/eval.js +1 -1
  18. package/dist/src/execution/continuous-entry.js +2 -2
  19. package/dist/src/execution/continuous-runtime.d.ts +1 -1
  20. package/dist/src/execution/continuous-runtime.js +3 -3
  21. package/dist/src/execution/runtime-errors.d.ts +13 -0
  22. package/dist/src/execution/runtime-errors.js +19 -0
  23. package/dist/src/execution/workflow-runtime.js +15 -3
  24. package/dist/src/internal/application/package.js +1 -1
  25. package/dist/src/public/channels/slack/interactions.d.ts +0 -5
  26. package/dist/src/public/channels/slack/interactions.js +20 -11
  27. package/dist/src/public/channels/slack/slackChannel.d.ts +18 -0
  28. package/package.json +1 -1
  29. package/dist/src/execution/continuous-runtime-errors.d.ts +0 -28
  30. package/dist/src/execution/continuous-runtime-errors.js +0 -34
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # experimental-ash
2
2
 
3
+ ## 0.16.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 2aac66f: Stop logging `[ash:channel.send] deliver failed, starting new session` on the expected resume-or-start path. The runtime now throws a typed `RuntimeNoActiveSessionError` (replacing the previous `ContinuousRuntimeNoActiveSessionError`) from both the continuous and workflow runtimes, and the channel `send()` helper treats this case as silent. Genuine delivery failures still warn so they remain visible to operators.
8
+
9
+ ## 0.16.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 8cf749c: Expose the clicking actor as a `user` field on `SlackInteractionAction` so `onInteraction` handlers can attribute resolutions without re-parsing the raw payload.
14
+
3
15
  ## 0.16.0
4
16
 
5
17
  ### Minor Changes
@@ -33,11 +33,13 @@ Use `agent.ts` for:
33
33
 
34
34
  - model selection
35
35
  - metadata you want preserved in runtime traces
36
- - human-in-the-loop policy
37
36
  - hosted-build packaging controls
38
37
  - compaction settings
39
38
  - provider-specific model options
40
39
 
40
+ Per-tool approval (formerly "human-in-the-loop policy") lives on each tool via `needsApproval`,
41
+ not in `agent.ts`. See [Human In The Loop](./human-in-the-loop.md).
42
+
41
43
  For OpenTelemetry configuration, use `instrumentation.ts` instead. See
42
44
  [`instrumentation.ts`](./instrumentation.md).
43
45
 
@@ -130,29 +132,10 @@ server output instead of being bundled.
130
132
  The shared per-run workspace is configured on the sandbox, not on `agent.ts`. See
131
133
  [Workspace](./workspace.md) and [Sandboxes](./sandbox.md).
132
134
 
133
- ## `humanInTheLoop`
134
-
135
- `humanInTheLoop` controls whether Ash should pause for approval before executing model-visible
136
- tools.
137
-
138
- ```ts
139
- export default defineAgent({
140
- humanInTheLoop: {
141
- mode: "require-approval",
142
- },
143
- });
144
- ```
145
-
146
- Supported fields:
147
-
148
- - `mode: "require-approval" | "auto-allow"`
149
- - `allow?: readonly string[]`
150
- - `ask?: readonly string[]`
151
-
152
- Use `require-approval` when the default should be "ask first". Use `auto-allow` when the default
153
- should be "run immediately" and only a few named tools should still require approval.
135
+ ## Human In The Loop
154
136
 
155
- See [Human In The Loop](./human-in-the-loop.md) for the runtime flow, `input.requested`
137
+ Approval policy lives on individual tools via `needsApproval` in `defineTool({...})`, not on
138
+ `agent.ts`. See [Human In The Loop](./human-in-the-loop.md) for the runtime flow, `input.requested`
156
139
  events, and HTTP response payloads.
157
140
 
158
141
  ## Telemetry
@@ -66,7 +66,6 @@ Use the weather tool before answering forecast or temperature questions.
66
66
 
67
67
  ```md
68
68
  ---
69
- name: research
70
69
  description: Research unfamiliar topics before answering with confidence.
71
70
  ---
72
71
 
@@ -84,7 +83,8 @@ prompt.
84
83
  ### Skill Rules That Matter
85
84
 
86
85
  - packaged `SKILL.md` files must include YAML frontmatter
87
- - `name` and `description` are required in packaged skill frontmatter
86
+ - `description` is required in packaged skill frontmatter; identity is derived from the directory
87
+ name
88
88
  - flat markdown skills may omit frontmatter
89
89
  - tools stay visible whether or not a skill is activated
90
90
 
@@ -39,9 +39,7 @@ import { defineEvalSuite } from "experimental-ash/evals";
39
39
  import { Run } from "experimental-ash/evals/scores";
40
40
 
41
41
  export default defineEvalSuite({
42
- id: "weather-smoke",
43
42
  model: "openai/gpt-5.4-mini",
44
- name: "Weather Smoke",
45
43
  description: "Basic message and tool-usage coverage for the weather agent.",
46
44
  cases: [
47
45
  {
@@ -55,13 +53,12 @@ export default defineEvalSuite({
55
53
  ```
56
54
 
57
55
  `defineEvalSuite(...)` validates the suite shape and returns a normalized suite object that the CLI
58
- can discover and run.
56
+ can discover and run. Suite identity is derived from the `.eval.ts` file path — authored
57
+ definitions do not carry an `id` or `name`.
59
58
 
60
59
  Every suite must provide:
61
60
 
62
- - `id`
63
61
  - `model`
64
- - `name`
65
62
  - `scores`
66
63
  - either `cases` or `load`
67
64
 
@@ -88,9 +85,7 @@ You can provide cases directly:
88
85
 
89
86
  ```ts
90
87
  export default defineEvalSuite({
91
- id: "smoke",
92
88
  model: "openai/gpt-5.4-mini",
93
- name: "Smoke",
94
89
  cases: [
95
90
  {
96
91
  id: "hello",
@@ -110,9 +105,7 @@ import { loadYaml } from "experimental-ash/evals/loaders";
110
105
  import { Text } from "experimental-ash/evals/scores";
111
106
 
112
107
  export default defineEvalSuite({
113
- id: "marketing-sql",
114
108
  model: "openai/gpt-5.4-mini",
115
- name: "Marketing SQL",
116
109
  async load() {
117
110
  const doc = await loadYaml("evals/data/cases.yaml");
118
111
  return (doc.evals as readonly { task: string; prompt: string; sql: string }[]).map((row) => ({
@@ -131,9 +124,7 @@ message.
131
124
 
132
125
  ```ts
133
126
  defineEvalSuite({
134
- id: "weather-task",
135
127
  model: "openai/gpt-5.4-mini",
136
- name: "Weather Task",
137
128
  task: {
138
129
  prompt: (testCase) => `Answer the user: ${String(testCase.input)}`,
139
130
  parseOutput: (result) => result.finalMessage,
@@ -149,9 +140,7 @@ Suite thresholds let you relax a scorer from the default exact-match requirement
149
140
 
150
141
  ```ts
151
142
  defineEvalSuite({
152
- id: "weather",
153
143
  model: "openai/gpt-5.4-mini",
154
- name: "Weather",
155
144
  cases: [{ id: "hello", input: "Hello", expected: "Hello" }],
156
145
  scores: [Run.didNotFail(), Text.includes()],
157
146
  thresholds: {
@@ -180,8 +169,6 @@ import { defineEvalSuite } from "experimental-ash/evals";
180
169
  import { Autoevals, Run } from "experimental-ash/evals/scores";
181
170
 
182
171
  export default defineEvalSuite({
183
- id: "support-quality",
184
- name: "Support Quality",
185
172
  model: "openai/gpt-5.4-mini",
186
173
  cases: [{ id: "refund", input: "How do I get a refund?", expected: "refund policy" }],
187
174
  scores: [Run.didNotFail(), Autoevals.factuality()],
@@ -34,7 +34,7 @@ my-agent/
34
34
  | Path | Purpose | Notes |
35
35
  | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
36
  | `instructions.md` or `instructions.ts` | Base instructions prompt | Exactly one instructions prompt is expected. Module-backed sources execute once at build time; the resulting markdown is baked into the compiled manifest. The legacy `system.{md,ts,...}` slot is still discovered with a deprecation warning. |
37
- | `agent.ts` | Runtime config | Model, metadata, workspace, build, compaction |
37
+ | `agent.ts` | Runtime config | Model, metadata, build, compaction, modelOptions |
38
38
  | `instrumentation.ts` | Telemetry config | OTel exporter setup and AI SDK span settings; auto-discovered and run before agent code |
39
39
  | `channels/` | HTTP or messaging entrypoints | Root-only today |
40
40
  | `connections/` | External service connections (MCP) | Each file defines one connection; name derived from filename |
@@ -45,7 +45,7 @@ The smallest skill is just a markdown file.
45
45
  Use the weather tool before answering forecast or temperature questions.
46
46
  ```
47
47
 
48
- For flat skills, Ash derives the skill id and name from the file path.
48
+ For flat skills, Ash derives the skill id from the file path.
49
49
 
50
50
  You can also add frontmatter when you want to control the description explicitly:
51
51
 
@@ -63,7 +63,6 @@ Use a packaged skill when the procedure needs sibling files.
63
63
 
64
64
  ```md
65
65
  ---
66
- name: research
67
66
  description: Research unfamiliar topics before answering with confidence.
68
67
  ---
69
68
 
@@ -99,7 +98,8 @@ export default defineTool({
99
98
 
100
99
  - flat skills can be simple markdown files under `skills/*.md`
101
100
  - packaged skills live under `skills/<name>/SKILL.md`
102
- - packaged `SKILL.md` files must include `name` and `description` frontmatter
101
+ - packaged `SKILL.md` files must include `description` frontmatter; skill identity is derived from
102
+ the directory name
103
103
  - flat skills may omit frontmatter
104
104
 
105
105
  ## Write Good Descriptions
@@ -145,7 +145,6 @@ If markdown is not enough, you can author a skill in TypeScript with `defineSkil
145
145
  import { defineSkill } from "experimental-ash/skills";
146
146
 
147
147
  export default defineSkill({
148
- name: "research",
149
148
  description: "Research unfamiliar topics before answering with confidence.",
150
149
  markdown:
151
150
  "When the task is novel or ambiguous, gather evidence first, then answer with the key facts and the remaining uncertainty.",
@@ -106,7 +106,7 @@ Child `session.started.data.invocation` includes the parent call/session/turn li
106
106
 
107
107
  Local subagents may have their own:
108
108
 
109
- - `system`
109
+ - `instructions.md` or `instructions.ts`
110
110
  - `skills/`
111
111
  - `lib/`
112
112
  - `tools/`
@@ -263,7 +263,6 @@ unbounded text, cap it in the executor before returning:
263
263
 
264
264
  ```ts
265
265
  import { defineTool } from "experimental-ash/tools";
266
- import { truncateHead } from "experimental-ash/sandbox/truncate-output";
267
266
  import { z } from "zod";
268
267
 
269
268
  export default defineTool({
@@ -20,8 +20,9 @@ Source of truth:
20
20
  Use these to author the filesystem-backed surface. Each concern has its own subpath:
21
21
  `experimental-ash/tools` for tools, `experimental-ash/hooks` for hooks,
22
22
  `experimental-ash/sandbox` for the sandbox, `experimental-ash/skills` for skills,
23
- `experimental-ash/context` for context helpers, and the main `experimental-ash`
24
- barrel for agent config, schedules, and systems.
23
+ `experimental-ash/schedules` for schedules, `experimental-ash/instructions` for the instructions
24
+ prompt, `experimental-ash/context` for context helpers, and the main `experimental-ash` barrel
25
+ for `defineAgent`.
25
26
 
26
27
  - `defineAgent(...)` - additive runtime config for `agent.ts`. Subagents reuse the same helper at
27
28
  `subagents/<id>/agent.ts`; the only difference is that subagents must declare a `description` so
@@ -41,7 +42,7 @@ barrel for agent config, schedules, and systems.
41
42
 
42
43
  Framework defaults reachable for spread/wrap composition:
43
44
 
44
- - `bash`, `readFile`, `writeFile`, `webFetch`, `todo`, `loadSkill` (`experimental-ash/tools/defaults`)
45
+ - `bash`, `glob`, `grep`, `readFile`, `writeFile`, `webFetch`, `webSearch`, `todo`, `loadSkill` (`experimental-ash/tools/defaults`)
45
46
 
46
47
  Most apps use `defineAgent`, `defineTool`, and `defineSandbox` the most.
47
48
 
@@ -1,6 +1,8 @@
1
1
  import { createSession } from "#channel/session.js";
2
+ import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
2
3
  import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";
3
- import { createLogger } from "#internal/logging.js";
4
+ import { createErrorId, createLogger } from "#internal/logging.js";
5
+ import { toErrorMessage } from "#shared/errors.js";
4
6
  const log = createLogger("channel.send");
5
7
  export function createSendFn(runtime, adapter, channelName) {
6
8
  return async (input, options) => {
@@ -18,8 +20,16 @@ export function createSendFn(runtime, adapter, channelName) {
18
20
  });
19
21
  return createSession(sessionId, rawToken, runtime);
20
22
  }
21
- catch {
22
- log.info("deliver failed, starting new session", { continuationToken });
23
+ catch (error) {
24
+ // No-active-session is the expected resume-or-start signal; only
25
+ // warn when the runtime surfaces a different delivery failure.
26
+ if (!isRuntimeNoActiveSessionError(error)) {
27
+ log.warn("deliver failed, falling back to starting a new session", {
28
+ continuationToken,
29
+ errorId: createErrorId(),
30
+ message: toErrorMessage(error),
31
+ });
32
+ }
23
33
  }
24
34
  if (inputResponses && inputResponses.length > 0) {
25
35
  throw new Error("Cannot deliver inputResponses — the target session was not found via continuation token.");
@@ -1,4 +1,4 @@
1
- import{o as e}from"./paths-ByH5Mnvt.js";import{t}from"./errors-DsO9xmQL.js";import{i as n}from"./package-DmsQgn4v.js";import{a as r,c as i,i as a,n as o,s,t as c}from"./prewarm-BsHOevz0.js";import{createRequire as l}from"node:module";import*as u from"node:path";import{dirname as d,isAbsolute as f,join as p,relative as m,resolve as h,sep as g}from"node:path";import{lstat as _,open as v,readFile as y,readdir as b,realpath as x,stat as S}from"node:fs/promises";import{existsSync as C,stat as w,unwatchFile as T,watch as E,watchFile as D}from"node:fs";import{EventEmitter as O}from"node:events";import{Readable as k}from"node:stream";import{type as ee}from"node:os";const A={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},j={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:A.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(j);const te=`READDIRP_RECURSIVE_ERROR`,ne=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,te]),re=[A.DIR_TYPE,A.EVERYTHING_TYPE,A.FILE_DIR_TYPE,A.FILE_TYPE],ie=new Set([A.DIR_TYPE,A.EVERYTHING_TYPE,A.FILE_DIR_TYPE]),ae=new Set([A.EVERYTHING_TYPE,A.FILE_DIR_TYPE,A.FILE_TYPE]),oe=e=>ne.has(e.code),se=process.platform===`win32`,M=e=>!0,N=e=>{if(e===void 0)return M;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return M};var ce=class extends k{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...j,...e},{root:n,type:r}=t;this._fileFilter=N(t.fileFilter),this._directoryFilter=N(t.directoryFilter);let i=t.lstat?_:S;se?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:j.depth,this._wantsDir=r?ie.has(r):!1,this._wantsFile=r?ae.has(r):!1,this._wantsEverything=r===A.EVERYTHING_TYPE,this._root=h(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await b(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=h(p(t,r));n={path:m(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){oe(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await x(t),n=await _(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===g){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=te,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function le(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=A.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!re.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${re.join(`, `)}`);return t.root=e,new ce(t)}const P=()=>{},F=process.platform,I=F===`win32`,ue=F===`darwin`,de=F===`linux`,fe=F===`freebsd`,pe=ee()===`OS400`,L={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},R=L,me={lstat:_,stat:S},z=`listeners`,B=`errHandlers`,V=`rawEmitters`,he=[z,B,V],ge=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),_e=e=>ge.has(u.extname(e).slice(1).toLowerCase()),H=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},U=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},ve=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},W=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},ye=e=>e instanceof Set?e.size===0:!e,G=new Map;function be(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&K(u.resolve(e,r),z,u.join(e,r))};try{return E(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const K=(e,t,n,r,i)=>{let a=G.get(e);a&&H(a[t],e=>{e(n,r,i)})},xe=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=G.get(t),c;if(!n.persistent)return c=be(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)U(s,z,i),U(s,B,a),U(s,V,o);else{if(c=be(e,n,K.bind(null,t,z),a,K.bind(null,t,V)),!c)return;c.on(R.ERROR,async n=>{let r=K.bind(null,t,B);if(s&&(s.watcherUnusable=!0),I&&n.code===`EPERM`)try{await(await v(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},G.set(t,s)}return()=>{W(s,z,i),W(s,B,a),W(s,V,o),ye(s.listeners)&&(s.watcher.close(),G.delete(t),he.forEach(ve(s)),s.watcher=void 0,Object.freeze(s))}},q=new Map,Se=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=q.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(T(t),o=void 0),o?(U(o,z,i),U(o,V,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:D(t,n,(n,r)=>{H(o.rawEmitters,e=>{e(R.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&H(o.listeners,t=>t(e,n))})},q.set(t,o)),()=>{W(o,z,i),W(o,V,a),ye(o.listeners)&&(q.delete(t),T(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Ce=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=u.dirname(e),i=u.basename(e);this.fsw._getWatchedDir(r).add(i);let a=u.resolve(e),o={persistent:n.persistent};t||=P;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&_e(i)?n.binaryInterval:n.interval,s=Se(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=xe(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=u.dirname(e),i=u.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await S(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(R.CHANGE,e,n),(ue||de||fe)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(R.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(R.ADD,e,0))return;this.fsw._emit(R.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await x(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(R.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(R.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=u.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(d)return d.on(`data`,async o=>{if(this.fsw.closed){d=void 0;return}let s=o.path,f=u.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,f,s))){if(this.fsw.closed){d=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),f=u.join(i,u.relative(i,f)),this._addToNodeFs(f,t,n,a+1))}}).on(R.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!d)return s();d.once(`end`,()=>{if(this.fsw.closed){d=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),d=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(u.dirname(e)),c=s.has(u.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(R.ADD_DIR,e,t),s.add(u.basename(e)),this.fsw._getWatchedDir(e);let l,d=this.fsw.options.depth;if((d==null||r<=d)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await me[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=u.resolve(e),l=s?await x(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await x(e):e;if(this.fsw.closed)return;let a=u.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(R.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(u.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};const we=/\\/g,Te=/\/\//g,Ee=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,De=/^\.[/\\]/;function J(e){return Array.isArray(e)?e:[e]}const Y=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Oe(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=u.relative(e.path,t);return n?!n.startsWith(`..`)&&!u.isAbsolute(n):!1}return!1}:()=>!1}function ke(e){if(typeof e!=`string`)throw Error(`string expected`);e=u.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(Te,`/`),t&&(e=`/`+e),e}function Ae(e,t,n){let r=ke(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function je(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=J(e).map(e=>Oe(e));return t==null?(e,t)=>Ae(n,e,t):Ae(n,t)}const Me=e=>{let t=J(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Pe)},Ne=e=>{let t=e.replace(we,`/`),n=!1;return t.startsWith(`//`)&&(n=!0),t=t.replace(Te,`/`),n&&(t=`/`+t),t},Pe=e=>Ne(u.normalize(Ne(e))),Fe=(e=``)=>t=>typeof t==`string`?Pe(u.isAbsolute(t)?t:u.join(e,t)):t,Ie=(e,t)=>u.isAbsolute(e)?e:u.join(t,e),Le=Object.freeze(new Set);var Re=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await b(n)}catch{this._removeWatcher&&this._removeWatcher(u.dirname(n),u.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=P,this.items=Le,Object.freeze(this)}},ze=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(De,``),this.watchPath=r,this.fullWatchPath=u.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return u.join(this.watchPath,u.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Be=class extends O{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?J(e.ignored):J([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};pe&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=P,this._readyEmitted=!0,process.nextTick(()=>this.emit(L.READY)))},this._emitRaw=(...e)=>this.emit(L.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Ce(this),Object.freeze(r)}_addIgnoredPath(e){if(Y(e)){for(let t of this._ignoredPaths)if(Y(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Y(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Me(e);return r&&(i=i.map(e=>Ie(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(u.dirname(e),u.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Me(e),{cwd:n}=this.options;return t.forEach(e=>{!u.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=u.join(n,e)),e=u.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?u.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==L.ERROR&&this.emit(L.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;I&&(t=u.normalize(t)),r.cwd&&(t=u.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===L.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(L.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===L.ADD&&this._pendingUnlinks.has(t)&&(e=L.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===L.ADD||e===L.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=L.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===L.CHANGE&&!this._throttle(L.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===L.ADD||e===L.ADD_DIR||e===L.CHANGE)){let e=r.cwd?u.join(r.cwd,t):t,n;try{n=await S(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(L.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!u.isAbsolute(e)&&(s=u.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function d(n){w(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(d,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(d,a))}_isIgnored(e,t){if(this.options.atomic&&Ee.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Fe(e)),n=[...[...this._ignoredPaths].map(Fe(e)),...t];this._userIgnored=je(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ze(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=u.resolve(e);return this._watched.has(t)||this._watched.set(t,new Re(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=u.join(e,t),i=u.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=u.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===L.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?L.UNLINK_DIR:L.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=u.dirname(e);this._getWatchedDir(t).remove(u.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=le(e,{type:L.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Ve(e,t={}){let n=new Be(t);return n.add(e),n}function He(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function f(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function p(e){r=e,i=``,a=0,o=16,d=0}function m(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Q(e.charCodeAt(r)))for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r);let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Q(e.charCodeAt(r))){for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;n=r}else d=3;return e.substring(t,n)}function h(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
1
+ import{o as e}from"./paths-BYA-Yank.js";import{t}from"./errors-DsO9xmQL.js";import{i as n}from"./package-DmsQgn4v.js";import{a as r,c as i,i as a,n as o,s,t as c}from"./prewarm-C4x0CPRP.js";import{createRequire as l}from"node:module";import*as u from"node:path";import{dirname as d,isAbsolute as f,join as p,relative as m,resolve as h,sep as g}from"node:path";import{lstat as _,open as v,readFile as y,readdir as b,realpath as x,stat as S}from"node:fs/promises";import{existsSync as C,stat as w,unwatchFile as T,watch as E,watchFile as D}from"node:fs";import{EventEmitter as O}from"node:events";import{Readable as k}from"node:stream";import{type as ee}from"node:os";const A={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},j={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:A.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(j);const te=`READDIRP_RECURSIVE_ERROR`,ne=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,te]),re=[A.DIR_TYPE,A.EVERYTHING_TYPE,A.FILE_DIR_TYPE,A.FILE_TYPE],ie=new Set([A.DIR_TYPE,A.EVERYTHING_TYPE,A.FILE_DIR_TYPE]),ae=new Set([A.EVERYTHING_TYPE,A.FILE_DIR_TYPE,A.FILE_TYPE]),oe=e=>ne.has(e.code),se=process.platform===`win32`,M=e=>!0,N=e=>{if(e===void 0)return M;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return M};var ce=class extends k{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...j,...e},{root:n,type:r}=t;this._fileFilter=N(t.fileFilter),this._directoryFilter=N(t.directoryFilter);let i=t.lstat?_:S;se?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:j.depth,this._wantsDir=r?ie.has(r):!1,this._wantsFile=r?ae.has(r):!1,this._wantsEverything=r===A.EVERYTHING_TYPE,this._root=h(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await b(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=h(p(t,r));n={path:m(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){oe(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await x(t),n=await _(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===g){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=te,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function le(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=A.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!re.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${re.join(`, `)}`);return t.root=e,new ce(t)}const P=()=>{},F=process.platform,I=F===`win32`,ue=F===`darwin`,de=F===`linux`,fe=F===`freebsd`,pe=ee()===`OS400`,L={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},R=L,me={lstat:_,stat:S},z=`listeners`,B=`errHandlers`,V=`rawEmitters`,he=[z,B,V],ge=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),_e=e=>ge.has(u.extname(e).slice(1).toLowerCase()),H=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},U=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},ve=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},W=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},ye=e=>e instanceof Set?e.size===0:!e,G=new Map;function be(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&K(u.resolve(e,r),z,u.join(e,r))};try{return E(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const K=(e,t,n,r,i)=>{let a=G.get(e);a&&H(a[t],e=>{e(n,r,i)})},xe=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=G.get(t),c;if(!n.persistent)return c=be(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)U(s,z,i),U(s,B,a),U(s,V,o);else{if(c=be(e,n,K.bind(null,t,z),a,K.bind(null,t,V)),!c)return;c.on(R.ERROR,async n=>{let r=K.bind(null,t,B);if(s&&(s.watcherUnusable=!0),I&&n.code===`EPERM`)try{await(await v(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},G.set(t,s)}return()=>{W(s,z,i),W(s,B,a),W(s,V,o),ye(s.listeners)&&(s.watcher.close(),G.delete(t),he.forEach(ve(s)),s.watcher=void 0,Object.freeze(s))}},q=new Map,Se=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=q.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(T(t),o=void 0),o?(U(o,z,i),U(o,V,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:D(t,n,(n,r)=>{H(o.rawEmitters,e=>{e(R.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&H(o.listeners,t=>t(e,n))})},q.set(t,o)),()=>{W(o,z,i),W(o,V,a),ye(o.listeners)&&(q.delete(t),T(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Ce=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=u.dirname(e),i=u.basename(e);this.fsw._getWatchedDir(r).add(i);let a=u.resolve(e),o={persistent:n.persistent};t||=P;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&_e(i)?n.binaryInterval:n.interval,s=Se(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=xe(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=u.dirname(e),i=u.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await S(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(R.CHANGE,e,n),(ue||de||fe)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(R.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(R.ADD,e,0))return;this.fsw._emit(R.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await x(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(R.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(R.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=u.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(d)return d.on(`data`,async o=>{if(this.fsw.closed){d=void 0;return}let s=o.path,f=u.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,f,s))){if(this.fsw.closed){d=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),f=u.join(i,u.relative(i,f)),this._addToNodeFs(f,t,n,a+1))}}).on(R.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!d)return s();d.once(`end`,()=>{if(this.fsw.closed){d=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),d=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(u.dirname(e)),c=s.has(u.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(R.ADD_DIR,e,t),s.add(u.basename(e)),this.fsw._getWatchedDir(e);let l,d=this.fsw.options.depth;if((d==null||r<=d)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await me[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=u.resolve(e),l=s?await x(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await x(e):e;if(this.fsw.closed)return;let a=u.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(R.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(u.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};const we=/\\/g,Te=/\/\//g,Ee=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,De=/^\.[/\\]/;function J(e){return Array.isArray(e)?e:[e]}const Y=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Oe(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=u.relative(e.path,t);return n?!n.startsWith(`..`)&&!u.isAbsolute(n):!1}return!1}:()=>!1}function ke(e){if(typeof e!=`string`)throw Error(`string expected`);e=u.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(Te,`/`),t&&(e=`/`+e),e}function Ae(e,t,n){let r=ke(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function je(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=J(e).map(e=>Oe(e));return t==null?(e,t)=>Ae(n,e,t):Ae(n,t)}const Me=e=>{let t=J(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Pe)},Ne=e=>{let t=e.replace(we,`/`),n=!1;return t.startsWith(`//`)&&(n=!0),t=t.replace(Te,`/`),n&&(t=`/`+t),t},Pe=e=>Ne(u.normalize(Ne(e))),Fe=(e=``)=>t=>typeof t==`string`?Pe(u.isAbsolute(t)?t:u.join(e,t)):t,Ie=(e,t)=>u.isAbsolute(e)?e:u.join(t,e),Le=Object.freeze(new Set);var Re=class{path;_removeWatcher;items;constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await b(n)}catch{this._removeWatcher&&this._removeWatcher(u.dirname(n),u.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=P,this.items=Le,Object.freeze(this)}},ze=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(De,``),this.watchPath=r,this.fullWatchPath=u.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return u.join(this.watchPath,u.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Be=class extends O{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?J(e.ignored):J([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};pe&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=P,this._readyEmitted=!0,process.nextTick(()=>this.emit(L.READY)))},this._emitRaw=(...e)=>this.emit(L.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Ce(this),Object.freeze(r)}_addIgnoredPath(e){if(Y(e)){for(let t of this._ignoredPaths)if(Y(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Y(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Me(e);return r&&(i=i.map(e=>Ie(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(u.dirname(e),u.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Me(e),{cwd:n}=this.options;return t.forEach(e=>{!u.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=u.join(n,e)),e=u.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?u.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==L.ERROR&&this.emit(L.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;I&&(t=u.normalize(t)),r.cwd&&(t=u.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===L.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(L.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===L.ADD&&this._pendingUnlinks.has(t)&&(e=L.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===L.ADD||e===L.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=L.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===L.CHANGE&&!this._throttle(L.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===L.ADD||e===L.ADD_DIR||e===L.CHANGE)){let e=r.cwd?u.join(r.cwd,t):t,n;try{n=await S(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(L.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!u.isAbsolute(e)&&(s=u.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function d(n){w(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(d,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(d,a))}_isIgnored(e,t){if(this.options.atomic&&Ee.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Fe(e)),n=[...[...this._ignoredPaths].map(Fe(e)),...t];this._userIgnored=je(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new ze(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=u.resolve(e);return this._watched.has(t)||this._watched.set(t,new Re(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=u.join(e,t),i=u.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=u.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===L.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?L.UNLINK_DIR:L.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=u.dirname(e);this._getWatchedDir(t).remove(u.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=le(e,{type:L.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Ve(e,t={}){let n=new Be(t);return n.add(e),n}function He(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function f(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function p(e){r=e,i=``,a=0,o=16,d=0}function m(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46)if(r++,r<e.length&&Q(e.charCodeAt(r)))for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r);let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101))if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&Q(e.charCodeAt(r))){for(r++;r<e.length&&Q(e.charCodeAt(r));)r++;n=r}else d=3;return e.substring(t,n)}function h(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
2
2
  `;break;case 114:t+=`\r`;break;case 116:t+=` `;break;case 117:let e=f(4,!0);e>=0?t+=String.fromCharCode(e):d=4;break;default:d=5}i=r;continue}if(a>=0&&a<=31)if(Z(a)){t+=e.substring(i,r),d=2;break}else d=6;r++}return t}function g(){if(i=``,d=0,a=r,c=s,u=l,r>=n)return a=n,o=17;let t=e.charCodeAt(r);if(X(t)){do r++,i+=String.fromCharCode(t),t=e.charCodeAt(r);while(X(t));return o=15}if(Z(t))return r++,i+=String.fromCharCode(t),t===13&&e.charCodeAt(r)===10&&(r++,i+=`
3
3
  `),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=h(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!Z(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,Z(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!Q(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=m(),o=11;default:for(;r<n&&_(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function _(e){if(X(e)||Z(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function v(){let e;do e=g();while(e>=12&&e<=15);return e}return{setPosition:p,getPosition:()=>r,scan:t?v:g,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function X(e){return e===32||e===9}function Z(e){return e===10||e===13}function Q(e){return e>=48&&e<=57}var Ue;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(Ue||={}),Array(20).fill(0).map((e,t)=>` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
4
4
  `+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r
@@ -1,4 +1,4 @@
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-ByH5Mnvt.js";import{a as o,i as s,o as c,r as l}from"./authored-module-loader-Pt_g8xX2.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-BsHOevz0.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 me,rm as w,writeFile as T}from"node:fs/promises";import{randomUUID as he}from"node:crypto";import{existsSync as ge,readFileSync as _e}from"node:fs";import{fileURLToPath as ve}from"node:url";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";import{Buffer as Te}from"node:buffer";const Ee=`ash-cache.json`;async function E(e){let t=await Oe(e),n=h().version;t!==null&&t===n||await w(e,{force:!0,recursive:!0})}async function De(e){await S(e,{recursive:!0}),await T(v(e,Ee),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Oe(e){try{let t=JSON.parse(await C(v(e,Ee),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const ke=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Ae(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await je(e.filename,e.source),n=Ne(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Je(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Ye(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${Me(e.source,t,n,r)}`,workflowManifest:i};let u=Re(e.source,a),d=e.mode===`workflow`?await ze(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(`
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-BYA-Yank.js";import{a as o,i as s,o as c,r as l}from"./authored-module-loader-Pt_g8xX2.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-C4x0CPRP.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 me,rm as w,writeFile as T}from"node:fs/promises";import{randomUUID as he}from"node:crypto";import{existsSync as ge,readFileSync as _e}from"node:fs";import{fileURLToPath as ve}from"node:url";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";import{Buffer as Te}from"node:buffer";const Ee=`ash-cache.json`;async function E(e){let t=await Oe(e),n=h().version;t!==null&&t===n||await w(e,{force:!0,recursive:!0})}async function De(e){await S(e,{recursive:!0}),await T(v(e,Ee),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Oe(e){try{let t=JSON.parse(await C(v(e,Ee),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const ke=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Ae(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await je(e.filename,e.source),n=Ne(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Je(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Ye(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${Me(e.source,t,n,r)}`,workflowManifest:i};let u=Re(e.source,a),d=e.mode===`workflow`?await ze(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
2
  `)}\n`:``}`,workflowManifest:i}}async function je(e,t){let{parseAst:n}=await c();return n(t,{astType:`ts`,lang:qe(e),range:!0,sourceType:`module`},e)}function Me(e,t,n,r){let i=Be(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=Ye(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
3
  `)}\n`:``}function Ne(e){let t=[];for(let n of e.body??[]){let e=Pe(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Ie(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Le(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 Pe(e){return e.type===`FunctionDeclaration`?Fe(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Fe(e.declaration,!0,e)}function Fe(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 Ie(e){return e===void 0||Array.isArray(e)?e:e.body}function Le(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 Re(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 je(e,t),r=We(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=Ue(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:Ke(t,e.end),start:e.start,text:``})}return i.length>0?Re(t,i):t}function Be(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(Ve)&&n.push(e.slice(r.start,r.end).trim());return n}function Ve(e){return He(e.init)}function He(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`?He(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function Ue(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function We(e){let t=new Set;return D(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function D(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)Ge(e)&&D(e,t);else Ge(n)&&D(n,t)}}function Ge(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function Ke(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
4
4
  `?n+2:e[n]===`
@@ -19,4 +19,4 @@ export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)
19
19
  `):null},resolveId(e){return an.test(e)?rn:null}}}function sn(e){return e===`all`||e===`app`}function cn(e){return z(e)}function z(e){return e===`all`||e===`flow`}function B(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
20
  `)}function V(e){return v(e.options.buildDir,`workflow`)}function ln(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function un(e,t){let n=v(V(e),`${t.bundleName}-handler.mjs`),r=_(n),i=ln(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=ln(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await T(n,dn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function dn(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 = __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
21
  `)}function fn(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 pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({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:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(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});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(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 un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[l(),...e]}}function _n(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 vn=`@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 yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(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 K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(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 An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(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 Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(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 Nn(e,t){let n=[t,v(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=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(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=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(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(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(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[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_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:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(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 pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(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 zn(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?Hn(t.instructions):null,schedules:t.schedules.map(Un),tools:t.tools.map(Wn),skills:t.skills.map(Gn),connections:t.connections.map(Kn),channels:t.channels.filter(Vn).map(qn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Jn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Bn(e){let t=zn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await T(n,`${JSON.stringify(t,null,2)}\n`),n}function Vn(e){return e.kind===`channel`}function Hn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Un(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Wn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Gn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Kn(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 qn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Rn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Jn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Yn(){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 Xn(e){return Yn()?(await se(e),!0):!1}function Zn(e){return e.replace(/[\\/]+$/,``)}async function Qn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function $n(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Qn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function er(e){let t=Zn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function tr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await er(n)}finally{await n.close()}}async function nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await er(e);return await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await er(n);await Xn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await tr(t,`flow`);return await $n({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,rr=new Set([`[::]`,`::`,`0.0.0.0`]);function ir(e){let t=new URL(e);return rr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function ar(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function or(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 sr(){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 cr(e){let t=or(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 lr(e){let t=process.env[Q],n=process.env[$],r=new URL(ir(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 ur(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function dr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=ur(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function fr(e){let t=cr({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(()=>{}),!ar(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 pr(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=xe(i);dr(a);let o=t.host??i.options.devServer.hostname,s=t.port??sr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await fr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=lr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-BmtpQdvr.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:ir(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var mr=e({buildHost:()=>hr,startHost:()=>gr});async function hr(e){return await nr(e)}async function gr(e,t={}){return await pr(e,t)}export{gr as n,mr as t};
22
+ `)}async function pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({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:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(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});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(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 un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[l(),...e]}}function _n(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 vn=`@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 yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(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 K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(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 An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(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 Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(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 Nn(e,t){let n=[t,v(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=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(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=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(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(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(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[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_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:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(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 pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(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 zn(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?Hn(t.instructions):null,schedules:t.schedules.map(Un),tools:t.tools.map(Wn),skills:t.skills.map(Gn),connections:t.connections.map(Kn),channels:t.channels.filter(Vn).map(qn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Jn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Bn(e){let t=zn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await T(n,`${JSON.stringify(t,null,2)}\n`),n}function Vn(e){return e.kind===`channel`}function Hn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Un(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Wn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Gn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Kn(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 qn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Rn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Jn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Yn(){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 Xn(e){return Yn()?(await se(e),!0):!1}function Zn(e){return e.replace(/[\\/]+$/,``)}async function Qn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function $n(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Qn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function er(e){let t=Zn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function tr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await er(n)}finally{await n.close()}}async function nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await er(e);return await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await er(n);await Xn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await tr(t,`flow`);return await $n({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,rr=new Set([`[::]`,`::`,`0.0.0.0`]);function ir(e){let t=new URL(e);return rr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function ar(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function or(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 sr(){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 cr(e){let t=or(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 lr(e){let t=process.env[Q],n=process.env[$],r=new URL(ir(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 ur(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function dr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=ur(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function fr(e){let t=cr({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(()=>{}),!ar(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 pr(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=xe(i);dr(a);let o=t.host??i.options.devServer.hostname,s=t.port??sr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await fr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=lr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-D2Lz_4ud.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:ir(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var mr=e({buildHost:()=>hr,startHost:()=>gr});async function hr(e){return await nr(e)}async function gr(e,t={}){return await pr(e,t)}export{gr as n,mr as t};
@@ -1,4 +1,4 @@
1
- import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js";import{c as n,d as r,f as i,l as a,m as o,n as s,p as c,s as l,t as u,u as d}from"./authored-module-loader-Pt_g8xX2.js";import{n as f,t as p}from"./guards-CjJ3lmju.js";import{t as m}from"./errors-DsO9xmQL.js";import{n as h,o as g,r as _,t as v}from"./package-DmsQgn4v.js";import{a as y,b as ee,i as te,n as ne,o as re,r as ie,s as ae,t as oe,u as se,y as ce}from"./types-MZUhN0Zy.js";import{t as le}from"./runtime-model-BWu6M_hq.js";import{z as b}from"#compiled/zod/index.js";import{basename as ue,dirname as x,join as S,posix as de,relative as fe,resolve as C,sep as pe}from"node:path";import{access as me,cp as he,mkdir as w,readFile as ge,readdir as _e,rm as ve,stat as ye,writeFile as T}from"node:fs/promises";import{createHash as be}from"node:crypto";import{pathToFileURL as xe}from"node:url";import{resumeHook as Se}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";import{SpanStatusCode as we,trace as Te}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as Ee}from"#compiled/@ai-sdk/provider/index.js";import{inspect as De}from"node:util";import{fromError as Oe}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as ke,decodeJwt as Ae,jwtVerify as je}from"#compiled/jose/index.js";import Me from"#compiled/turndown/index.js";const Ne=b.union([b.literal(`error`),b.literal(`warning`)]);b.object({code:b.string(),message:b.string(),severity:Ne,sourcePath:b.string()}).strict();const Pe=b.object({errors:b.number().finite(),warnings:b.number().finite()}).strict();function Fe(e){return e}function E(e){return Fe({...e,severity:`error`})}function Ie(e){return Fe({...e,severity:`warning`})}function Le(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Re(e){return e.some(e=>e.severity===`error`)}const ze=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],Be=[`package.json`,`vercel.json`],Ve=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],He=[`channels`,`connections`,`hooks`,`lib`,`sandbox`,`skills`,`tools`,`schedules`,`subagents`],Ue=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],We=[`hooks`,`lib`,`sandbox`,`skills`,`tools`,`subagents`],Ge=[`SKILL.md`],Ke=[`scripts`,`references`,`assets`],qe=new Set(Be);new Set(Ve),new Set(He),new Set(Ue),new Set(We),new Set(Ge),new Set(Ke);function D(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function Je(e,t){return t===`file`&&qe.has(e)}function Ye(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function Xe(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function Ze(e,t){if(t===`file`)return e===`SKILL.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function Qe(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(k(e)!==null)return`flat-skill-module`}return`unknown`}function O(e){return e.replaceAll(pe,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function k(e){for(let t of ze)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function A(e,t){return k(e)===t}function j(e){let t=O(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}var $e=e(t(),1);function et(e,t){let i=n(e,t);if(a(i,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],t),i.model===void 0)throw Error(`${t} The "model" field is required.`);let o={model:i.model};i.description!==void 0&&(o.description=r(i.description,t));let s=c(i,`metadata`,t);return s!==void 0&&(o.metadata=s),i.compaction!==void 0&&(o.compaction=it(i.compaction,t)),i.build!==void 0&&(o.build=nt(i.build,t)),i.modelOptions!==void 0&&(o.modelOptions=rt(i.modelOptions,t)),i.modelContextWindowTokens!==void 0&&(o.modelContextWindowTokens=tt(i.modelContextWindowTokens,t)),o}function tt(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function nt(e,t){let i=n(e,t);a(i,[`externalDependencies`],t);let o={};if(i.externalDependencies!==void 0){if(!Array.isArray(i.externalDependencies))throw Error(t);o.externalDependencies=Object.freeze(i.externalDependencies.map(e=>r(e,t)))}return o}function rt(e,t){let r=n(e,t);a(r,[`providerOptions`],t);let i=r.providerOptions;return i===void 0?{}:{providerOptions:d(i,t)}}function it(e,t){let r=n(e,t);a(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],t);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=tt(r.modelContextWindowTokens,t)),r.thresholdPercent!==void 0){let e=r.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(t);i.thresholdPercent=e}return i}function at(e,t){let i=n(e,t);return a(i,[`markdown`],t),{markdown:r(i.markdown,t)}}function ot(e,t){let i=n(e,t);a(i,[`description`,`license`,`markdown`,`metadata`],t);let o={description:r(i.description,t),markdown:r(i.markdown,t)},s=i.license,l=c(i,`metadata`,t);return s!==void 0&&(o.license=r(s,t)),l!==void 0&&(o.metadata=l),o}function st(e,t){let i=n(e,t);a(i,[`channel`,`cron`,`markdown`],t);let o={cron:r(i.cron,t),markdown:r(i.markdown,t)};return i.channel!==void 0&&i.channel!==null&&(o.channel=i.channel),o}function ct(e){return e}function lt(e){return e}function ut(e){return e}const dt=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function ft(e){if(!$e.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,$e.default)(e)}catch(t){throw gt(e)&&!_t(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!f(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:vt(t.content)}}function pt(e){return ut(at({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function mt(e){let t=ft(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`channel`in t.frontmatter)throw Error('Markdown-form schedules do not support the "channel" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to deliver to a channel.');return ct(st({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function ht(e,t={}){let n=ft(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=xt(n.frontmatter),a=St(i.description,`description`),o=r===void 0?Ct(i.description,`description`):a??t.description??Tt(n.markdown,r),s={...i,description:o,markdown:n.markdown};return yt(s,i),lt(ot(s,`Expected authored skill markdown to match the public Ash shape.`))}function gt(e){return e.startsWith(`---
1
+ import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js";import{c as n,d as r,f as i,l as a,m as o,n as s,p as c,s as l,t as u,u as d}from"./authored-module-loader-Pt_g8xX2.js";import{n as f,t as p}from"./guards-CjJ3lmju.js";import{t as m}from"./errors-DsO9xmQL.js";import{n as h,o as g,r as _,t as v}from"./package-DmsQgn4v.js";import{a as y,b as ee,i as te,n as ne,o as re,r as ie,s as ae,t as oe,u as se,y as ce}from"./types-MZUhN0Zy.js";import{t as le}from"./runtime-model-BWu6M_hq.js";import{z as b}from"#compiled/zod/index.js";import{basename as ue,dirname as x,join as S,posix as de,relative as fe,resolve as C,sep as pe}from"node:path";import{access as me,cp as he,mkdir as w,readFile as ge,readdir as _e,rm as ve,stat as ye,writeFile as T}from"node:fs/promises";import{createHash as be}from"node:crypto";import{pathToFileURL as xe}from"node:url";import"#compiled/@workflow/errors/index.js";import{resumeHook as Se}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";import{SpanStatusCode as we,trace as Te}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as Ee}from"#compiled/@ai-sdk/provider/index.js";import{inspect as De}from"node:util";import{fromError as Oe}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as ke,decodeJwt as Ae,jwtVerify as je}from"#compiled/jose/index.js";import Me from"#compiled/turndown/index.js";const Ne=b.union([b.literal(`error`),b.literal(`warning`)]);b.object({code:b.string(),message:b.string(),severity:Ne,sourcePath:b.string()}).strict();const Pe=b.object({errors:b.number().finite(),warnings:b.number().finite()}).strict();function Fe(e){return e}function E(e){return Fe({...e,severity:`error`})}function Ie(e){return Fe({...e,severity:`warning`})}function Le(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Re(e){return e.some(e=>e.severity===`error`)}const ze=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],Be=[`package.json`,`vercel.json`],Ve=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],He=[`channels`,`connections`,`hooks`,`lib`,`sandbox`,`skills`,`tools`,`schedules`,`subagents`],Ue=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],We=[`hooks`,`lib`,`sandbox`,`skills`,`tools`,`subagents`],Ge=[`SKILL.md`],Ke=[`scripts`,`references`,`assets`],qe=new Set(Be);new Set(Ve),new Set(He),new Set(Ue),new Set(We),new Set(Ge),new Set(Ke);function D(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function Je(e,t){return t===`file`&&qe.has(e)}function Ye(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function Xe(e,t){if(t===`file`)return A(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:A(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:A(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function Ze(e,t){if(t===`file`)return e===`SKILL.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function Qe(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(k(e)!==null)return`flat-skill-module`}return`unknown`}function O(e){return e.replaceAll(pe,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function k(e){for(let t of ze)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function A(e,t){return k(e)===t}function j(e){let t=O(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}var $e=e(t(),1);function et(e,t){let i=n(e,t);if(a(i,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],t),i.model===void 0)throw Error(`${t} The "model" field is required.`);let o={model:i.model};i.description!==void 0&&(o.description=r(i.description,t));let s=c(i,`metadata`,t);return s!==void 0&&(o.metadata=s),i.compaction!==void 0&&(o.compaction=it(i.compaction,t)),i.build!==void 0&&(o.build=nt(i.build,t)),i.modelOptions!==void 0&&(o.modelOptions=rt(i.modelOptions,t)),i.modelContextWindowTokens!==void 0&&(o.modelContextWindowTokens=tt(i.modelContextWindowTokens,t)),o}function tt(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function nt(e,t){let i=n(e,t);a(i,[`externalDependencies`],t);let o={};if(i.externalDependencies!==void 0){if(!Array.isArray(i.externalDependencies))throw Error(t);o.externalDependencies=Object.freeze(i.externalDependencies.map(e=>r(e,t)))}return o}function rt(e,t){let r=n(e,t);a(r,[`providerOptions`],t);let i=r.providerOptions;return i===void 0?{}:{providerOptions:d(i,t)}}function it(e,t){let r=n(e,t);a(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],t);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=tt(r.modelContextWindowTokens,t)),r.thresholdPercent!==void 0){let e=r.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(t);i.thresholdPercent=e}return i}function at(e,t){let i=n(e,t);return a(i,[`markdown`],t),{markdown:r(i.markdown,t)}}function ot(e,t){let i=n(e,t);a(i,[`description`,`license`,`markdown`,`metadata`],t);let o={description:r(i.description,t),markdown:r(i.markdown,t)},s=i.license,l=c(i,`metadata`,t);return s!==void 0&&(o.license=r(s,t)),l!==void 0&&(o.metadata=l),o}function st(e,t){let i=n(e,t);a(i,[`channel`,`cron`,`markdown`],t);let o={cron:r(i.cron,t),markdown:r(i.markdown,t)};return i.channel!==void 0&&i.channel!==null&&(o.channel=i.channel),o}function ct(e){return e}function lt(e){return e}function ut(e){return e}const dt=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function ft(e){if(!$e.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,$e.default)(e)}catch(t){throw gt(e)&&!_t(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!f(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:vt(t.content)}}function pt(e){return ut(at({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function mt(e){let t=ft(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`channel`in t.frontmatter)throw Error('Markdown-form schedules do not support the "channel" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to deliver to a channel.');return ct(st({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function ht(e,t={}){let n=ft(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=xt(n.frontmatter),a=St(i.description,`description`),o=r===void 0?Ct(i.description,`description`):a??t.description??Tt(n.markdown,r),s={...i,description:o,markdown:n.markdown};return yt(s,i),lt(ot(s,`Expected authored skill markdown to match the public Ash shape.`))}function gt(e){return e.startsWith(`---
2
2
  `)||e.startsWith(`---\r
3
3
  `)}function _t(e){return dt.test(e)}function vt(e){return e.replace(/^\r?\n/u,``)}function yt(e,t){let n=St(t.license,`license`);n!==void 0&&(e.license=n);let r=wt(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const bt=[`name`];function xt(e){let t={...e};for(let e of bt)delete t[e];return t}function St(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function Ct(e,t){let n=St(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function wt(e,t){if(e==null)return;if(!f(e))throw Error(`Expected "${t}" frontmatter to be an object.`);let n=Object.entries(e).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected "${t}.${e}" frontmatter to be a string.`);return[e,n]});return Object.fromEntries(n)}function Tt(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}function Et(e){let t=C(e.appRoot),n=C(e.agentRoot),r={agentId:e.agentId??Dt(t,n,e.packageName),agentRoot:n,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:Le(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:`ash-agent-discovery-manifest`,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(r.configModule=e.configModule),e.instructions!==void 0&&(r.instructions=e.instructions),r}function Dt(e,t,n){let r=O(fe(e,t));return r===``||r===`.`||r===`agent`?n??ue(e):ue(t)}function M(e){return O(e)}function N(e){let t=O(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??M(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function Ot(e){return{...N(e),connectionName:e.connectionName}}function kt(e){let t=O(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??M(t),subagentId:e.subagentId}}function At(e){let t={description:e.description,sourceKind:`skill-package`,logicalPath:O(e.logicalPath),markdown:e.markdown,name:e.name,rootPath:e.rootPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId};return e.assetsPath!==void 0&&(t.assetsPath=e.assetsPath),e.license!==void 0&&(t.license=e.license),e.metadata!==void 0&&(t.metadata={...e.metadata}),e.referencesPath!==void 0&&(t.referencesPath=e.referencesPath),e.scriptsPath!==void 0&&(t.scriptsPath=e.scriptsPath),t}async function jt(e){let t=O(e.logicalPath);return{definition:e.lower(await e.source.readTextFile(e.sourcePath),{name:j(t)}),sourceKind:`markdown`,logicalPath:t,sourceId:M(t)}}function Mt(e,t){let n={moduleFileNames:[]};for(let r of e)if(r.isFile()){if(t.markdownFileName!==void 0&&r.name===t.markdownFileName){n.markdownFileName=r.name;continue}t.moduleBaseName!==void 0&&k(r.name)===t.moduleBaseName&&n.moduleFileNames.push(r.name)}return n.moduleFileNames.sort((e,t)=>e.localeCompare(t)),n}function Nt(e,t){let n=new Map;for(let r of e){if(!r.isFile())continue;let e=t.allowMarkdown?Pt(r.name):null,i=t.allowModules?k(r.name):null,a=e??i;if(a===null)continue;let o=n.get(a);if(o===void 0&&(o={moduleFileNames:[],slotName:a},n.set(a,o)),e!==null){o.markdownFileName=r.name;continue}i!==null&&o.moduleFileNames.push(r.name)}return[...n.values()].map(e=>(e.moduleFileNames.sort((e,t)=>e.localeCompare(t)),e)).sort((e,t)=>e.slotName.localeCompare(t.slotName))}function Pt(e){return!e.endsWith(`.md`)||e.length<=3?null:e.slice(0,-3)}async function P(e){let t=S(e.rootPath,e.directoryName),n=e.rootEntries.find(t=>t.name===e.directoryName);if(n===void 0)return{diagnostics:[],sources:[]};if(!n.isDirectory())return{diagnostics:[E({code:e.invalidDirectoryCode,message:e.invalidDirectoryMessage,sourcePath:t})],sources:[]};let r=[],i=[];return await Ft({allowMarkdown:e.allowMarkdown===!0,diagnostics:r,markdownLowerer:e.allowMarkdown===!0?e.markdownLowerer:void 0,projectSource:e.source,recursive:e.recursive,relativeDirectory:e.directoryName,rootDirectoryPath:t,sources:i,subdirectoryRelative:``,unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment}),{diagnostics:r,sources:i}}async function Ft(e){let t=e.subdirectoryRelative===``?e.rootDirectoryPath:S(e.rootDirectoryPath,e.subdirectoryRelative),n=await F(e.projectSource,t);e.recursive&&await It(e,n,t),(e.unsupportedFileCode!==void 0||e.unsupportedEntryCode!==void 0)&&Lt(e,n,t),await Rt(e,n,t)}async function It(e,t,n){for(let r of t){if(!r.isDirectory())continue;let t=S(n,r.name);if(e.validateSegment!==void 0){let n=e.validateSegment(r.name,t);if(n!==null){e.diagnostics.push(n);continue}}await Ft({allowMarkdown:e.allowMarkdown,diagnostics:e.diagnostics,markdownLowerer:e.markdownLowerer,projectSource:e.projectSource,recursive:e.recursive,relativeDirectory:e.relativeDirectory,rootDirectoryPath:e.rootDirectoryPath,sources:e.sources,subdirectoryRelative:e.subdirectoryRelative===``?r.name:S(e.subdirectoryRelative,r.name),unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment})}}function Lt(e,t,n){for(let r of t){let t=D(r),i=S(n,r.name);if(t===`directory`)continue;if(t===`other`){e.unsupportedEntryCode!==void 0&&e.diagnostics.push(E({code:e.unsupportedEntryCode,message:e.unsupportedEntryMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a regular file or directory within "${e.relativeDirectory}/".`,sourcePath:i}));continue}if(e.unsupportedFileCode===void 0)continue;let a=k(r.name)!==null,o=e.allowMarkdown&&r.name.endsWith(`.md`);a||o||e.diagnostics.push(E({code:e.unsupportedFileCode,message:e.unsupportedFileMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a supported authored source within "${e.relativeDirectory}/".`,sourcePath:i}))}}async function Rt(e,t,n){for(let r of Nt(t,{allowMarkdown:e.allowMarkdown,allowModules:!0})){let t=e.subdirectoryRelative===``?r.slotName:S(e.subdirectoryRelative,r.slotName),i=O(S(e.relativeDirectory,t));if(e.validateSegment!==void 0){let t=r.markdownFileName??r.moduleFileNames[0]??r.slotName,i=e.validateSegment(r.slotName,S(n,t));if(i!==null){e.diagnostics.push(i);continue}}if(r.markdownFileName!==void 0&&r.moduleFileNames.length>0){e.diagnostics.push($t(n,i,[r.markdownFileName,...r.moduleFileNames]));continue}if(r.moduleFileNames.length>1){e.diagnostics.push(en(n,i,r.moduleFileNames));continue}if(r.markdownFileName!==void 0){let t=e.subdirectoryRelative===``?r.markdownFileName:S(e.subdirectoryRelative,r.markdownFileName),n=O(S(e.relativeDirectory,t));if(e.markdownLowerer===void 0)continue;let i=await jt({logicalPath:n,lower:e.markdownLowerer,source:e.projectSource,sourcePath:S(e.rootDirectoryPath,t)});e.sources.push(i);continue}let[a]=r.moduleFileNames;if(a===void 0)continue;let o=e.subdirectoryRelative===``?a:S(e.subdirectoryRelative,a);e.sources.push(N({logicalPath:O(S(e.relativeDirectory,o))}))}}const zt=`discover/module-slot-collision`,Bt=`discover/tools-directory-invalid`,Vt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ht=/^[a-z][a-z0-9-]{0,63}$/,Ut=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,Wt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;async function F(e,t){let n=[...await e.readDirectory(t)];return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function Gt(e){let t=await Kt({markdownFileName:`instructions.md`,moduleBaseName:`instructions`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`instructions`,source:e.source});if(t.diagnostics.length>0||t.source!==void 0)return{diagnostics:t.diagnostics,instructions:t.source};let n=await Kt({markdownFileName:`system.md`,moduleBaseName:`system`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`system`,source:e.source});if(n.source!==void 0){let t=n.source.sourceKind===`markdown`?`system.md`:n.source.logicalPath;return{diagnostics:[Ie({code:`discover/deprecated-system-slot`,message:`The "${t}" slot is deprecated. Rename it to "${t.replace(/^system/,`instructions`)}" — the runtime still loads the legacy slot for now, but support will be removed in a future release.`,sourcePath:S(e.rootPath,t)}),...n.diagnostics],instructions:n.source}}return n.diagnostics.length>0?{diagnostics:n.diagnostics}:{diagnostics:[E({code:`discover/required-instructions-missing`,message:`Expected one authored instructions prompt source at "instructions.md", "instructions.ts", "instructions.cts", "instructions.mts", "instructions.js", "instructions.cjs", or "instructions.mjs".`,sourcePath:e.rootPath})]}}async function Kt(e){let t=Mt(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[$t(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await jt({logicalPath:e.markdownFileName,lower:pt,source:e.source,sourcePath:S(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:N({logicalPath:n})}}function qt(e){let t=Mt(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[E({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:N({logicalPath:n})}}function Jt(e,t){return Vt.test(e)?null:E({code:`discover/tool-name-invalid`,message:`Tool filename "${e}" is not a legal tool name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Yt(e,t){return Ht.test(e)?null:E({code:`discover/connection-name-invalid`,message:`Connection filename "${e}" is not a legal connection name. Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Xt(e,t){return Ut.test(e)?null:E({code:`discover/channel-name-invalid`,message:`Channel path segment "${e}" is not a legal channel name. Expected lowercase kebab-case (\`my-channel\`), optionally with a leading dot (\`.well-known\`), or a path parameter form (\`[sessionId]\`).`,sourcePath:t})}function Zt(e,t){return Wt.test(e)?null:E({code:`discover/hook-name-invalid`,message:`Hook path segment "${e}" is not a legal hook name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Qt(e){return e.rootEntries.flatMap(t=>!t.isDirectory()||e.classifyEntry(t.name,D(t))!==`unknown`?[]:[Ie({code:`discover/unsupported-directory`,message:e.createUnsupportedDirectoryMessage(t.name),sourcePath:S(e.rootPath,t.name)})])}function $t(e,t,n){return E({code:`discover/slot-collision`,message:`Found conflicting authored sources for "${t}": ${tn(n)}.`,sourcePath:e})}function en(e,t,n){return E({code:zt,message:`Found multiple authored module sources for "${t}": ${tn(n)}.`,sourcePath:e})}function tn(e){return e.map(e=>`"${e}"`).join(`, `)}async function nn(e){let t=`connections`,n=S(e.rootPath,t),r=e.rootEntries.find(e=>e.name===t);if(r===void 0)return{connections:[],diagnostics:[]};if(!r.isDirectory())return{connections:[],diagnostics:[E({code:`discover/connections-directory-invalid`,message:`Expected "${n}" to be a directory of authored connections.`,sourcePath:n})]};let i=await F(e.source,n),a=[],o=[],s=new Set;for(let e of Nt(i,{allowMarkdown:!1,allowModules:!0})){let r=O(S(t,e.slotName));if(e.moduleFileNames.length>1){s.add(e.slotName),o.push(en(n,r,e.moduleFileNames));continue}let[i]=e.moduleFileNames;if(i===void 0)continue;s.add(e.slotName);let c=Yt(e.slotName,S(n,i));if(c!==null){o.push(c);continue}a.push(Ot({connectionName:e.slotName,logicalPath:S(t,i)}))}for(let r of i){if(!r.isDirectory())continue;let i=r.name,c=S(n,i);if(s.has(i)){o.push(E({code:`discover/connection-file-folder-collision`,message:`Connection "${i}" is defined twice. Found both file-form "connections/${i}.ts" and folder-form "connections/${i}/". Use one form, not both.`,sourcePath:c}));let e=a.findIndex(e=>e.connectionName===i);e!==-1&&a.splice(e,1);continue}let l=Yt(i,c);if(l!==null){o.push(l);continue}let u=rn(await F(e.source,c));if(u.length>1){o.push(E({code:zt,message:`Found multiple connection definition modules inside "${O(S(t,i))}": `+u.map(e=>`"${e}"`).join(`, `),sourcePath:c}));continue}let[d]=u;if(d===void 0){o.push(E({code:`discover/connection-folder-empty`,message:`Connection folder "connections/${i}/" contains no "connection.ts" definition. Add "connections/${i}/connection.ts" or use the file form "connections/${i}.ts".`,sourcePath:c}));continue}a.push(Ot({connectionName:i,logicalPath:S(t,i,d)}))}return{connections:a,diagnostics:o}}function rn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===`connection`&&n.push(...e.moduleFileNames);return n}const an=`discover/lib-entry-unsupported`;async function on(e){let t=await P({directoryName:`lib`,invalidDirectoryCode:`discover/lib-directory-invalid`,invalidDirectoryMessage:`Expected "${e.agentRoot}/lib" to be a directory of authored helper modules.`,recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedEntryCode:an,unsupportedEntryMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`,unsupportedFileCode:an,unsupportedFileMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`});return{diagnostics:t.diagnostics,lib:t.sources}}function I(){return{kind:`disk`,async readDirectory(e){return await _e(e,{withFileTypes:!0})},async readTextFile(e){return await ge(e,`utf8`)},async stat(e){try{let t=await ye(e);return t.isDirectory()?`directory`:t.isFile()?`file`:`other`}catch{return`missing`}}}}const sn=`sandbox`,cn=`workspace`,ln=`sandbox`;async function un(e){let t=[],n=e.rootEntries.find(e=>e.name===sn);if(n===void 0)return dn({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=S(e.rootPath,sn);if(!n.isDirectory())return t.push(E({code:`discover/sandbox-directory-invalid`,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await F(e.source,r),a=fn(i),o=i.find(e=>e.name===cn&&e.isDirectory());if(a.length>1)return t.push(E({code:zt,message:`Found multiple sandbox definition modules inside "${O(sn)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[s]=a,c=s!==void 0,l=o!==void 0;if(!c&&!l)return t.push(E({code:`discover/sandbox-folder-empty`,message:`Sandbox folder "sandbox/" contains neither a "sandbox.<ext>" definition nor a "workspace/" subdirectory. Add one or the other, or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let u=null;c&&(u=N({logicalPath:S(sn,s)}));let d=null;if(l){let n=S(r,cn),i=O(S(sn,cn)),a=await mn(e.source,n);a===null?d={logicalPath:i,rootEntries:await pn(e.source,n),sourceId:M(i),sourcePath:n}:t.push(a)}return{diagnostics:t,sandbox:u,sandboxWorkspace:d}}function dn(e){let t=Mt(e.rootEntries,{moduleBaseName:ln});if(t.moduleFileNames.length>1)return e.diagnostics.push(E({code:zt,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:N({logicalPath:n}),sandboxWorkspace:null}}function fn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===ln&&n.push(...e.moduleFileNames);return n}async function pn(e,t){let n=await F(e,t),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}async function mn(e,t){return(await F(e,t)).find(e=>e.name===`skills`)===void 0?null:E({code:`discover/sandbox-workspace-skills-reserved`,message:`"sandbox/workspace/skills/" is reserved for the framework skill discovery. Move skill files under "agent/skills/" instead, or rename the subtree.`,sourcePath:S(t,`skills`)})}const hn=`discover/skill-frontmatter-invalid`;async function gn(e){let t=e.source??I(),n=C(e.agentRoot),r=C(e.skillsDirectoryPath??S(n,`skills`)),i=O(e.skillsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],skills:[]};if(a!==`directory`)return{diagnostics:[E({code:`discover/skills-directory-invalid`,message:`Expected "${r}" to be a directory of authored skills.`,sourcePath:r})],skills:[]};let o=[],s=new Set,c=new Map,l=await F(t,r);for(let e of l){let n=await _n({entryName:e.name,entryType:D(e),skillsDirectoryPath:r,skillsLogicalPath:i,source:t});if(o.push(...n.diagnostics),n.skill===null||n.skillId===null||s.has(n.skillId))continue;let a=c.get(n.skillId);if(a!==void 0){o.push(E({code:`discover/skill-collision`,message:`Found conflicting authored skill sources for "${n.skillId}": "${a.logicalPath}" and "${n.logicalPath}".`,sourcePath:S(r,n.skillId)})),s.add(n.skillId),c.delete(n.skillId);continue}c.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:o,skills:[...c.values()].map(e=>e.skill)}}async function _n(e){let t=S(e.skillsDirectoryPath,e.entryName);switch(Qe(e.entryName,e.entryType)){case`skill-package-directory`:return vn({logicalSkillsPath:e.skillsLogicalPath,skillId:e.entryName,skillRootPath:t,source:e.source});case`flat-skill-markdown`:return yn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName,skillFilePath:t,source:e.source});case`flat-skill-module`:return bn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName});default:return{diagnostics:[E({code:`discover/skill-entry-not-directory`,message:`Expected "${t}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:t})],logicalPath:O(S(e.skillsLogicalPath,e.entryName)),skill:null,skillId:null}}}async function vn(e){let t=S(e.skillRootPath,`SKILL.md`),n=O(S(e.logicalSkillsPath,e.skillId,`SKILL.md`));if(await e.source.stat(t)!==`file`)return{diagnostics:[E({code:`discover/skill-markdown-missing`,message:`Expected "${t}" to exist for the "${e.skillId}" skill.`,sourcePath:e.skillRootPath})],logicalPath:n,skill:null,skillId:null};let r;try{r=ht(await e.source.readTextFile(t))}catch(e){return{diagnostics:[E({code:hn,message:Sn(t,e),sourcePath:t})],logicalPath:n,skill:null,skillId:null}}let i=await xn(e.source,e.skillRootPath),a={description:r.description,logicalPath:n,markdown:r.markdown,name:e.skillId,rootPath:e.skillRootPath,skillFilePath:t,skillId:e.skillId,sourceId:M(n)};return i.assetsPath!==void 0&&(a.assetsPath=i.assetsPath),r.license!==void 0&&(a.license=r.license),r.metadata!==void 0&&(a.metadata=r.metadata),i.referencesPath!==void 0&&(a.referencesPath=i.referencesPath),i.scriptsPath!==void 0&&(a.scriptsPath=i.scriptsPath),{diagnostics:[],logicalPath:n,skill:At(a),skillId:e.skillId}}async function yn(e){let t=Cn(e.skillFileName),n=O(S(e.logicalSkillsPath,e.skillFileName)),r;try{r=ht(await e.source.readTextFile(e.skillFilePath),{slug:t})}catch(t){return{diagnostics:[E({code:hn,message:Sn(e.skillFilePath,t),sourcePath:e.skillFilePath})],logicalPath:n,skill:null,skillId:null}}return{diagnostics:[],logicalPath:n,skill:{definition:r,sourceKind:`markdown`,logicalPath:n,sourceId:M(n)},skillId:t}}async function bn(e){let t=k(e.skillFileName),n=O(S(e.logicalSkillsPath,e.skillFileName));return t===null?{diagnostics:[],logicalPath:n,skill:null,skillId:null}:{diagnostics:[],logicalPath:n,skill:N({logicalPath:n}),skillId:t}}async function xn(e,t){let n=await e.readDirectory(t),r={};for(let e of n)if(e.isDirectory())switch(Ze(e.name,D(e))){case`skill-assets-directory`:r.assetsPath=S(t,e.name);break;case`skill-references-directory`:r.referencesPath=S(t,e.name);break;case`skill-scripts-directory`:r.scriptsPath=S(t,e.name);break;default:break}return r}function Sn(e,t){return`Invalid authored skill frontmatter in "${e}": ${m(t)}`}function Cn(e){return e.endsWith(`.md`)?e.slice(0,-3):e}async function wn(e){let t=e.source??I(),n=C(e.agentRoot),r=C(e.subagentsDirectoryPath??S(n,`subagents`)),i=O(e.subagentsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],subagents:[]};if(a!==`directory`)return{diagnostics:[E({code:`discover/subagents-directory-invalid`,message:`Expected "${r}" to be a directory of authored subagents.`,sourcePath:r})],subagents:[]};let o=await F(t,r),s=[],c=[];for(let n of o){if(!n.isDirectory())continue;let a=await Tn({appRoot:e.appRoot,source:t,subagentId:n.name,subagentLogicalPath:S(i,n.name),subagentRoot:S(r,n.name)});s.push(...a.diagnostics),c.push(a.subagent)}return{diagnostics:s,subagents:c}}async function Tn(e){let t=[],n=await F(e.source,e.subagentRoot);t.push(...Qt({classifyEntry:Xe,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:n,rootPath:e.subagentRoot}));let r=await Gt({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...r.diagnostics);let i=qt({missingDiagnostic:{code:`discover/required-subagent-config-module-missing`,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:n,rootPath:e.subagentRoot,slotName:`agent`});t.push(...i.diagnostics);let a=await nn({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...a.diagnostics);let o=await un({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...o.diagnostics);let s=await P({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${S(e.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Jt});t.push(...s.diagnostics);let c=await P({directoryName:`hooks`,invalidDirectoryCode:On,invalidDirectoryMessage:`Expected "${S(e.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Zt});t.push(...c.diagnostics);let l=await on({agentRoot:e.subagentRoot,rootEntries:n,source:e.source});t.push(...l.diagnostics),t.push(...En(e.subagentRoot,n));let u=await gn({agentRoot:e.subagentRoot,source:e.source});t.push(...u.diagnostics);let d=await wn({agentRoot:e.subagentRoot,appRoot:e.appRoot,source:e.source});t.push(...d.diagnostics);let f={agentRoot:e.subagentRoot,appRoot:e.appRoot,connections:a.connections,diagnostics:t,hooks:c.sources,lib:l.lib,instructions:r.instructions,sandbox:o.sandbox,sandboxWorkspaces:o.sandboxWorkspace===null?[]:[o.sandboxWorkspace],skills:u.skills,tools:s.sources,subagents:d.subagents};i.module!==void 0&&(f.configModule=i.module);let p=Et(f);return{diagnostics:t,subagent:kt({entryPath:e.subagentRoot,logicalPath:e.subagentLogicalPath,manifest:p,rootPath:e.subagentRoot,subagentId:e.subagentId})}}function En(e,t){return t.flatMap(t=>Xe(t.name,D(t))===`invalid-schedules-directory`?[E({code:`discover/local-subagent-schedules-invalid`,message:`Local subagent packages cannot define schedules at "${S(e,t.name)}".`,sourcePath:S(e,t.name)})]:[])}async function Dn(e){let t=await P({allowMarkdown:!0,directoryName:`schedules`,invalidDirectoryCode:`discover/schedules-directory-invalid`,invalidDirectoryMessage:`Expected "${S(e.agentRoot,`schedules`)}" to be a directory of authored schedules.`,markdownLowerer:e=>mt(e),recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedFileCode:`discover/schedule-file-unsupported`,unsupportedFileMessage:e=>`Expected "${e}" to be a TypeScript or markdown schedule file within "schedules/".`});return{diagnostics:t.diagnostics,schedules:t.sources}}const On=`discover/hooks-directory-invalid`;async function kn(e){let t=e.source??I(),n=C(e.appRoot),r=C(e.agentRoot),i=[],a=await An(t,n),o=await F(t,r);i.push(...Qt({classifyEntry:Ye,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:o,rootPath:r}));let s=await Gt({rootEntries:o,rootPath:r,source:t});i.push(...s.diagnostics);let c=qt({rootEntries:o,rootPath:r,slotName:`agent`});i.push(...c.diagnostics);let l=await P({directoryName:`channels`,invalidDirectoryCode:`discover/channels-directory-invalid`,invalidDirectoryMessage:`Expected "${S(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Xt});i.push(...l.diagnostics);let u=await on({agentRoot:r,rootEntries:o,source:t});i.push(...u.diagnostics);let d=await Dn({agentRoot:r,rootEntries:o,source:t});i.push(...d.diagnostics);let f=await nn({rootEntries:o,rootPath:r,source:t});i.push(...f.diagnostics);let p=await un({rootEntries:o,rootPath:r,source:t});i.push(...p.diagnostics);let m=await P({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${S(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Jt});i.push(...m.diagnostics);let h=await P({directoryName:`hooks`,invalidDirectoryCode:On,invalidDirectoryMessage:`Expected "${S(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Zt});i.push(...h.diagnostics);let g=await gn({agentRoot:r,source:t});i.push(...g.diagnostics);let _=await wn({agentRoot:r,appRoot:n,source:t});i.push(..._.diagnostics);let v={agentRoot:r,appRoot:n,channels:l.sources,connections:f.connections,packageName:a,diagnostics:i,hooks:h.sources,lib:u.lib,instructions:s.instructions,sandbox:p.sandbox,sandboxWorkspaces:p.sandboxWorkspace===null?[]:[p.sandboxWorkspace],schedules:d.schedules,skills:g.skills,tools:m.sources,subagents:_.subagents};return c.module!==void 0&&(v.configModule=c.module),{diagnostics:i,manifest:Et(v)}}async function An(e,t){try{let n=S(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;if(typeof r!=`string`||r.length===0)return;let i=r.lastIndexOf(`/`);return i===-1?r:r.slice(i+1)}catch{return}}var jn=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function Mn(e=process.cwd(),t={}){let n=t.source??I(),r=await Nn(n,e),i=r;for(;;){let e=await Pn(n,i);if(e!==null)return e;let t=await Fn(n,i);if(t!==null)return t;if(await In(n,i))return{agentRoot:i,appRoot:i,layout:`flat`};let r=x(i);if(r===i)break;i=r}throw new jn(E({code:`discover/project-not-found`,message:`Could not resolve an Ash agent root from "${r}".`,sourcePath:r}))}async function Nn(e,t){let n=C(t);return await e.stat(n)===`directory`?n:x(n)}async function Pn(e,t){if(ue(t)!==`agent`)return null;let n=x(t);return await Ln(e,n)?{agentRoot:t,appRoot:n,layout:`nested`}:null}async function Fn(e,t){if(!await Ln(e,t))return null;let n=S(t,`agent`);return await zn(e,n)?{agentRoot:n,appRoot:t,layout:`nested`}:null}async function In(e,t){let n=await Rn(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=Ye(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function Ln(e,t){let n=await Rn(e,t);return Array.from(n.entries()).some(([e,t])=>Je(e,t))}async function Rn(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,D(e)]))}async function zn(e,t){return await e.stat(t)===`directory`}const Bn=`ash-agent-compiled-manifest`,L=`__root__`,Vn=b.object({exportName:b.string().optional(),sourceKind:b.literal(`module`),logicalPath:b.string(),sourceId:b.string()}).strict(),Hn=b.union([b.literal(`GET`),b.literal(`POST`),b.literal(`PUT`),b.literal(`DELETE`),b.literal(`PATCH`)]),Un=b.object({kind:b.literal(`channel`),name:b.string(),logicalPath:b.string(),method:Hn,urlPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),exportName:b.string().optional(),adapterKind:b.string().optional()}).strict(),Wn=b.object({kind:b.literal(`disabled`),name:b.string(),logicalPath:b.string()}).strict(),Gn=b.union([Un,Wn]),Kn=b.object({contextWindowTokens:b.number().int().positive().optional(),id:b.string(),source:Vn.optional(),providerOptions:ce.optional()}).strict(),qn=b.object({externalDependencies:b.array(b.string()).optional()}).strict(),Jn=b.object({model:Kn.optional(),thresholdPercent:b.number().finite().min(0).max(1).optional()}).strict(),Yn=b.object({build:qn.optional(),compaction:Jn.optional(),description:b.string().optional(),metadata:b.record(b.string(),b.string()),model:Kn,name:b.string(),source:Vn.optional()}).strict(),Xn=b.object({name:b.string(),logicalPath:b.string(),markdown:b.string(),sourceId:b.string(),sourceKind:b.union([b.literal(`markdown`),b.literal(`module`)])}).strict(),Zn={name:b.string(),description:b.string(),license:b.string().optional(),markdown:b.string(),metadata:b.record(b.string(),b.string()).optional(),sourceId:b.string(),logicalPath:b.string()},Qn=b.discriminatedUnion(`sourceKind`,[b.object({...Zn,sourceKind:b.literal(`markdown`)}).strict(),b.object({...Zn,sourceKind:b.literal(`module`),exportName:b.string().optional()}).strict(),b.object({...Zn,sourceKind:b.literal(`skill-package`),skillId:b.string(),skillFilePath:b.string(),rootPath:b.string(),assetsPath:b.string().optional(),referencesPath:b.string().optional(),scriptsPath:b.string().optional()}).strict()]),$n=b.object({name:b.string(),args:b.record(b.string(),b.unknown())}).strict(),er=b.object({channel:$n.optional(),cron:b.string(),name:b.string(),logicalPath:b.string(),markdown:b.string(),sourceId:b.string(),sourceKind:b.union([b.literal(`markdown`),b.literal(`module`)])}).strict(),tr=b.object({description:b.string().optional(),exportName:b.string().optional(),logicalPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),nr=b.object({logicalPath:b.string(),rootEntries:b.array(b.string()).readonly(),sourceId:b.string(),sourcePath:b.string()}).strict(),rr=b.object({logicalPath:b.string(),rootEntries:b.array(b.string()).readonly()}).strict(),ir=b.object({connectionName:b.string(),description:b.string(),exportName:b.string().optional(),logicalPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),url:b.string(),vercelConnect:b.object({connector:b.string()}).strict().optional()}).strict(),ar=b.object({description:b.string(),exportName:b.string().optional(),inputSchema:ce.nullable(),logicalPath:b.string(),name:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),or=b.object({exportName:b.string().optional(),logicalPath:b.string(),slug:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`)}).strict(),sr=b.object({agentRoot:b.string(),appRoot:b.string(),channels:b.array(Gn),config:Yn,connections:b.array(ir),diagnosticsSummary:Pe,disabledFrameworkTools:b.array(b.string()).readonly(),hooks:b.array(or),sandbox:tr.nullable(),sandboxWorkspaces:b.array(nr),schedules:b.array(er),skills:b.array(Qn).readonly(),instructions:Xn.optional(),tools:b.array(ar),workspaceResourceRoot:rr}).strict(),cr=b.object({agent:sr,description:b.string(),entryPath:b.string(),logicalPath:b.string(),name:b.string(),nodeId:b.string(),rootPath:b.string(),sourceId:b.string(),sourceKind:b.literal(`module`),exportName:b.string().optional()}).strict(),lr=b.object({childNodeId:b.string(),parentNodeId:b.string()}).strict(),ur=b.object({agentRoot:b.string(),appRoot:b.string(),channels:b.array(Gn),config:Yn,connections:b.array(ir),diagnosticsSummary:Pe,disabledFrameworkTools:b.array(b.string()).readonly(),hooks:b.array(or),kind:b.literal(Bn),sandbox:tr.nullable(),sandboxWorkspaces:b.array(nr),schedules:b.array(er),skills:b.array(Qn).readonly(),subagentEdges:b.array(lr),subagents:b.array(cr),instructions:Xn.optional(),tools:b.array(ar),version:b.literal(22),workspaceResourceRoot:rr}).strict();function dr(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:hr(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,metadata:{...e.config.metadata},model:hr(e.config.model),name:e.config.name,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],hooks:[...e.hooks??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:fr({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function fr(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function pr(e,t){return e===`__root__`?t:`${e}::${t}`}function mr(e){return{...dr(e),kind:Bn,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:22}}function hr(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}const gr=/^\/?[A-Za-z]:[\\/]/,_r=/^\\\\[^\\]/,vr=/(\b(?:from|import)\s*(?:\(\s*)?)(["'])([A-Za-z]:[\\/][^"'\n\r]*)\2/g;function yr(e){return gr.test(e)||_r.test(e)}function br(e){let t=e.replaceAll(`\\`,`/`);return t.startsWith(`//`)?new URL(`file:${t}`).href:(/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1)),new URL(`file:///${t}`).href)}function xr(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}function Sr(e){if(e.startsWith(`file://`))return e;let{path:t,suffix:n}=xr(e);return yr(t)?`${br(t)}${n}`:e.replaceAll(`\\`,`/`)}function Cr(e){return JSON.stringify(Sr(e))}function wr(e){return e.replace(vr,(e,t,n,r)=>`${t}${n}${Sr(r)}${n}`)}const Tr=b.object({modules:b.record(b.string(),b.object({}).passthrough())}).strict(),Er=b.object({nodes:b.record(b.string(),Tr)}).strict();function Dr(e){let t=Nr(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=[Or({agentRoot:e.manifest.agentRoot,importSpecifierStyle:n,manifest:e.manifest,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:L}),...[...e.manifest.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>Or({agentRoot:e.agent.agentRoot,importSpecifierStyle:n,manifest:e.agent,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:e.nodeId}))],a=i.flatMap(e=>e.modules.map(e=>`import * as ${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`));return[`// Generated by Ash. Do not edit by hand.`,``,...a,...a.length>0?[``]:[],`export const moduleMap = ${jr(i)};`,``,`export default moduleMap;`,``].join(`
4
4
  `)}function Or(e){return{modules:kr(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:Ar({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Pr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function kr(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function Ar(e){if(e.importSpecifierStyle===`absolute`)return Sr(Ir(e.targetPath));let t=Fr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function jr(e){return Mr([{key:`nodes`,value:Mr(e.map(e=>({key:e.nodeId,value:Mr([{key:`modules`,value:Mr(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Mr(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
@@ -1,4 +1,4 @@
1
- import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-ByH5Mnvt.js";import{t as m}from"./authored-module-loader-Pt_g8xX2.js";import{t as h}from"./errors-DsO9xmQL.js";import{i as g,t as _}from"./package-DmsQgn4v.js";import{join as v,posix as y}from"node:path";import{mkdir as ne,readFile as re,readdir as ie,realpath as b,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:g(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,o=a();for(let e of t){if(e.kind===`disabled`){if(!o.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: ${[...o].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let s=l().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),c=new Set,u=[];for(let e of[...s,...r]){let t=k(e);c.has(t)||(c.add(t),u.push(e))}return u}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(g(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
1
+ import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-BYA-Yank.js";import{t as m}from"./authored-module-loader-Pt_g8xX2.js";import{t as h}from"./errors-DsO9xmQL.js";import{i as g,t as _}from"./package-DmsQgn4v.js";import{join as v,posix as y}from"node:path";import{mkdir as ne,readFile as re,readdir as ie,realpath as b,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:g(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,o=a();for(let e of t){if(e.kind===`disabled`){if(!o.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: ${[...o].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let s=l().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),c=new Set,u=[];for(let e of[...s,...r]){let t=k(e);c.has(t)||(c.add(t),u.push(e))}return u}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(g(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
2
2
  `)}function j(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&M(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(T)&&delete e.options.virtual[t]}function M(e){return e.handler.startsWith(T)}function N(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}const P=`ash.schedule.`;var F=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 I(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:R(e.sourceId)})).sort((e,t)=>e.sourceId.localeCompare(t.sourceId));return L(t),t}function L(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 F(`Duplicate authored schedule id "${n.scheduleId}" found in "${e.logicalPath}" and "${n.logicalPath}".`,{scheduleId:n.scheduleId,sourceId:n.sourceId,taskName:n.taskName})}}function R(e){return`${P}${Buffer.from(e,`utf8`).toString(`base64url`)}`}const z=`#ash-schedule-task/`;function B(e,t){if(t.registrations.length!==0){e.options.experimental.tasks=!0;for(let n of t.registrations)U(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registration:n})}}function V(e,t){let n=!G(t.previous,t.next);return H(e),B(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registrations:t.next}),n}function H(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(z)&&delete e.options.virtual[t];for(let[t,n]of Object.entries(e.options.scheduledTasks)){let r=W(n).filter(e=>!e.startsWith(P));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 U(e,t){let r=`${z}${t.registration.taskName}`,i=n(t.dispatchModulePath);e.options.tasks[t.registration.taskName]={description:t.registration.description,handler:r},e.options.virtual[r]=[`import { dispatchScheduleTask } from ${i};`,`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(`
3
3
  `),ae(e,t.registration.cron,t.registration.taskName)}function ae(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 W(e){return typeof e==`string`?[e]:[...e]}function G(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}async function K(e){return[...e.manifest.schedules].map(e=>{let t={cron:e.cron,logicalPath:e.logicalPath,markdown:e.markdown,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.channel===void 0?t:{...t,channel:e.channel}})}async function q(e){return await K({manifest:await o({compiledArtifactsSource:e.compiledArtifactsSource})})}async function J(e){let t=v(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=v(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=se(e.compileResult.manifest.agentRoot);await ne(e.outDir,{recursive:!0}),await x(t,await le({compileResult:e.compileResult,installModulePath:g(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),r!==void 0&&await x(n,ue({agentName:e.compileResult.manifest.config.name,instrumentationPath:r,registerConfigPath:g(`src/harness/instrumentation-config.ts`)}));let i={bootstrapPath:t};return r!==void 0&&(i.instrumentationPluginPath=n,i.instrumentationSourcePath=r),i}const oe=[`.ts`,`.mts`,`.js`,`.mjs`];function se(e){for(let t of oe){let n=v(e,`instrumentation${t}`);if(C(n))return n}}function ce(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
4
4
  `)}async function le(e){let r=ce(t({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Ash. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${n(e.installModulePath)};`,``,r,``,`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(`
@@ -1,2 +1,2 @@
1
- import{D as e,b as t,t as n,v as r,y as i}from"../../chunks/paths-ByH5Mnvt.js";import{d as a,f as o,h as s}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as c,renderCliBanner as l,renderCliSection as u}from"../ui/output.js";async function d(e){let t=await f(e);return{application:n(t?.project.appRoot??e),compiledState:t,messaging:{createSessionRoutePath:o,continueSessionRoutePattern:a,streamRoutePattern:s}}}async function f(n){try{return await i({startPath:n})}catch(n){if(n instanceof r)return n.result;if(n instanceof e||n instanceof t)return null;throw n}}function p(e,t){return`${e} ${t}${e===1?``:`s`}`}function m(e,t){return`${`${e} error${e===1?``:`s`}`}, ${`${t} warning${t===1?``:`s`}`}`}function h(e){switch(e){case`ready`:return`success`;case`failed`:return`danger`;default:return`warning`}}async function g(e,t){let n=await d(t),r=n.compiledState,i=n.application,a=c(),o=[{label:`App Root`,value:i.appRoot}],s=[{label:`Workflow Build`,value:i.workflowBuildDir},{label:`Output`,value:i.outputDir}],f=[];r===null?o.push({label:`Compile`,tone:`warning`,value:`unavailable`}):(o.push({label:`Agent Root`,value:r.project.agentRoot},{label:`Layout`,value:r.project.layout},{label:`Compile`,tone:h(r.metadata.status),value:r.metadata.status},{label:`Diagnostics`,tone:r.metadata.discovery.summary.errors>0?`danger`:r.metadata.discovery.summary.warnings>0?`warning`:`success`,value:m(r.metadata.discovery.summary.errors,r.metadata.discovery.summary.warnings)},{label:`Instructions`,value:r.manifest.instructions?.logicalPath??`none`},{label:`Skills`,value:p(r.manifest.skills.length,`skill`)}),s.unshift({label:`Compiled Manifest`,value:r.paths.compiledManifestPath},{label:`Discovery Manifest`,value:r.paths.discoveryManifestPath},{label:`Diagnostics`,value:r.paths.diagnosticsPath},{label:`Module Map`,value:r.paths.moduleMapPath},{label:`Metadata`,value:r.paths.compileMetadataPath}),f.push(r.manifest.instructions===void 0?{label:`Instructions`,value:`No instructions prompt discovered.`}:{label:`Instructions`,value:r.manifest.instructions.logicalPath})),e.log([l(a,{subtitle:`Resolved application paths and the active message contract.`,title:`Ash Info`}),``,u(a,{rows:o,title:`Application`}),``,u(a,{rows:s,title:`Artifacts`}),...r===null?[]:[``,u(a,{rows:f,title:`Instructions`})],``,u(a,{rows:[{label:`Workflow ID`,value:i.workflowId},{label:`Source Dir`,value:i.workflowSourceDir},{label:`Create`,tone:`info`,value:`POST ${n.messaging.createSessionRoutePath}`},{label:`Continue`,tone:`info`,value:`POST ${n.messaging.continueSessionRoutePattern}`},{label:`Stream`,tone:`info`,value:`GET ${n.messaging.streamRoutePattern}`}],title:`Messaging`})].join(`
1
+ import{D as e,b as t,t as n,v as r,y as i}from"../../chunks/paths-BYA-Yank.js";import{d as a,f as o,h as s}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as c,renderCliBanner as l,renderCliSection as u}from"../ui/output.js";async function d(e){let t=await f(e);return{application:n(t?.project.appRoot??e),compiledState:t,messaging:{createSessionRoutePath:o,continueSessionRoutePattern:a,streamRoutePattern:s}}}async function f(n){try{return await i({startPath:n})}catch(n){if(n instanceof r)return n.result;if(n instanceof e||n instanceof t)return null;throw n}}function p(e,t){return`${e} ${t}${e===1?``:`s`}`}function m(e,t){return`${`${e} error${e===1?``:`s`}`}, ${`${t} warning${t===1?``:`s`}`}`}function h(e){switch(e){case`ready`:return`success`;case`failed`:return`danger`;default:return`warning`}}async function g(e,t){let n=await d(t),r=n.compiledState,i=n.application,a=c(),o=[{label:`App Root`,value:i.appRoot}],s=[{label:`Workflow Build`,value:i.workflowBuildDir},{label:`Output`,value:i.outputDir}],f=[];r===null?o.push({label:`Compile`,tone:`warning`,value:`unavailable`}):(o.push({label:`Agent Root`,value:r.project.agentRoot},{label:`Layout`,value:r.project.layout},{label:`Compile`,tone:h(r.metadata.status),value:r.metadata.status},{label:`Diagnostics`,tone:r.metadata.discovery.summary.errors>0?`danger`:r.metadata.discovery.summary.warnings>0?`warning`:`success`,value:m(r.metadata.discovery.summary.errors,r.metadata.discovery.summary.warnings)},{label:`Instructions`,value:r.manifest.instructions?.logicalPath??`none`},{label:`Skills`,value:p(r.manifest.skills.length,`skill`)}),s.unshift({label:`Compiled Manifest`,value:r.paths.compiledManifestPath},{label:`Discovery Manifest`,value:r.paths.discoveryManifestPath},{label:`Diagnostics`,value:r.paths.diagnosticsPath},{label:`Module Map`,value:r.paths.moduleMapPath},{label:`Metadata`,value:r.paths.compileMetadataPath}),f.push(r.manifest.instructions===void 0?{label:`Instructions`,value:`No instructions prompt discovered.`}:{label:`Instructions`,value:r.manifest.instructions.logicalPath})),e.log([l(a,{subtitle:`Resolved application paths and the active message contract.`,title:`Ash Info`}),``,u(a,{rows:o,title:`Application`}),``,u(a,{rows:s,title:`Artifacts`}),...r===null?[]:[``,u(a,{rows:f,title:`Instructions`})],``,u(a,{rows:[{label:`Workflow ID`,value:i.workflowId},{label:`Source Dir`,value:i.workflowSourceDir},{label:`Create`,tone:`info`,value:`POST ${n.messaging.createSessionRoutePath}`},{label:`Continue`,tone:`info`,value:`POST ${n.messaging.continueSessionRoutePattern}`},{label:`Stream`,tone:`info`,value:`GET ${n.messaging.streamRoutePattern}`}],title:`Messaging`})].join(`
2
2
  `))}export{g as printApplicationInfo};
@@ -1,3 +1,3 @@
1
- import{t as e}from"../chunks/package-DmsQgn4v.js";import{createCliTheme as t,renderCliTaggedLine as n}from"./ui/output.js";import{i as r,n as i,r as a,t as o}from"../chunks/url-BVRhVE2O.js";import{resolve as s}from"node:path";async function c(){return(await import(`../chunks/host-q4jM7D0h.js`).then(e=>e.t)).buildHost}async function l(){return(await import(`./commands/info.js`)).printApplicationInfo}async function u(){return(await import(`./dev/repl.js`)).runDevelopmentRepl}async function d(){return(await import(`../evals/cli/eval.js`)).runEvalCommand}async function f(){return(await import(`../chunks/host-q4jM7D0h.js`).then(e=>e.t)).startHost}function p(e=process.cwd()){return s(e)}function m(e){return`Ash (v${e})`}function h(e){return e.name()===`info`||e.name()===`dev`}async function g(e){await new Promise((t,n)=>{let r=!1,i=()=>{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)},a=()=>{r||(r=!0,i(),e.close().then(t,n))};process.once(`SIGINT`,a),process.once(`SIGTERM`,a)})}function _(e){if(!/^-?\d+$/.test(e))throw new r(`Expected a numeric port, received "${e}".`);let t=Number(e);if(!Number.isInteger(t))throw new r(`Expected a numeric port, received "${e}".`);if(t<0||t>65535)throw new r(`Expected a port between 0 and 65535, received "${e}".`);return t}function v(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function y(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function b(e){if(e.url){if(e.host!==void 0)throw new r(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new r(`The --port option cannot be used with --url.`);if(e.repl===!1)throw new r(`The --no-repl option cannot be used with --url.`);return e.url}}function x(r,a){let s=p(),y=e().version,x=new i,S=t();return x.name(`ash`).description(`Build and run an Ash application.`).version(y).showHelpAfterError().exitOverride().hook(`preAction`,(e,t)=>{h(t)&&r.log(m(y))}).configureOutput({writeErr:e=>{r.error(e.trimEnd())},writeOut:e=>{r.log(e.trimEnd())}}),x.command(`build`).description(`Build the current Ash application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:e}=await import(`./dev/environment.js`);e(s);let t=await(a.buildHost??await c())(s);r.log(n(S,{message:`built output at ${t}`,tag:`build`,tone:`success`}))}),x.command(`dev`).description(`Start the Ash development server or connect the REPL to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--no-repl`,`Start the server without the interactive REPL`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,_).option(`--schedules`,`Run scheduled tasks during development (off by default)`).option(`-u, --url <url>`,`Connect the REPL to an existing server URL`,o).addHelpText(`after`,`
1
+ import{t as e}from"../chunks/package-DmsQgn4v.js";import{createCliTheme as t,renderCliTaggedLine as n}from"./ui/output.js";import{i as r,n as i,r as a,t as o}from"../chunks/url-BVRhVE2O.js";import{resolve as s}from"node:path";async function c(){return(await import(`../chunks/host-B2D2qXsD.js`).then(e=>e.t)).buildHost}async function l(){return(await import(`./commands/info.js`)).printApplicationInfo}async function u(){return(await import(`./dev/repl.js`)).runDevelopmentRepl}async function d(){return(await import(`../evals/cli/eval.js`)).runEvalCommand}async function f(){return(await import(`../chunks/host-B2D2qXsD.js`).then(e=>e.t)).startHost}function p(e=process.cwd()){return s(e)}function m(e){return`Ash (v${e})`}function h(e){return e.name()===`info`||e.name()===`dev`}async function g(e){await new Promise((t,n)=>{let r=!1,i=()=>{process.off(`SIGINT`,a),process.off(`SIGTERM`,a)},a=()=>{r||(r=!0,i(),e.close().then(t,n))};process.once(`SIGINT`,a),process.once(`SIGTERM`,a)})}function _(e){if(!/^-?\d+$/.test(e))throw new r(`Expected a numeric port, received "${e}".`);let t=Number(e);if(!Number.isInteger(t))throw new r(`Expected a numeric port, received "${e}".`);if(t<0||t>65535)throw new r(`Expected a port between 0 and 65535, received "${e}".`);return t}function v(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function y(e){let t=e[1];return e[0]!==`dev`||e.length!==2||t===void 0||t.startsWith(`-`)?[...e]:[`dev`,`--url`,t]}function b(e){if(e.url){if(e.host!==void 0)throw new r(`The --host option cannot be used with --url.`);if(e.port!==void 0)throw new r(`The --port option cannot be used with --url.`);if(e.repl===!1)throw new r(`The --no-repl option cannot be used with --url.`);return e.url}}function x(r,a){let s=p(),y=e().version,x=new i,S=t();return x.name(`ash`).description(`Build and run an Ash application.`).version(y).showHelpAfterError().exitOverride().hook(`preAction`,(e,t)=>{h(t)&&r.log(m(y))}).configureOutput({writeErr:e=>{r.error(e.trimEnd())},writeOut:e=>{r.log(e.trimEnd())}}),x.command(`build`).description(`Build the current Ash application.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:e}=await import(`./dev/environment.js`);e(s);let t=await(a.buildHost??await c())(s);r.log(n(S,{message:`built output at ${t}`,tag:`build`,tone:`success`}))}),x.command(`dev`).description(`Start the Ash development server or connect the REPL to an existing URL.`).option(`--host <host>`,`Host interface to bind`).option(`--no-repl`,`Start the server without the interactive REPL`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,_).option(`--schedules`,`Run scheduled tasks during development (off by default)`).option(`-u, --url <url>`,`Connect the REPL to an existing server URL`,o).addHelpText(`after`,`
2
2
  You can also pass a bare URL as the only argument, for example: ash dev https://example.com
3
3
  `).action(async e=>{let t=b(e),{loadDevelopmentEnvironmentFiles:i}=await import(`./dev/environment.js`);if(i(s),t){if(r.log(n(S,{message:`REPL connecting to ${t}`,tag:`dev`,tone:`info`})),!v()){r.log(n(S,{message:`Interactive REPL disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}r.log(``),await(a.runDevelopmentRepl??await u())({serverUrl:t});return}let o=await(a.startHost??await f())(s,{host:e.host,port:e.port,schedules:e.schedules===!0}),c=!1,l=async()=>{c||(c=!0,await o.close())};try{if(r.log(n(S,{message:`server listening at ${o.url}`,tag:`dev`,tone:`success`})),e.repl===!1)return await g({close:l});if(!v())return r.log(n(S,{message:`Interactive REPL disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await g({close:l});r.log(``),await(a.runDevelopmentRepl??await u())({serverUrl:o.url})}finally{await l()}}),x.command(`info`).description(`Print resolved application information.`).action(async()=>{await(a.printApplicationInfo??await l())(r,s)}),x.command(`eval`).description(`Run eval suites against an Ash agent.`).option(`--suite <id...>`,`Suite IDs to run (repeatable)`).option(`--all`,`Run all discovered suites`).option(`--url <url>`,`Remote agent URL (skip local host startup)`).option(`--timeout <ms>`,`Per-case timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent case executions per suite`).option(`--json`,`Output results as JSON`).option(`--list-suites`,`List discovered suites and exit`).option(`--skip-report`,`Skip suite-defined reporters (e.g. Braintrust)`).action(async e=>{await(a.runEvalCommand??await d())(e,r)}),x}async function S(e=process.argv.slice(2),t=console,n={}){let r=x(t,n),i=e.length===0?[`info`]:y(e);try{await r.parseAsync(i,{from:`user`})}catch(e){if(e instanceof a){if(e.exitCode===0)return;throw Error(e.message)}throw e}}export{S as runCli};
@@ -1 +1 @@
1
- import{n as e}from"../../chunks/paths-ByH5Mnvt.js";import{loadDevelopmentEnvironmentFiles as t}from"../../cli/dev/environment.js";import{a as n,n as r,t as i}from"../../chunks/client-BeZ_W7vl.js";import{n as a}from"../../chunks/host-q4jM7D0h.js";import{discoverAndImportSuites as o,discoverSuiteFiles as s,importSuiteFile as c}from"../runner/discover.js";import{executeSuite as l}from"../runner/execute-suite.js";import{ConsoleReporter as u}from"../runner/reporters/console.js";var d=n();function f(e,t){e.command(`eval`).description(`Run eval suites against an Ash agent.`).option(`--suite <id...>`,`Suite IDs to run (repeatable)`).option(`--all`,`Run all discovered suites`).option(`--url <url>`,`Remote agent URL (skip local host startup)`).option(`--timeout <ms>`,`Per-case timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent case executions per suite`).option(`--json`,`Output results as JSON`).option(`--list-suites`,`List discovered suites and exit`).option(`--skip-report`,`Skip suite-defined reporters (e.g. Braintrust)`).action(async e=>{await p(e,t)})}async function p(n,r){let i=e();if(t(i),n.listSuites){await y(i,r);return}let s=n.suite,c=await o(i,s);if(c.length===0){s&&s.length>0?r.error(`No suites found matching: ${s.join(`, `)}`):r.error(`No eval suites found. Create suite files under evals/ with the *.eval.ts extension.`),process.exitCode=1;return}let u,d;n.url?d={kind:`remote`,url:n.url}:(u=await a(i,{host:`127.0.0.1`,port:0}),d={kind:`local`,url:u.url});let f=m(d);try{let e=[];for(let t of c){let r=_(t,n),a=v(r,{json:n.json===!0,skipReport:n.skipReport===!0}),o=await l({suite:r,target:d,reporters:a,appRoot:i,client:f});e.push(o)}n.json&&r.log(JSON.stringify(e,null,2)),e.some(e=>e.errored>0)&&(process.exitCode=1)}finally{u&&await u.close()}process.exit(process.exitCode??0)}function m(e){if(e.kind===`local`)return new i({host:e.url});let t={},n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return n&&(t[r]=n),new i({auth:h(),headers:Object.keys(t).length>0?t:void 0,host:e.url})}function h(){let e=process.env.ASH_EVAL_AUTH_TOKEN?.trim();return e?{bearer:e}:{bearer:g}}async function g(){try{let e=(await(0,d.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{}return process.env.VERCEL_OIDC_TOKEN?.trim()??``}function _(e,t){let n=t.maxConcurrency?Number.parseInt(t.maxConcurrency,10):void 0,r=t.timeout?Number.parseInt(t.timeout,10):void 0;if(n===void 0&&r===void 0)return e;let i={...e};return n!==void 0&&(i.maxConcurrency=n),r!==void 0&&(i.timeoutMs=r),i}function v(e,t){let n=t.json?[]:[new u];return!t.skipReport&&e.reporters&&n.push(...e.reporters),n}async function y(e,t){let n=await s(e);if(n.length===0){t.log(`No eval suites found.`);return}t.log(`Found ${n.length} eval suite file(s):\n`);for(let r of n){let n=await c(e,r);t.log(` ${n.id}${n.description?` - ${n.description}`:``}`)}}export{f as registerEvalCommand,p as runEvalCommand};
1
+ import{n as e}from"../../chunks/paths-BYA-Yank.js";import{loadDevelopmentEnvironmentFiles as t}from"../../cli/dev/environment.js";import{a as n,n as r,t as i}from"../../chunks/client-BeZ_W7vl.js";import{n as a}from"../../chunks/host-B2D2qXsD.js";import{discoverAndImportSuites as o,discoverSuiteFiles as s,importSuiteFile as c}from"../runner/discover.js";import{executeSuite as l}from"../runner/execute-suite.js";import{ConsoleReporter as u}from"../runner/reporters/console.js";var d=n();function f(e,t){e.command(`eval`).description(`Run eval suites against an Ash agent.`).option(`--suite <id...>`,`Suite IDs to run (repeatable)`).option(`--all`,`Run all discovered suites`).option(`--url <url>`,`Remote agent URL (skip local host startup)`).option(`--timeout <ms>`,`Per-case timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent case executions per suite`).option(`--json`,`Output results as JSON`).option(`--list-suites`,`List discovered suites and exit`).option(`--skip-report`,`Skip suite-defined reporters (e.g. Braintrust)`).action(async e=>{await p(e,t)})}async function p(n,r){let i=e();if(t(i),n.listSuites){await y(i,r);return}let s=n.suite,c=await o(i,s);if(c.length===0){s&&s.length>0?r.error(`No suites found matching: ${s.join(`, `)}`):r.error(`No eval suites found. Create suite files under evals/ with the *.eval.ts extension.`),process.exitCode=1;return}let u,d;n.url?d={kind:`remote`,url:n.url}:(u=await a(i,{host:`127.0.0.1`,port:0}),d={kind:`local`,url:u.url});let f=m(d);try{let e=[];for(let t of c){let r=_(t,n),a=v(r,{json:n.json===!0,skipReport:n.skipReport===!0}),o=await l({suite:r,target:d,reporters:a,appRoot:i,client:f});e.push(o)}n.json&&r.log(JSON.stringify(e,null,2)),e.some(e=>e.errored>0)&&(process.exitCode=1)}finally{u&&await u.close()}process.exit(process.exitCode??0)}function m(e){if(e.kind===`local`)return new i({host:e.url});let t={},n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return n&&(t[r]=n),new i({auth:h(),headers:Object.keys(t).length>0?t:void 0,host:e.url})}function h(){let e=process.env.ASH_EVAL_AUTH_TOKEN?.trim();return e?{bearer:e}:{bearer:g}}async function g(){try{let e=(await(0,d.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{}return process.env.VERCEL_OIDC_TOKEN?.trim()??``}function _(e,t){let n=t.maxConcurrency?Number.parseInt(t.maxConcurrency,10):void 0,r=t.timeout?Number.parseInt(t.timeout,10):void 0;if(n===void 0&&r===void 0)return e;let i={...e};return n!==void 0&&(i.maxConcurrency=n),r!==void 0&&(i.timeoutMs=r),i}function v(e,t){let n=t.json?[]:[new u];return!t.skipReport&&e.reporters&&n.push(...e.reporters),n}async function y(e,t){let n=await s(e);if(n.length===0){t.log(`No eval suites found.`);return}t.log(`Found ${n.length} eval suite file(s):\n`);for(let r of n){let n=await c(e,r);t.log(` ${n.id}${n.description?` - ${n.description}`:``}`)}}export{f as registerEvalCommand,p as runEvalCommand};
@@ -13,7 +13,7 @@ import { createErrorId, createLogger } from "#internal/logging.js";
13
13
  import { createSubagentCalledEvent } from "#protocol/message.js";
14
14
  import { drainPendingConnectionAuthorizations } from "#runtime/framework-tools/connection-search.js";
15
15
  import { toErrorMessage } from "#shared/errors.js";
16
- import { isContinuousRuntimeNoActiveSessionError } from "#execution/continuous-runtime-errors.js";
16
+ import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
17
17
  import { registerContinuousSubagentInputRequestDispatcher, unregisterContinuousSubagentInputRequestDispatcher, } from "#execution/subagent-adapter.js";
18
18
  import { createExecutionNodeStep } from "#execution/node-step.js";
19
19
  import { emitProxiedInputRequest, routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
@@ -270,7 +270,7 @@ async function routeProxiedDeliverPayloads(input) {
270
270
  // between the HITL emission and the user's response. Treat
271
271
  // the deliver as a no-op — the response effectively falls
272
272
  // through to the parent as stale input.
273
- if (!isContinuousRuntimeNoActiveSessionError(error)) {
273
+ if (!isRuntimeNoActiveSessionError(error)) {
274
274
  throw error;
275
275
  }
276
276
  // Breadcrumb the drop so an operator chasing a "user
@@ -1,7 +1,7 @@
1
1
  import type { Runtime } from "#channel/types.js";
2
2
  import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
3
3
  import type { CreateRuntime } from "#execution/node-step.js";
4
- export { ContinuousRuntimeNoActiveSessionError, isContinuousRuntimeNoActiveSessionError, } from "#execution/continuous-runtime-errors.js";
4
+ export { RuntimeNoActiveSessionError, isRuntimeNoActiveSessionError, } from "#execution/runtime-errors.js";
5
5
  /**
6
6
  * Creates a {@link CreateRuntime} factory for the continuous
7
7
  * (non-durable) runtime.
@@ -5,9 +5,9 @@ import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
5
5
  import { BundleKey, ChannelKey, SessionIdKey } from "#context/keys.js";
6
6
  import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
7
7
  import { continuousEntry } from "#execution/continuous-entry.js";
8
- import { ContinuousRuntimeNoActiveSessionError } from "#execution/continuous-runtime-errors.js";
9
8
  import { buildRunContext } from "#execution/runtime-context.js";
10
- export { ContinuousRuntimeNoActiveSessionError, isContinuousRuntimeNoActiveSessionError, } from "#execution/continuous-runtime-errors.js";
9
+ import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
10
+ export { RuntimeNoActiveSessionError, isRuntimeNoActiveSessionError, } from "#execution/runtime-errors.js";
11
11
  /**
12
12
  * Creates a {@link CreateRuntime} factory for the continuous
13
13
  * (non-durable) runtime.
@@ -97,7 +97,7 @@ function buildContinuousRuntime(input) {
97
97
  async deliver(input) {
98
98
  const queue = queues.get(input.continuationToken);
99
99
  if (queue === undefined) {
100
- throw new ContinuousRuntimeNoActiveSessionError(input.continuationToken);
100
+ throw new RuntimeNoActiveSessionError(input.continuationToken);
101
101
  }
102
102
  queue.push({
103
103
  auth: input.auth,
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Thrown by a {@link Runtime}'s `deliver` when no in-flight session
3
+ * matches the continuation token. Callers using the resume-or-start
4
+ * pattern (e.g. {@link createSendFn}) treat this as the signal to start
5
+ * a fresh session.
6
+ */
7
+ export declare class RuntimeNoActiveSessionError extends Error {
8
+ readonly code: "NO_ACTIVE_SESSION";
9
+ readonly continuationToken: string;
10
+ constructor(continuationToken: string);
11
+ }
12
+ /** Type guard for {@link RuntimeNoActiveSessionError}. */
13
+ export declare function isRuntimeNoActiveSessionError(error: unknown): error is RuntimeNoActiveSessionError;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Thrown by a {@link Runtime}'s `deliver` when no in-flight session
3
+ * matches the continuation token. Callers using the resume-or-start
4
+ * pattern (e.g. {@link createSendFn}) treat this as the signal to start
5
+ * a fresh session.
6
+ */
7
+ export class RuntimeNoActiveSessionError extends Error {
8
+ code = "NO_ACTIVE_SESSION";
9
+ continuationToken;
10
+ constructor(continuationToken) {
11
+ super(`No active session for continuationToken "${continuationToken}".`);
12
+ this.name = "RuntimeNoActiveSessionError";
13
+ this.continuationToken = continuationToken;
14
+ }
15
+ }
16
+ /** Type guard for {@link RuntimeNoActiveSessionError}. */
17
+ export function isRuntimeNoActiveSessionError(error) {
18
+ return error instanceof RuntimeNoActiveSessionError;
19
+ }
@@ -1,8 +1,10 @@
1
+ import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
1
2
  import { getHookByToken, getRun, resumeHook, start } from "#compiled/@workflow/core/runtime.js";
2
3
  import { serializeContext } from "#context/serialize.js";
3
4
  import { resolveInstalledPackageInfo } from "#internal/application/package.js";
4
5
  import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
5
6
  import { buildRunContext } from "#execution/runtime-context.js";
7
+ import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
6
8
  const WORKFLOW_ENTRY_NAME = "workflowEntry";
7
9
  const ASH_PACKAGE_INFO = resolveInstalledPackageInfo();
8
10
  /**
@@ -48,9 +50,19 @@ export function createWorkflowRuntime(config) {
48
50
  kind: "deliver",
49
51
  payloads: [input.payload],
50
52
  };
51
- const hook = normalizeWorkflowHook(await getHookByToken(input.continuationToken));
52
- await resumeHook(input.continuationToken, hookPayload);
53
- return { sessionId: hook.runId };
53
+ try {
54
+ const hook = normalizeWorkflowHook(await getHookByToken(input.continuationToken));
55
+ await resumeHook(input.continuationToken, hookPayload);
56
+ return { sessionId: hook.runId };
57
+ }
58
+ catch (error) {
59
+ // Normalize the workflow-library "no hook" error so callers
60
+ // depend on the ash-owned class instead of `@workflow/errors`.
61
+ if (HookNotFoundError.is(error)) {
62
+ throw new RuntimeNoActiveSessionError(input.continuationToken);
63
+ }
64
+ throw error;
65
+ }
54
66
  },
55
67
  async getEventStream(sessionId, options) {
56
68
  return parseNdjsonStream(getRun(sessionId).getReadable({ startIndex: options?.startIndex }));
@@ -6,7 +6,7 @@ import { ASH_PACKAGE_NAME } from "#package-name.js";
6
6
  let cachedPackageInfo;
7
7
  // The package build stamps the published version into `dist` so bundled
8
8
  // deployments can still report package metadata without resolving package.json.
9
- const BUNDLED_FALLBACK_PACKAGE_VERSION = "0.16.0";
9
+ const BUNDLED_FALLBACK_PACKAGE_VERSION = "0.16.2";
10
10
  const BUNDLED_FALLBACK_PACKAGE_VERSION_PLACEHOLDER = "__ASH_PACKAGE_VERSION_PLACEHOLDER__";
11
11
  const WORKFLOW_MODULE_ALIASES = {
12
12
  "workflow/api": "src/compiled/@workflow/core/runtime.js",
@@ -27,11 +27,6 @@ interface ParsedBlockActionsPayload {
27
27
  readonly channelId: string;
28
28
  readonly threadTs: string;
29
29
  readonly teamId: string | undefined;
30
- /**
31
- * Slack actor that authored the click. Used to attribute the answered
32
- * card via `Answered by <@userId>` after a HITL response is delivered.
33
- */
34
- readonly userId: string | undefined;
35
30
  /**
36
31
  * The full block list off the clicked message. Preserved on the
37
32
  * answered-card update so the original prompt stays visible after the
@@ -29,30 +29,37 @@ export function parseBlockActionsPayload(body) {
29
29
  const actions = body.actions;
30
30
  if (!Array.isArray(actions))
31
31
  return null;
32
+ // `channel` and `message` are Optional on block_actions payloads — only
33
+ // present when the action was triggered from a message in a channel.
32
34
  const channel = body.channel?.id;
33
35
  const message = body.message;
34
36
  const threadTs = message?.thread_ts ?? message?.ts;
35
37
  if (!channel || !threadTs)
36
38
  return null;
39
+ // `team` is Required but can be `null` for org-installed apps.
40
+ // `user` is Required and always carries `id`.
37
41
  const team = body.team;
38
- const user = body.user;
39
- const teamId = team?.id ?? user?.team_id;
40
- const userId = typeof user?.id === "string" ? user.id : undefined;
41
- const messageTs = typeof message?.ts === "string" ? message.ts : undefined;
42
- const messageBlocks = Array.isArray(message?.blocks) ? message.blocks : [];
42
+ const userBlock = body.user;
43
+ const teamId = team?.id ?? userBlock.team_id;
44
+ const user = {
45
+ id: userBlock.id,
46
+ username: userBlock.username,
47
+ name: userBlock.name,
48
+ };
49
+ const messageBlocks = message?.blocks ?? [];
43
50
  return {
44
51
  actions: actions.map((a) => ({
45
52
  actionId: String(a.action_id ?? ""),
46
53
  value: a.value != null ? String(a.value) : undefined,
47
54
  blockId: a.block_id != null ? String(a.block_id) : undefined,
48
55
  selectedOptionValue: extractSelectedOptionValue(a),
49
- messageTs,
56
+ messageTs: message?.ts,
50
57
  label: extractActionLabel(a),
58
+ user,
51
59
  })),
52
60
  channelId: channel,
53
61
  threadTs,
54
62
  teamId,
55
- userId,
56
63
  messageBlocks,
57
64
  };
58
65
  }
@@ -130,7 +137,7 @@ export async function handleInteractionPost(rawBody, ctx, deps) {
130
137
  channelId: interaction.channelId,
131
138
  threadTs: interaction.threadTs,
132
139
  teamId: interaction.teamId ?? null,
133
- triggeringUserId: interaction.userId ?? null,
140
+ triggeringUserId: interaction.actions[0]?.user.id ?? null,
134
141
  },
135
142
  })
136
143
  .catch((error) => {
@@ -222,9 +229,11 @@ async function handleViewSubmission(payload, ctx, _deps) {
222
229
  const text = typeof raw === "string" ? raw : "";
223
230
  if (text.length === 0)
224
231
  return ack;
232
+ // `user` is Required on view_submission payloads; `team_id` is on the
233
+ // user object in modern payloads but not guaranteed in all examples.
225
234
  const user = payload.user;
226
- const triggeringUserId = typeof user?.id === "string" ? user.id : null;
227
- const teamId = typeof user?.team_id === "string" ? user.team_id : null;
235
+ const triggeringUserId = user.id;
236
+ const teamId = user.team_id ?? null;
228
237
  ctx.waitUntil(ctx
229
238
  .send({ inputResponses: [{ requestId: metadata.requestId, text }] }, {
230
239
  auth: null,
@@ -260,7 +269,7 @@ async function updateAnsweredHitlCard(interaction, deps) {
260
269
  const blocks = buildAnsweredBlocks({
261
270
  promptBlock: findPromptBlock(interaction.messageBlocks),
262
271
  answerLabel,
263
- userId: interaction.userId,
272
+ userId: hitlAction.user.id,
264
273
  });
265
274
  const token = await resolveSlackBotToken(deps.config.credentials?.botToken);
266
275
  const response = await fetch("https://slack.com/api/chat.update", {
@@ -117,6 +117,24 @@ export interface SlackInteractionAction {
117
117
  * the "answered" card without re-fetching the original request.
118
118
  */
119
119
  readonly label?: string;
120
+ /**
121
+ * Slack actor who triggered the interaction. Lets `onInteraction`
122
+ * handlers attribute resolutions back to the clicker (e.g. "Filed by
123
+ * <@U0123456789>") without re-parsing the raw payload. Always present
124
+ * — Slack requires `user` on every `block_actions` payload.
125
+ */
126
+ readonly user: SlackInteractionUser;
127
+ }
128
+ /**
129
+ * Slack actor surfaced on {@link SlackInteractionAction.user}. Mirrors
130
+ * `body.user` from the inbound `block_actions` payload.
131
+ */
132
+ export interface SlackInteractionUser {
133
+ readonly id: string;
134
+ /** Modern canonical display handle. */
135
+ readonly username?: string;
136
+ /** Legacy display handle, kept for older workspaces. */
137
+ readonly name?: string;
120
138
  }
121
139
  /**
122
140
  * Result of an `onAppMention` or `onDirectMessage` callback. Return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "experimental-ash",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "bin": {
5
5
  "ash": "./bin/ash.js",
6
6
  "experimental-ash": "./bin/ash.js"
@@ -1,28 +0,0 @@
1
- /**
2
- * Typed errors thrown by the continuous (in-memory) runtime.
3
- *
4
- * Kept in a separate module from `continuous-runtime.ts` so the
5
- * continuous entry body — which runs inside the runtime factory's
6
- * closure — can `instanceof`-check these errors without creating an
7
- * import cycle with the factory module.
8
- */
9
- /**
10
- * Thrown by the continuous runtime's `deliver` implementation when a
11
- * caller tries to deliver to a `continuationToken` that has no matching
12
- * in-flight run.
13
- *
14
- * Surfaced as a class so callers can discriminate this condition from
15
- * other failures without string-matching `error.message`. Stale HITL
16
- * responses routed to a finished descendant are the common cause.
17
- */
18
- export declare class ContinuousRuntimeNoActiveSessionError extends Error {
19
- readonly code: "NO_ACTIVE_SESSION";
20
- readonly continuationToken: string;
21
- constructor(continuationToken: string);
22
- }
23
- /**
24
- * Type guard for {@link ContinuousRuntimeNoActiveSessionError}. Prefer
25
- * this over `instanceof` at module boundaries so callers don't have to
26
- * import the class directly.
27
- */
28
- export declare function isContinuousRuntimeNoActiveSessionError(error: unknown): error is ContinuousRuntimeNoActiveSessionError;
@@ -1,34 +0,0 @@
1
- /**
2
- * Typed errors thrown by the continuous (in-memory) runtime.
3
- *
4
- * Kept in a separate module from `continuous-runtime.ts` so the
5
- * continuous entry body — which runs inside the runtime factory's
6
- * closure — can `instanceof`-check these errors without creating an
7
- * import cycle with the factory module.
8
- */
9
- /**
10
- * Thrown by the continuous runtime's `deliver` implementation when a
11
- * caller tries to deliver to a `continuationToken` that has no matching
12
- * in-flight run.
13
- *
14
- * Surfaced as a class so callers can discriminate this condition from
15
- * other failures without string-matching `error.message`. Stale HITL
16
- * responses routed to a finished descendant are the common cause.
17
- */
18
- export class ContinuousRuntimeNoActiveSessionError extends Error {
19
- code = "NO_ACTIVE_SESSION";
20
- continuationToken;
21
- constructor(continuationToken) {
22
- super(`No active session for continuationToken "${continuationToken}".`);
23
- this.name = "ContinuousRuntimeNoActiveSessionError";
24
- this.continuationToken = continuationToken;
25
- }
26
- }
27
- /**
28
- * Type guard for {@link ContinuousRuntimeNoActiveSessionError}. Prefer
29
- * this over `instanceof` at module boundaries so callers don't have to
30
- * import the class directly.
31
- */
32
- export function isContinuousRuntimeNoActiveSessionError(error) {
33
- return error instanceof ContinuousRuntimeNoActiveSessionError;
34
- }