experimental-ash 0.22.1 → 0.22.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # experimental-ash
2
2
 
3
+ ## 0.22.2
4
+
5
+ ### Patch Changes
6
+
7
+ - b81e154: feat(ash): support creating sandbox from existing snapshot source
8
+
3
9
  ## 0.22.1
4
10
 
5
11
  ### Patch Changes
@@ -300,6 +300,31 @@ The Vercel SDK forbids the `runtime` field when creating from a snapshot, so Ash
300
300
  from session-create calls. `runtime` only takes effect on the template create — the resulting
301
301
  snapshot then determines the runtime for every session derived from it.
302
302
 
303
+ ### Starting From a Pre-Built Snapshot (Vercel)
304
+
305
+ If you already maintain a Vercel Sandbox snapshot — for example, one your CI builds with your
306
+ dependencies preinstalled — pass it via `vercelBackend({ source })` to use as the base layer of
307
+ Ash's template:
308
+
309
+ ```ts
310
+ backend: vercelBackend({
311
+ source: { type: "snapshot", snapshotId: "snap_..." },
312
+ });
313
+ ```
314
+
315
+ The author-supplied `source` is honored **only** on the template create at prewarm time. Bootstrap,
316
+ seed files, and Ash's framework setup (workspace directory, ripgrep) still run on top, and every
317
+ session derives from the resulting Ash-owned snapshot. `source` is stripped from session-create
318
+ calls — sessions never start directly from an external snapshot.
319
+
320
+ Other `source` shapes accepted by the Vercel SDK (`{ type: "git", ... }`, `{ type: "tarball", ... }`)
321
+ also work and follow the same rules. When `source.type === "snapshot"`, the Vercel SDK forbids
322
+ `runtime`, and TypeScript enforces that at the factory call site.
323
+
324
+ Ash does not detect changes to an external snapshot. If you rebuild your snapshot and want Ash to
325
+ pick it up, force a template rebuild — for example, by changing the sandbox definition so its
326
+ template key changes.
327
+
303
328
  ### Deferring Backend Construction
304
329
 
305
330
  `SandboxDefinition.backend` also accepts a zero-arg callback that returns a backend. The callback
@@ -1,4 +1,4 @@
1
- import{o as e}from"./paths-DxgjK2PI.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-xQtl6kAD.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-C6sp4T2U.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-hz8p2jlZ.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-DxgjK2PI.js";import{a as o,i as s,n as c,r as l}from"./authored-module-loader-XcFLnl49.js";import{a as u,i as d,n as f,o as p,r as m,t as h}from"./package-DmsQgn4v.js";import{g,m as ee,p as te}from"./types-MZUhN0Zy.js";import{a as ne,c as re,n as ie,o as ae,r as oe,t as se}from"./prewarm-xQtl6kAD.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 w,realpath as fe,rename as T,rm as E,symlink as pe,writeFile as D}from"node:fs/promises";import{randomUUID as me}from"node:crypto";import{existsSync as he,readFileSync as ge}from"node:fs";import{fileURLToPath as _e}from"node:url";import{Buffer as ve}from"node:buffer";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";const Te=`ash-cache.json`;async function Ee(e){let t=await De(e),n=h().version;t!==null&&t===n||await E(e,{force:!0,recursive:!0})}async function O(e){await S(e,{recursive:!0}),await D(v(e,Te),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function De(e){try{let t=JSON.parse(await C(v(e,Te),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const Oe=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function ke(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await Ae(e.filename,e.source),n=Me(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${qe(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Je(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${je(e.source,t,n,r)}`,workflowManifest:i};let u=Le(e.source,a),d=e.mode===`workflow`?await Re(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-C6sp4T2U.js";import{a as o,i as s,n as c,r as l}from"./authored-module-loader-XcFLnl49.js";import{a as u,i as d,n as f,o as p,r as m,t as h}from"./package-DmsQgn4v.js";import{g,m as ee,p as te}from"./types-MZUhN0Zy.js";import{a as ne,c as re,n as ie,o as ae,r as oe,t as se}from"./prewarm-hz8p2jlZ.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 w,realpath as fe,rename as T,rm as E,symlink as pe,writeFile as D}from"node:fs/promises";import{randomUUID as me}from"node:crypto";import{existsSync as he,readFileSync as ge}from"node:fs";import{fileURLToPath as _e}from"node:url";import{Buffer as ve}from"node:buffer";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";const Te=`ash-cache.json`;async function Ee(e){let t=await De(e),n=h().version;t!==null&&t===n||await E(e,{force:!0,recursive:!0})}async function O(e){await S(e,{recursive:!0}),await D(v(e,Te),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function De(e){try{let t=JSON.parse(await C(v(e,Te),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const Oe=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function ke(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await Ae(e.filename,e.source),n=Me(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${qe(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Je(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${je(e.source,t,n,r)}`,workflowManifest:i};let u=Le(e.source,a),d=e.mode===`workflow`?await Re(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 Ae(e,t){let{parseAst:n}=await o();return n(t,{astType:`ts`,lang:Ke(e),range:!0,sourceType:`module`},e)}function je(e,t,n,r){let i=ze(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=Je(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 Me(e){let t=[];for(let n of e.body??[]){let e=Ne(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Fe(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Ie(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 Ne(e){return e.type===`FunctionDeclaration`?Pe(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Pe(e.declaration,!0,e)}function Pe(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 Fe(e){return e===void 0||Array.isArray(e)?e:e.body}function Ie(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 Le(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 Re(e,t){let n=await Ae(e,t),r=Ue(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=He(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:Ge(t,e.end),start:e.start,text:``})}return i.length>0?Le(t,i):t}function ze(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(Be)&&n.push(e.slice(r.start,r.end).trim());return n}function Be(e){return Ve(e.init)}function Ve(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`?Ve(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function He(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function Ue(e){let t=new Set;return k(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function k(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)We(e)&&k(e,t);else We(n)&&k(n,t)}}function We(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function Ge(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]===`
@@ -10,13 +10,56 @@ const workflowCode = \`${(e.code.endsWith(`
10
10
  `)?e.code:`${e.code}\n`).replace(/[\\`$]/g,`\\$&`)}\`;
11
11
 
12
12
  export const POST = workflowEntrypoint(workflowCode);`;if(!e.bundleFinalOutput){await St(e.outfile,t);return}let n=s(await l({cwd:e.workingDir,input:st,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[pt(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await St(e.outfile,n.code)}function vt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function yt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function bt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function xt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function I(e){for(let t of e)if(he(t))return{id:b(t)}}async function St(e,t){await S(_(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await D(n,t),await T(n,e)}function Ct(e,t){e.steps=L(e.steps,t.steps),e.workflows=L(e.workflows,t.workflows),e.classes=L(e.classes,t.classes)}function L(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function wt(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function Tt(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function R(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await D(n,t),await Et(n,e)}async function Et(e,t){if(process.platform!==`win32`){await T(e,t);return}for(let n=0;n<10;n+=1)try{await T(e,t);return}catch(e){if(!(e instanceof Error&&`code`in e&&(e.code===`EPERM`||e.code===`EACCES`||e.code===`EBUSY`))||n===9)throw e;await new Promise(e=>setTimeout(e,10*(n+1)))}}async function Dt(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=await kt({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=_(e.outfile),o=[`// Generated by Ash. Do not edit by hand.`,...Ot({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:z({outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,targetPath:e.builtinsPath}),outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,serdeOnlyFiles:r,stepFiles:t}),`export const __steps_registered = true;`,``].join(`
13
- `);return await S(a,{recursive:!0}),await Nt(e.outfile)!==o&&await D(e.outfile,o),i}function Ot(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function z(e){return e.preferAbsoluteFileImports?t(e.targetPath):Mt(e.outfileDirectory,e.targetPath)}async function kt(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await C(r,`utf8`);At(t,(await j(jt(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function At(e,t){e.steps=B(e.steps,t.steps),e.workflows=B(e.workflows,t.workflows),e.classes=B(e.classes,t.classes)}function B(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function jt(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function Mt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Nt(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const Pt=[`@mongodb-js/zstd`,`node-liblzma`],Ft=[`@chat-adapter/slack`,`chat`],It=[`ash/`,`.well-known/workflow/`];function Lt(e){let t={};return V(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Rt(e){await E(e,{force:!0,recursive:!0}),await S(e,{recursive:!0})}async function zt(e){try{return await fe(e.sourcePath)}catch{return await fe(e.fallbackPath)}}async function Bt(e){let t=await zt({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await Rt(e.targetPath),await x(t,e.targetPath,{dereference:!0,recursive:!0})}async function Vt(e){let t=v(e,`functions`),n=await Ht(t);n!==null&&await Ut(t,n),await Gt(t,t),await Kt(e)}async function Ht(e){let t=v(e,`__server.func`),n=v(e,`ash/__server.func`),r;try{r=await fe(t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let i=`${n}.ash-staging`;return await S(_(n),{recursive:!0}),await E(i,{force:!0,recursive:!0}),await x(r,i,{dereference:!0,recursive:!0}),await E(n,{force:!0,recursive:!0}),await T(i,n),n}async function Ut(e,t,n=e){let r;try{r=await w(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(r.map(async r=>{let i=v(e,r.name),a=H(y(n,i));if(r.isSymbolicLink()){r.name.endsWith(`.func`)&&qt(a)&&await Wt(i,t);return}r.isDirectory()&&!r.name.endsWith(`.func`)&&await Ut(i,t,n)}))}async function Wt(e,t){await E(e,{force:!0,recursive:!0}),await pe(H(y(_(e),t)),e,`dir`)}async function Gt(e,t){let n;try{n=await w(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let r=v(t,n.name),i=H(y(e,r));if(n.name.endsWith(`.func`)){qt(i)||await E(r,{force:!0,recursive:!0});return}n.isDirectory()&&await Gt(e,r)}))}async function Kt(e){let t=v(e,`config.json`),n;try{n=JSON.parse(await C(t,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!V(n)||!Array.isArray(n.routes)||(n.routes=n.routes.filter(Jt),await D(t,`${JSON.stringify(n,null,2)}\n`))}function H(e){return e.replaceAll(`\\`,`/`)}function qt(e){return It.some(t=>e.startsWith(t))}function Jt(e){if(!V(e)||`handle`in e)return!0;let t=typeof e.src==`string`?e.src:``,n=typeof e.dest==`string`?e.dest:``;return Yt(t)||Yt(n)}function Yt(e){return e.includes(`/ash/v1`)||e.includes(`/.well-known/workflow/`)}function Xt(e){let t=y(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function Zt(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
14
- `)}async function Qt(e){try{let t=JSON.parse(await C(v(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function $t(e){let t=await Qt(e.functionDirectoryPath),n=v(e.functionDirectoryPath,t),r=_(n),i=le(t),a=v(r,`__ash_nitro_handler__${i.length>0?i:`.mjs`}`),o=Xt({fromDirectoryPath:r,toFilePath:a});await T(n,a),await D(n,Zt({delegateImportPath:o,workflowRoutePath:e.workflowRoutePath}))}const en=new Map;var tn=class{#e;#t;config;#n=new WeakMap;constructor(e){this.config={buildTarget:`standalone`,dirs:[m(`src/execution`)],externalPackages:[...Pt,...Ft],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.compiledArtifactsBootstrapPath,this.#t=e.outDir}async build(e={}){let t=(en.get(this.#t)??Promise.resolve()).then(()=>this.#r(e));en.set(this.#t,t.catch(()=>{})),await t}async#r(e){await Ee(this.#t);let t=await this.#i();if(t.length===0)throw Error(`Expected the execution workflow source file under "${m(`src/execution`)}".`);let n=await this.findTsConfigPath();await S(this.#t,{recursive:!0});let r=await this.discoverEntries(t,this.#t,n),i=v(this.#t,`workflows.mjs`),{manifest:a}=await this.createWorkflowsBundle({discoveredEntries:r,keepInterimBundleContext:!1,outfile:i,bundleFinalOutput:!1,format:`esm`,inputFiles:t,tsconfigPath:n}),o=v(this.#t,`steps.mjs`),s=await Dt({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:o,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),c=e.nitroStepOutfile;c!==void 0&&c!==o&&await Dt({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:c,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),await nn(i,o),await rn(i),await an(i);let l=e.nitroWorkflowOutfile;l!==void 0&&l!==i&&(await S(_(l),{recursive:!0}),await fn(i,l),c!==void 0&&(await nn(l,c),await rn(l),await an(l))),await this.createManifest({workflowBundlePath:v(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...s.steps,...a.steps},workflows:{...s.workflows,...a.workflows},classes:{...s.classes,...a.classes}}}),await O(this.#t)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=v(e,t);try{return await C(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=_(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>b(this.config.workingDir,e));return(await Promise.all(e.map(e=>dt(e)))).flat()}async discoverEntries(e,t,n){let r=this.#n.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=Ze(await C(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#n.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:n=`cjs`,inputFiles:r,keepInterimBundleContext:i=this.config.watch,outfile:a,tsconfigPath:o}){let c=t??await this.discoverEntries(r,_(a),o),u=[...c.discoveredWorkflows].sort(),d=new Set(u),f=[...c.discoveredSerdeFiles].sort().filter(e=>!d.has(e)),p={},m=[...u.map(e=>ft(e,this.config.workingDir)),...f.map(e=>ft(e,this.config.workingDir))].join(`
15
- `);return await _t({bundleFinalOutput:e,code:s(await l({cwd:this.config.workingDir,input:st,platform:`neutral`,plugins:[pt(m),mt(),ht(this.config.workingDir,{workflowCondition:!0}),gt({manifest:p,projectRoot:this.transformProjectRoot,sideEffectFiles:[...u,...f],workingDir:this.config.workingDir})],resolve:{conditionNames:[`ash-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:o??!1,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${a}"`).code,format:n,outfile:a,workingDir:this.config.workingDir}),i?{bundleFinal:async t=>{await _t({bundleFinalOutput:e,code:t,format:n,outfile:a,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:p}:{manifest:p}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:vt(e.steps),workflows:yt(e.workflows),classes:bt(e.classes)},r=JSON.stringify(n,null,2);return await S(t,{recursive:!0}),await D(v(t,`manifest.json`),r),r}async buildVercelOutput(e){await this.build();let t=v(this.#t,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=v(t,`flow.func`),r=v(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),i=v(e.flowNitroOutputDir,`functions`,`__server.func`),a=v(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),o=v(r,`flow.func`),s=v(r,`step.func`),c=v(r,`webhook`,`[token].func`);await Bt({fallbackPath:i,sourcePath:a,targetPath:n}),await Promise.all([this.#a(n,{experimentalTriggers:Array.from([Ye]),maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),x(v(this.#t,`manifest.json`),v(t,`manifest.json`))]),await $t({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([E(o,{force:!0,recursive:!0}),E(s,{force:!0,recursive:!0}),E(c,{force:!0,recursive:!0})]),await S(r,{recursive:!0}),await Promise.all([x(n,o,{recursive:!0}),x(v(t,`manifest.json`),v(r,`manifest.json`))])}async#i(){return[...await this.getInputFiles(),this.#e]}async#a(e,t){let n=v(e,`.vc-config.json`),r=await this.#o(n),i={...r};i.environment=Lt(r.environment),t.runtime!==null&&(i.runtime=t.runtime),t.maxDuration!==void 0&&(i.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(i.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(i.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(i.experimentalTriggers=[...t.experimentalTriggers]),await D(n,`${JSON.stringify(i,null,2)}\n`)}async#o(e){try{let t=JSON.parse(await C(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function nn(e,t){let n=await U(e);if(n===null||n.includes(`__ashWorkflowStepsRegistered`))return;let r=un(_(e),t),i=[`import { __steps_registered as __ashWorkflowStepsRegistered } from ${JSON.stringify(r)};`,`void __ashWorkflowStepsRegistered;`,``].join(`
16
- `),a=n.match(/^import\s.+?;\n/m);if(a===null||a.index===void 0){await R(e,`${i}${n}`);return}let o=a.index+a[0].length;await R(e,`${n.slice(0,o)}${i}${n.slice(o)}`)}async function rn(e){let t=await U(e);if(t===null)return;let n=t;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let t=ln(u(e));n=cn(n,e,t)}n!==t&&await R(e,n)}async function an(e){let t=await U(e);if(t===null)return;let n=t.indexOf(`const workflowCode = `),r=t.lastIndexOf(`;
17
-
18
- export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)return;let i=n+21,a=t.slice(i,r);if(!a.trimStart().startsWith("`"))return;let o=sn(a,e),s=`${t.slice(0,i)}${on(o)}${t.slice(r)}`;s!==t&&await R(e,s)}function on(e){let t=ve.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function sn(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function cn(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function ln(e){return t(e)}function un(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function U(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function dn(e){try{return await C(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function fn(e,t){let n=await C(e),r=await dn(t);r!==null&&r.equals(n)||await R(t,n)}const pn=`\0ash-pruned-local-sandbox-backend`,mn=/[/\\]bindings[/\\]local\.js$/;function hn(){return{name:`ash-hosted-sandbox-backend-prune`,load(e){return e===pn?[`export function createLocalSandboxBackend() {`,` throw new Error("The local sandbox backend is pruned from hosted server bundles.");`,`}`,``].join(`
19
- `):null},resolveId(e){return mn.test(e)?pn:null}}}const gn=`${g}/runs`,_n=`${g}/runs/:runId`,vn=`${g}/runs/:runId/steps`,yn=`${g}/runs/:runId/events`;function bn(e){return e===`all`||e===`app`}function xn(e){return W(e)}function W(e){return e===`all`||e===`flow`}function G(e,t){let r=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,i=n(t.handlerPath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import handler from ${i};`,`export default handler;`].join(`
20
- `)}function K(e){return v(e.options.buildDir,`workflow`)}function Sn(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Cn(e,t){let n=v(K(e),`${t.bundleName}-handler.mjs`),r=_(n),i=Sn(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=Sn(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await D(n,wn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function wn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = await __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
21
- `)}function Tn(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 En(e,n,r){if(xn(r.surface)){let t=f(),i=new tn({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:W(r.surface)?v(K(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&W(r.surface)?v(K(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});bn(r.surface)&&(G(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),G(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),Tn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:gn}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:_n}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:vn}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:yn}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=K(e),o=W(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 Cn(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function Dn(){return`${g}/cron/${me()}`}function On(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=Dn())}function kn(e){return{plugins:[c(),...e]}}function An(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 jn=`@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 Mn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const Nn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],Pn=Symbol(`ash.workflow-transform-patched`),Fn=[`@napi-rs/keyring`];function In(){let e={};for(let t of Nn)e[t]=u(t);return e}function Ln(e){if(!e&&process.env.VERCEL)return`vercel`}function Rn(e){return e===`all`||e===`app`}function zn(e){return e===`all`||e===`flow`}function Bn(e){return zn(e)}function Vn(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Hn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Fn,...jn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function q(e){return e.replaceAll(`\\`,`/`)}function Un(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 Wn(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function J(e,t){return t.startsWith(`file://`)?q(Wn(Un(_e(t)))):ue(t)?q(Wn(Un(t))):q(Wn(Un(b(e,t))))}function Gn(e,t){let n=q(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function Kn(e){let t=q(e);return process.platform===`win32`?t.toLowerCase():t}function qn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function Y(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?J(n===void 0?e:_(J(e,n)),t):null}async function Jn(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of qn(n)){let n=Y(t,i,e);n!==null&&r.add(Kn(n))}return r}async function Yn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Jn(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 Xn(e,t){let n=q(e).replace(/\/$/,``),r=q(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function Zn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>J(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=Y(e.options.rootDir,t,r)??J(e.options.rootDir,t);return n.some(e=>Gn(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Qn(e,t){let n=null,r=async()=>(n===null&&(n=await Jn(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=Y(e.options.rootDir,t,n);return i===null||!(await r()).has(Kn(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function $n(e,t){let n=null,r=async()=>(n===null&&(n=await Jn(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=J(e.options.rootDir,n);return i.has(Kn(a))?{code:(await j(Xn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function er(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return q(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function tr(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[Pn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return Gn(t,n)?null:r.call(this,e,t,...i)},t[Pn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Rn(r)&&e.scheduleRegistrations.length>0,o=Ln(t),s=o===`vercel`?hn():null,c=s===null?[]:[s],l=kn(c),u=kn(c),f=Hn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Ee(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:Bn(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:Mn(o===`vercel`&&Rn(r))},t?{watch:!0}:void 0);if(await O(p),An(g),zn(r)){let t=In();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Zn(g,e.workflowBuildDir),tr(g,e.workflowBuildDir)}if(Bn(r)){let t=Vn(g,e);Qn(g,{stepEntrypointPath:t}),$n(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&er(g,e.compiledArtifacts.instrumentationSourcePath),t&&zn(r)){let t=e.workflowBuildDir,n=new Set([q(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(q(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(On(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 En(g,e,{surface:r}),Bn(r)&&await Yn(g,Vn(g,e)),g}function nr(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 rr(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?or(t.instructions):null,schedules:t.schedules.map(sr),tools:t.tools.map(cr),skills:t.skills.map(lr),connections:t.connections.map(ur),channels:t.channels.filter(ar).map(dr),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(fr),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function ir(e){let t=rr({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await D(n,`${JSON.stringify(t,null,2)}\n`),n}function ar(e){return e.kind===`channel`}function or(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function sr(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function cr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function lr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function ur(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 dr(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:nr(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function fr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function pr(){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 mr(e){return pr()?(await se(e),!0):!1}function hr(e){return e.replace(/[\\/]+$/,``)}function gr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _r(e,t){return typeof t!=`string`||t.trim().length===0?null:b(e,t)}function vr(e){if(!gr(e.config)||!gr(e.config.experimentalServices))return!1;let t=!1,n=!1;for(let r of Object.values(e.config.experimentalServices)){if(!gr(r))continue;if(r.framework===`nextjs`){t=!0;continue}if(r.framework!==`ash`)continue;let i=_r(e.configRoot,r.entrypoint),a=typeof r.routePrefix==`string`?r.routePrefix.trim():``;i===e.appRoot&&a.length>0&&a!==`/`&&(n=!0)}return t&&n}async function yr(e){let t=e;for(;;){try{let n=v(t,`vercel.json`),r=JSON.parse(await C(n,`utf8`));if(vr({appRoot:e,configRoot:t,config:r}))return!0}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let n=_(t);if(n===t)return!1;t=n}}async function br(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function xr(e){let t=new tn({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await br(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function Sr(e){let t=hr(e.options.output.dir);return await Ee(t),await Ce(e),await be(e),await we(e),await ye(e),await O(t),t}async function Cr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await Sr(n)}finally{await n.close()}}async function wr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await Sr(e);return await ir({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await Sr(n);await mr({appRoot:t.appRoot,log(e){console.log(e)}});let r=await Cr(t,`flow`);return await xr({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await yr(t.appRoot)&&await Vt(e),await ir({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,Tr=new Set([`[::]`,`::`,`0.0.0.0`]);function Er(e){let t=new URL(e);return Tr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function Dr(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function 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 kr(){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 Ar(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 jr(e){let t=process.env[Q],n=process.env[$],r=new URL(Er(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 Mr(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function Nr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=Mr(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function Pr(e){let t=Ar({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!Dr(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function Fr(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);Nr(a);let o=t.host??i.options.devServer.hostname,s=t.port??kr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await Pr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=jr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-Bj0TDis0.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:Er(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var Ir=e({buildHost:()=>Lr,startHost:()=>Rr});async function Lr(e){return await wr(e)}async function Rr(e,t={}){return await Fr(e,t)}export{Rr as n,Ir as t};
13
+ `);return await S(a,{recursive:!0}),await Nt(e.outfile)!==o&&await D(e.outfile,o),i}function Ot(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function z(e){return e.preferAbsoluteFileImports?t(e.targetPath):Mt(e.outfileDirectory,e.targetPath)}async function kt(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await C(r,`utf8`);At(t,(await j(jt(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function At(e,t){e.steps=B(e.steps,t.steps),e.workflows=B(e.workflows,t.workflows),e.classes=B(e.classes,t.classes)}function B(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function jt(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function Mt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Nt(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const Pt=`index.__ash_service_route_prefix.mjs`,Ft=[`ash/`,`.well-known/workflow/`];function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function It(e){return Ft.some(t=>e.startsWith(t))}function Lt(e,t){return e.filter(Rt).map(e=>Bt(e,t))}function Rt(e){if(!V(e)||`handle`in e)return!0;let t=typeof e.src==`string`?e.src:``,n=typeof e.dest==`string`?e.dest:``;return H(t)||H(n)}function H(e){return e.includes(`/ash/v1`)||e.includes(`/.well-known/workflow/`)}function zt(e){return e.includes(`/ash/v1`)}function Bt(e,t){if(!V(e)||`handle`in e||typeof e.src!=`string`)return e;let n=zt(e.src)||typeof e.dest==`string`&&zt(e.dest),r={...e,src:Vt(e.src,t)};return n&&(r.dest=`/ash/__server`),r}function Vt(e,t){if(t===void 0||t===`/`||!H(e)||e.includes(t))return e;let n=t.endsWith(`/`)?t.slice(0,-1):t,r=n.replaceAll(`/`,`\\/`);return e.includes(r)?e:e.startsWith(`^(?:/`)?`^(?:${n}${e.slice(4)}`:e.startsWith(`^/`)?`^${n}${e.slice(1)}`:e.startsWith(`/`)?`${n}${e}`:e}async function Ht(e,t){let n=v(e,`.vc-config.json`),r=v(e,Pt),i=JSON.parse(await C(n,`utf8`)),a=V(i)?i:{};await D(r,Ut(t)),await D(n,`${JSON.stringify({...a,handler:Pt},null,2)}\n`)}function Ut(e){return`
14
+ import { Server } from "node:http";
15
+
16
+ const SERVICE_PREFIX = ${JSON.stringify(Wt(e))};
17
+ const PATCH_SYMBOL = Symbol.for("ash.service.route-prefix-strip.patch");
18
+
19
+ function stripServiceRoutePrefix(requestUrl) {
20
+ if (typeof requestUrl !== "string" || requestUrl === "*") {
21
+ return requestUrl;
22
+ }
23
+
24
+ const queryIndex = requestUrl.indexOf("?");
25
+ const rawPath = queryIndex === -1 ? requestUrl : requestUrl.slice(0, queryIndex);
26
+ const query = queryIndex === -1 ? "" : requestUrl.slice(queryIndex);
27
+ const path = rawPath.startsWith("/") ? rawPath : \`/\${rawPath}\`;
28
+
29
+ if (path === SERVICE_PREFIX) {
30
+ return \`/\${query}\`;
31
+ }
32
+
33
+ if (path.startsWith(\`\${SERVICE_PREFIX}/\`)) {
34
+ return path.slice(SERVICE_PREFIX.length) + query;
35
+ }
36
+
37
+ return path + query;
38
+ }
39
+
40
+ if (!globalThis[PATCH_SYMBOL]) {
41
+ globalThis[PATCH_SYMBOL] = true;
42
+ const originalEmit = Server.prototype.emit;
43
+ Server.prototype.emit = function patchedEmit(event, request, ...args) {
44
+ if (event === "request" && request && typeof request.url === "string") {
45
+ request.url = stripServiceRoutePrefix(request.url);
46
+ }
47
+
48
+ return originalEmit.call(this, event, request, ...args);
49
+ };
50
+ }
51
+
52
+ const originalModule = await import("./index.mjs");
53
+ const entrypoint = originalModule?.default ?? originalModule;
54
+
55
+ export default entrypoint;
56
+ `.trimStart()}function Wt(e){let t=(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``);return t.length===0?`/`:t}const Gt=[`@mongodb-js/zstd`,`node-liblzma`],Kt=[`@chat-adapter/slack`,`chat`];function qt(e){let t={};return Jt(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function Jt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Yt(e){await E(e,{force:!0,recursive:!0}),await S(e,{recursive:!0})}async function Xt(e){try{return await fe(e.sourcePath)}catch{return await fe(e.fallbackPath)}}async function Zt(e){let t=await Xt({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await Yt(e.targetPath),await x(t,e.targetPath,{dereference:!0,recursive:!0})}async function Qt(e,t={}){let n=v(e,`functions`),r=await $t(n);r!==null&&(t.servicePrefix!==void 0&&await Ht(r,t.servicePrefix),await en(n,r)),await nn(n,n),await rn(e,t.servicePrefix)}async function $t(e){let t=v(e,`__server.func`),n=v(e,`ash/__server.func`),r;try{r=await fe(t)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}let i=`${n}.ash-staging`;return await S(_(n),{recursive:!0}),await E(i,{force:!0,recursive:!0}),await x(r,i,{dereference:!0,recursive:!0}),await E(n,{force:!0,recursive:!0}),await T(i,n),n}async function en(e,t,n=e){let r;try{r=await w(e,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(r.map(async r=>{let i=v(e,r.name),a=U(y(n,i));if(r.isSymbolicLink()){r.name.endsWith(`.func`)&&It(a)&&await tn(i,t);return}r.isDirectory()&&!r.name.endsWith(`.func`)&&await en(i,t,n)}))}async function tn(e,t){await E(e,{force:!0,recursive:!0}),await pe(U(y(_(e),t)),e,`dir`)}async function nn(e,t){let n;try{n=await w(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}await Promise.all(n.map(async n=>{let r=v(t,n.name),i=U(y(e,r));if(n.name.endsWith(`.func`)){It(i)||await E(r,{force:!0,recursive:!0});return}n.isDirectory()&&await nn(e,r)}))}async function rn(e,t){let n=v(e,`config.json`),r;try{r=JSON.parse(await C(n,`utf8`))}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}!Jt(r)||!Array.isArray(r.routes)||(r.routes=Lt(r.routes,t),await D(n,`${JSON.stringify(r,null,2)}\n`))}function U(e){return e.replaceAll(`\\`,`/`)}function an(e){let t=y(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function on(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
57
+ `)}async function sn(e){try{let t=JSON.parse(await C(v(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function cn(e){let t=await sn(e.functionDirectoryPath),n=v(e.functionDirectoryPath,t),r=_(n),i=le(t),a=v(r,`__ash_nitro_handler__${i.length>0?i:`.mjs`}`),o=an({fromDirectoryPath:r,toFilePath:a});await T(n,a),await D(n,on({delegateImportPath:o,workflowRoutePath:e.workflowRoutePath}))}const ln=new Map;var un=class{#e;#t;config;#n=new WeakMap;constructor(e){this.config={buildTarget:`standalone`,dirs:[m(`src/execution`)],externalPackages:[...Gt,...Kt],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.compiledArtifactsBootstrapPath,this.#t=e.outDir}async build(e={}){let t=(ln.get(this.#t)??Promise.resolve()).then(()=>this.#r(e));ln.set(this.#t,t.catch(()=>{})),await t}async#r(e){await Ee(this.#t);let t=await this.#i();if(t.length===0)throw Error(`Expected the execution workflow source file under "${m(`src/execution`)}".`);let n=await this.findTsConfigPath();await S(this.#t,{recursive:!0});let r=await this.discoverEntries(t,this.#t,n),i=v(this.#t,`workflows.mjs`),{manifest:a}=await this.createWorkflowsBundle({discoveredEntries:r,keepInterimBundleContext:!1,outfile:i,bundleFinalOutput:!1,format:`esm`,inputFiles:t,tsconfigPath:n}),o=v(this.#t,`steps.mjs`),s=await Dt({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:o,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),c=e.nitroStepOutfile;c!==void 0&&c!==o&&await Dt({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:c,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),await dn(i,o),await fn(i),await pn(i);let l=e.nitroWorkflowOutfile;l!==void 0&&l!==i&&(await S(_(l),{recursive:!0}),await xn(i,l),c!==void 0&&(await dn(l,c),await fn(l),await pn(l))),await this.createManifest({workflowBundlePath:v(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...s.steps,...a.steps},workflows:{...s.workflows,...a.workflows},classes:{...s.classes,...a.classes}}}),await O(this.#t)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=v(e,t);try{return await C(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=_(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>b(this.config.workingDir,e));return(await Promise.all(e.map(e=>dt(e)))).flat()}async discoverEntries(e,t,n){let r=this.#n.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=Ze(await C(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#n.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:n=`cjs`,inputFiles:r,keepInterimBundleContext:i=this.config.watch,outfile:a,tsconfigPath:o}){let c=t??await this.discoverEntries(r,_(a),o),u=[...c.discoveredWorkflows].sort(),d=new Set(u),f=[...c.discoveredSerdeFiles].sort().filter(e=>!d.has(e)),p={},m=[...u.map(e=>ft(e,this.config.workingDir)),...f.map(e=>ft(e,this.config.workingDir))].join(`
58
+ `);return await _t({bundleFinalOutput:e,code:s(await l({cwd:this.config.workingDir,input:st,platform:`neutral`,plugins:[pt(m),mt(),ht(this.config.workingDir,{workflowCondition:!0}),gt({manifest:p,projectRoot:this.transformProjectRoot,sideEffectFiles:[...u,...f],workingDir:this.config.workingDir})],resolve:{conditionNames:[`ash-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:o??!1,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${a}"`).code,format:n,outfile:a,workingDir:this.config.workingDir}),i?{bundleFinal:async t=>{await _t({bundleFinalOutput:e,code:t,format:n,outfile:a,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:p}:{manifest:p}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:vt(e.steps),workflows:yt(e.workflows),classes:bt(e.classes)},r=JSON.stringify(n,null,2);return await S(t,{recursive:!0}),await D(v(t,`manifest.json`),r),r}async buildVercelOutput(e){await this.build();let t=v(this.#t,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=v(t,`flow.func`),r=v(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),i=v(e.flowNitroOutputDir,`functions`,`__server.func`),a=v(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),o=v(r,`flow.func`),s=v(r,`step.func`),c=v(r,`webhook`,`[token].func`);await Zt({fallbackPath:i,sourcePath:a,targetPath:n}),await Promise.all([this.#a(n,{experimentalTriggers:Array.from([Ye]),maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),x(v(this.#t,`manifest.json`),v(t,`manifest.json`))]),await cn({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([E(o,{force:!0,recursive:!0}),E(s,{force:!0,recursive:!0}),E(c,{force:!0,recursive:!0})]),await S(r,{recursive:!0}),await Promise.all([x(n,o,{recursive:!0}),x(v(t,`manifest.json`),v(r,`manifest.json`))])}async#i(){return[...await this.getInputFiles(),this.#e]}async#a(e,t){let n=v(e,`.vc-config.json`),r=await this.#o(n),i={...r};i.environment=qt(r.environment),t.runtime!==null&&(i.runtime=t.runtime),t.maxDuration!==void 0&&(i.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(i.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(i.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(i.experimentalTriggers=[...t.experimentalTriggers]),await D(n,`${JSON.stringify(i,null,2)}\n`)}async#o(e){try{let t=JSON.parse(await C(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function dn(e,t){let n=await yn(e);if(n===null||n.includes(`__ashWorkflowStepsRegistered`))return;let r=vn(_(e),t),i=[`import { __steps_registered as __ashWorkflowStepsRegistered } from ${JSON.stringify(r)};`,`void __ashWorkflowStepsRegistered;`,``].join(`
59
+ `),a=n.match(/^import\s.+?;\n/m);if(a===null||a.index===void 0){await R(e,`${i}${n}`);return}let o=a.index+a[0].length;await R(e,`${n.slice(0,o)}${i}${n.slice(o)}`)}async function fn(e){let t=await yn(e);if(t===null)return;let n=t;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let t=_n(u(e));n=gn(n,e,t)}n!==t&&await R(e,n)}async function pn(e){let t=await yn(e);if(t===null)return;let n=t.indexOf(`const workflowCode = `),r=t.lastIndexOf(`;
60
+
61
+ export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)return;let i=n+21,a=t.slice(i,r);if(!a.trimStart().startsWith("`"))return;let o=hn(a,e),s=`${t.slice(0,i)}${mn(o)}${t.slice(r)}`;s!==t&&await R(e,s)}function mn(e){let t=ve.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function hn(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function gn(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function _n(e){return t(e)}function vn(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function yn(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function bn(e){try{return await C(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function xn(e,t){let n=await C(e),r=await bn(t);r!==null&&r.equals(n)||await R(t,n)}const Sn=`\0ash-pruned-local-sandbox-backend`,Cn=/[/\\]bindings[/\\]local\.js$/;function wn(){return{name:`ash-hosted-sandbox-backend-prune`,load(e){return e===Sn?[`export function createLocalSandboxBackend() {`,` throw new Error("The local sandbox backend is pruned from hosted server bundles.");`,`}`,``].join(`
62
+ `):null},resolveId(e){return Cn.test(e)?Sn:null}}}const Tn=`${g}/runs`,En=`${g}/runs/:runId`,Dn=`${g}/runs/:runId/steps`,On=`${g}/runs/:runId/events`;function kn(e){return e===`all`||e===`app`}function An(e){return W(e)}function W(e){return e===`all`||e===`flow`}function G(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(`
63
+ `)}function K(e){return v(e.options.buildDir,`workflow`)}function jn(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Mn(e,t){let n=v(K(e),`${t.bundleName}-handler.mjs`),r=_(n),i=jn(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=jn(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await D(n,Nn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function Nn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = await __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
64
+ `)}function Pn(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(`
65
+ `)}async function Fn(e,n,r){if(An(r.surface)){let t=f(),i=new un({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:W(r.surface)?v(K(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&W(r.surface)?v(K(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});kn(r.surface)&&(G(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),G(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),Pn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:Tn}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:En}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:Dn}),G(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:On}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=K(e),o=W(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 Mn(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function In(){return`${g}/cron/${me()}`}function Ln(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=In())}function Rn(e){return{plugins:[c(),...e]}}function zn(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 Bn=`@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 Vn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const Hn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],Un=Symbol(`ash.workflow-transform-patched`),Wn=[`@napi-rs/keyring`];function Gn(){let e={};for(let t of Hn)e[t]=u(t);return e}function Kn(e){if(!e&&process.env.VERCEL)return`vercel`}function qn(e){return e===`all`||e===`app`}function Jn(e){return e===`all`||e===`flow`}function Yn(e){return Jn(e)}function Xn(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Zn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Wn,...Bn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function q(e){return e.replaceAll(`\\`,`/`)}function Qn(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 $n(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function J(e,t){return t.startsWith(`file://`)?q($n(Qn(_e(t)))):ue(t)?q($n(Qn(t))):q($n(Qn(b(e,t))))}function er(e,t){let n=q(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function tr(e){let t=q(e);return process.platform===`win32`?t.toLowerCase():t}function nr(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 rr(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?J(n===void 0?e:_(J(e,n)),t):null}async function ir(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of nr(n)){let n=rr(t,i,e);n!==null&&r.add(tr(n))}return r}async function ar(e,t){if(e.options.noExternals===!0)return;let n;try{n=await ir(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 or(e,t){let n=q(e).replace(/\/$/,``),r=q(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function sr(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>J(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=rr(e.options.rootDir,t,r)??J(e.options.rootDir,t);return n.some(e=>er(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function cr(e,t){let n=null,r=async()=>(n===null&&(n=await ir(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=rr(e.options.rootDir,t,n);return i===null||!(await r()).has(tr(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function lr(e,t){let n=null,r=async()=>(n===null&&(n=await ir(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=J(e.options.rootDir,n);return i.has(tr(a))?{code:(await j(or(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function ur(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return q(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function dr(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[Un]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return er(t,n)?null:r.call(this,e,t,...i)},t[Un]=!0}})}async function Y(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&qn(r)&&e.scheduleRegistrations.length>0,o=Kn(t),s=o===`vercel`?wn():null,c=s===null?[]:[s],l=Rn(c),u=Rn(c),f=Zn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Ee(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:Yn(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:Vn(o===`vercel`&&qn(r))},t?{watch:!0}:void 0);if(await O(p),zn(g),Jn(r)){let t=Gn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;sr(g,e.workflowBuildDir),dr(g,e.workflowBuildDir)}if(Yn(r)){let t=Xn(g,e);cr(g,{stepEntrypointPath:t}),lr(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&ur(g,e.compiledArtifacts.instrumentationSourcePath),t&&Jn(r)){let t=e.workflowBuildDir,n=new Set([q(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(q(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(Ln(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 Fn(g,e,{surface:r}),Yn(r)&&await ar(g,Xn(g,e)),g}function fr(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 pr(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?gr(t.instructions):null,schedules:t.schedules.map(_r),tools:t.tools.map(vr),skills:t.skills.map(yr),connections:t.connections.map(br),channels:t.channels.filter(hr).map(xr),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Sr),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function mr(e){let t=pr({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await D(n,`${JSON.stringify(t,null,2)}\n`),n}function hr(e){return e.kind===`channel`}function gr(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function _r(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function vr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function yr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function br(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 xr(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:fr(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Sr(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Cr(){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 wr(e){return Cr()?(await se(e),!0):!1}function Tr(e){return e.replace(/[\\/]+$/,``)}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Er(e,t){return typeof t!=`string`||t.trim().length===0?null:b(e,t)}function Dr(e){if(!X(e.config)||!X(e.config.experimentalServices))return;let t=!1,n;for(let r of Object.values(e.config.experimentalServices)){if(!X(r))continue;if(r.framework===`nextjs`){t=!0;continue}if(r.framework!==`ash`)continue;let i=Er(e.configRoot,r.entrypoint),a=typeof r.routePrefix==`string`?r.routePrefix.trim():``;i===e.appRoot&&a.length>0&&a!==`/`&&(n=a)}return t?n:void 0}async function Or(e){let t=e;for(;;){try{let n=v(t,`vercel.json`),r=JSON.parse(await C(n,`utf8`)),i=Dr({appRoot:e,configRoot:t,config:r});if(i!==void 0)return i}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let n=_(t);if(n===t)return;t=n}}async function kr(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function Ar(e){let t=new un({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await kr(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function jr(e){let t=Tr(e.options.output.dir);return await Ee(t),await Ce(e),await be(e),await we(e),await ye(e),await O(t),t}async function Mr(e,t){let n=await Y(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await jr(n)}finally{await n.close()}}async function Nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await Y(t,!1);try{let n=await jr(e);return await mr({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await Y(t,!1,{surface:`app`});try{let e=await jr(n);await wr({appRoot:t.appRoot,log(e){console.log(e)}});let r=await Mr(t,`flow`);await Ar({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir});let i=await Or(t.appRoot);return i!==void 0&&await Qt(e,{servicePrefix:i}),await mr({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,Pr=new Set([`[::]`,`::`,`0.0.0.0`]);function Fr(e){let t=new URL(e);return Pr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function Ir(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function Lr(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 Rr(){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 zr(e){let t=Lr(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 Br(e){let t=process.env[Q],n=process.env[$],r=new URL(Fr(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 Vr(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function Hr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=Vr(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function Ur(e){let t=zr({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(()=>{}),!Ir(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 Wr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await Y(r,!0,{schedules:n}),a=xe(i);Hr(a);let o=t.host??i.options.devServer.hostname,s=t.port??Rr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await Ur({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=Br(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-BLzYWh05.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:Fr(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var Gr=e({buildHost:()=>Kr,startHost:()=>qr});async function Kr(e){return await Nr(e)}async function qr(e,t={}){return await Wr(e,t)}export{qr as n,Gr as t};
@@ -62,7 +62,7 @@ A single tool or subagent call runs as one serial action. If you call multiple i
62
62
  <p>You can close this tab and return to your app.</p>
63
63
  </main>
64
64
  </body>
65
- </html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const sc=[`GET`,`POST`];function cc(){return sc.map(e=>uc(e))}function lc(){return new Set(sc.map(dc))}function uc(e){let t=dc(e);return{name:t,method:e,urlPath:se,fetch:fc,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function dc(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function fc(e,t){let n=t.params.name,r=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing connection name.`,ok:!1},{status:400});if(typeof r!=`string`||r.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let i=await pc(e);try{await De(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return oc()}async function pc(e){let t={};e.headers.forEach((e,n)=>{t[n]=e});let n=``;if(e.method!==`GET`&&e.method!==`HEAD`)try{n=await e.text()}catch{n=``}return{body:n,headers:t,method:e.method,url:e.url}}function mc(){let e=Xs({auth:gc()}),t=[];for(let n of e.routes)t.push({name:`ash`,method:n.method.toUpperCase(),urlPath:n.path,fetch:async(e,t)=>n.handler(e,t),handler:n.handler,adapter:e.adapter,logicalPath:`framework://channels/${n.path}`,sourceId:`ash:framework:${n.method.toLowerCase()}-${n.path}`,sourceKind:`module`});return t.push(...cc()),t}function hc(){return new Set([`ash`,...lc()])}function gc(){return process.env.VERCEL?Ms():As()}const _c=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:vc,...yc}=y.toJSONSchema(_c),bc={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:yc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function q(){let e=V().get(hd);if(e===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current runtime context.`);return t}function xc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function Sc(e){return wc(e,`head`)}function Cc(e){return wc(e,`tail`)}function wc(e,t){let n=e.split(`
65
+ </html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const sc=[`GET`,`POST`];function cc(){return sc.map(e=>uc(e))}function lc(){return new Set(sc.map(dc))}function uc(e){let t=dc(e);return{name:t,method:e,urlPath:se,fetch:fc,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function dc(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function fc(e,t){let n=t.params.name,r=t.params.token;if(typeof n!=`string`||n.length===0)return Response.json({error:`Missing connection name.`,ok:!1},{status:400});if(typeof r!=`string`||r.length===0)return Response.json({error:`Missing callback token.`,ok:!1},{status:400});let i=await pc(e);try{await De(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return oc()}async function pc(e){let t={};e.headers.forEach((e,n)=>{t[n]=e});let n=``;if(e.method!==`GET`&&e.method!==`HEAD`)try{n=await e.text()}catch{n=``}return{body:n,headers:t,method:e.method,url:e.url}}function mc(){let e=Xs({auth:gc()}),t=[];for(let n of e.routes)t.push({name:`ash`,method:n.method.toUpperCase(),urlPath:n.path,fetch:async(e,t)=>n.handler(e,t),handler:n.handler,adapter:e.adapter,logicalPath:`framework://channels/${n.path}`,sourceId:`ash:framework:${n.method.toLowerCase()}-${n.path}`,sourceKind:`module`});return t.push(...cc()),t}function hc(){return new Set([`ash`,...lc()])}function gc(){return process.env.VERCEL?Ms():As()}const _c=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:vc,...yc}=y.toJSONSchema(_c),bc={description:`Ask the user a question and wait for their response before continuing. Use this when you need clarification or a choice from the user.`,inputSchema:yc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function q(){let e=V().get(gd);if(e===void 0)throw Error(`This tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current runtime context.`);return t}function xc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function Sc(e){return wc(e,`head`)}function Cc(e){return wc(e,`tail`)}function wc(e,t){let n=e.split(`
66
66
  `),r=Ec(n),i=t===`head`,a=[],o=0,s=i?0:n.length-1,c=i?1:-1;for(let e=s;e>=0&&e<n.length&&a.length<2e3;e+=c){let t=Tc(n[e]??``),r=Buffer.byteLength(t,`utf8`)+1;if(o+r>51200&&a.length>0)break;a.push(t),o+=r}return i||a.reverse(),{output:a.join(`
67
67
  `),outputLines:a.length,totalLines:r,truncated:a.length<r}}function Tc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function Ec(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function Dc(e){let t=await(await q()).runCommand({command:e.command}),n=Cc(t.stdout),r=Cc(t.stderr),i=n.truncated||r.truncated,a=n.output;n.truncated&&(a=`[stdout truncated: showing last ${n.outputLines} of ${n.totalLines} lines]\n`+a);let o=r.output;return r.truncated&&(o=`[stderr truncated: showing last ${r.outputLines} of ${r.totalLines} lines]\n`+o),{exitCode:t.exitCode,stderr:o,stdout:a,truncated:i}}const Oc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function kc(e){return Dc(e)}const Ac={description:`Execute a shell command in the shared workspace environment.`,execute:kc,inputSchema:Oc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},jc=new B(`ash.readFile`);function J(e){return de.normalize(e)}function Mc(e){return e}function Nc(e){let t=be(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function Pc(e,t,n){let r=e.ensure(jc,()=>({byTarget:{}}));e.set(jc,{byTarget:{...r.byTarget,[t]:n}})}function Fc(e){e.set(jc,{byTarget:{}})}const Ic=new Map;async function Lc(e){let t=Ic.get(e.id);if(t!==void 0)return t;let n=Rc(e);Ic.set(e.id,n);try{return await n}catch{return Ic.delete(e.id),!1}}async function Rc(e){return(await e.runCommand({command:`command -v rg >/dev/null 2>&1`})).exitCode===0}function Y(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function zc(e){let t=e.path??`/workspace`;xc(t);let n=J(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await q(),a=await Lc(i)?Bc({normalizedPath:n,pattern:e.pattern}):Vc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand({command:a});if(o.exitCode!==0&&o.exitCode!==1)throw Uc(a,o.exitCode,o.stderr);let s=o.stdout.split(`
68
68
  `).filter(e=>e.length>0),c=s.length>r,l=c?s.slice(0,r):s,u=[],d=0,f=!1;for(let e of l){let t=J(e),n=Buffer.byteLength(t,`utf8`)+1;if(d+n>51200&&u.length>0){f=!0;break}u.push(t),d+=n}if(u.length===0)return{content:`No files found`,count:0,path:n,truncated:!1};let p=c||f,m=[...u];return p&&(m.push(``),m.push(`(Results truncated: showing first ${u.length} results out of more. Use a more specific path or pattern to narrow results.)`)),{content:m.join(`
@@ -73,7 +73,7 @@ A single tool or subagent call runs as one serial action. If you call multiple i
73
73
  `),execute:$c,inputSchema:Qc,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function tl(e){let{filePath:t,offset:n,limit:r}=e;xc(t);let i=await q(),a=J(t),o=n??1,s=r??2e3;if(o<1)throw Error(`offset must be >= 1. Received: ${o}.`);let c=await i.readTextFile({path:t});if(c===null)throw Error(`File not found: ${t}. Verify the path exists and is accessible in the sandbox.`);if(c.includes(`\0`))throw Error(`File "${t}" contains NUL bytes and appears to be a binary file. read_file only supports text files.`);let l=c.split(`
74
74
  `),u=l.length>0&&l[l.length-1]===``?l.length-1:l.length;if(u===0){if(o>1)throw Error(`offset ${o} is past the end of the file (0 lines). Use the default offset to read an empty file.`);return{content:``,path:a,totalLines:0,truncated:!1}}if(o>u)throw Error(`offset ${o} is past the end of the file (${u} lines).`);let d=Nc({content:c,filePath:a}),f=Mc(a);Pc(V(),f,d);let p=o-1,m=Math.min(p+s,u),h=l.slice(p,m),g=[],_=0,v=!1;for(let e=0;e<h.length;e++){let t=`${o+e}: ${Tc(h[e]??``)}`,n=Buffer.byteLength(t,`utf8`)+1;if(_+n>51200&&g.length>0){v=!0;break}g.push(t),_+=n}let ee=g.join(`
75
75
  `),te=o+g.length-1;return te<u||v?{content:ee,nextOffset:te+1,path:a,totalLines:u,truncated:!0}:{content:ee,path:a,totalLines:u,truncated:!1}}const nl={additionalProperties:!1,properties:{filePath:{description:`The absolute path to the file to read.`,type:`string`},limit:{description:`Maximum number of lines to return. Defaults to 2000.`,minimum:1,type:`integer`},offset:{description:`1-based line number to start from. Defaults to 1.`,minimum:1,type:`integer`}},required:[`filePath`],type:`object`};async function rl(e){return tl(e)}const il={description:[`Read a file from the local filesystem. If the path does not exist, an error is returned.`,``,`Usage:`,`- The filePath parameter should be an absolute path.`,`- By default, this tool returns up to 2000 lines from the start of the file.`,`- The offset parameter is the line number to start from (1-indexed).`,`- To read later sections, call this tool again with a larger offset.`,`- Use the grep tool to find specific content in large files or files with long lines.`,`- If you are unsure of the correct file path, use the glob tool to look up filenames by glob pattern.`,'- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n".',`- Any line longer than 2000 characters is truncated.`,`- Call this tool in parallel when you know there are multiple files you want to read.`,`- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.`].join(`
76
- `),execute:rl,inputSchema:nl,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Fc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},al=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function ol(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill id to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}async function sl(e,t){ol(t);let n=await cl(e),r=ll(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(al,``)}async function cl(e){let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return t}function ll(e,t){return`${G}/skills/${e}/${t}`}async function ul(e){let t=V().get(hd);if(t===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:n}=e;return await sl(t,n)}const dl={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>ul(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`ash:framework/load-skill`,name:`load_skill`,retentionPolicy:`keep`,sourceId:`ash:load-skill-tool`,sourceKind:`module`},fl=new B(`ash.todo`);function pl(e){if(e.items.length!==0)return`[Your task list was preserved across context compaction]\n${e.items.map(e=>`- [${e.status===`completed`?`x`:e.status===`cancelled`?`-`:` `}] [${e.priority}] ${e.content}`).join(`
76
+ `),execute:rl,inputSchema:nl,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Fc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},al=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function ol(e){if(e.length===0||e.trim()!==e||e.startsWith(`.`)||e.includes(`/`)||e.includes(`\\`)||e.includes(`..`)||/^[A-Za-z]:/.test(e))throw Error(`Expected skill id to be a non-empty safe path segment without whitespace, separators, "." prefix, or "..".`)}async function sl(e,t){ol(t);let n=await cl(e),r=ll(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(al,``)}async function cl(e){let t=await e.get();if(t===null)throw Error(`The sandbox is not available in the current authored runtime context.`);return t}function ll(e,t){return`${G}/skills/${e}/${t}`}async function ul(e){let t=V().get(gd);if(t===void 0)throw Error(`The load_skill tool requires sandbox access on the runtime context. Ensure the step is running inside a managed runtime context with sandbox support.`);let{skill:n}=e;return await sl(t,n)}const dl={description:[`Load the full instructions for one available skill by name or id.`,`Use this tool when the request clearly matches a listed skill description or when the user explicitly asks for that skill.`,`Loading adds the skill instructions to the current turn.`,`Choose the "skill" value from the Available skills block.`].join(` `),execute:e=>ul(e),inputSchema:{additionalProperties:!1,properties:{skill:{description:`Available skill name or id.`,type:`string`}},required:[`skill`],type:`object`},logicalPath:`ash:framework/load-skill`,name:`load_skill`,retentionPolicy:`keep`,sourceId:`ash:load-skill-tool`,sourceKind:`module`},fl=new B(`ash.todo`);function pl(e){if(e.items.length!==0)return`[Your task list was preserved across context compaction]\n${e.items.map(e=>`- [${e.status===`completed`?`x`:e.status===`cancelled`?`-`:` `}] [${e.priority}] ${e.content}`).join(`
77
77
  `)}`}function ml(e){let{items:t}=e,n={cancelled:0,completed:0,in_progress:0,pending:0,total:t.length};for(let e of t)n[e.status]++;return{counts:n,todos:t}}function hl(e){let t=V(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(fl,e),ml(e)}return ml(t.ensure(fl,()=>({items:[]})))}const gl={description:[`Use this tool to create and manage a structured task list for the current session.`,`This helps you track progress, organize complex tasks, and demonstrate thoroughness.`,``,`When to use:`,`- Complex multistep tasks requiring 3 or more distinct steps`,`- When the user provides multiple tasks or a numbered list`,`- After receiving new instructions, to capture requirements`,`- After completing a task, to mark it complete and add follow-ups`,``,`When NOT to use:`,`- Single, straightforward tasks that need no tracking`,`- Purely conversational or informational requests`,``,`Usage:`,"- Call with `todos` to replace the entire list (full replacement write)","- Call without `todos` to read the current list",`- Both return the full current list with status counts`,`- Mark tasks in_progress when you start, completed when done`,`- Only have ONE task in_progress at a time`].join(`
78
78
  `),execute:async e=>hl(e??{}),inputSchema:{additionalProperties:!1,properties:{todos:{description:`The updated todo list. Omit to read the current list without modifying it.`,items:{additionalProperties:!1,properties:{content:{description:`Brief description of the task.`,type:`string`},priority:{description:`Priority level of the task.`,enum:[`high`,`medium`,`low`],type:`string`},status:{description:`Current status of the task.`,enum:[`pending`,`in_progress`,`completed`,`cancelled`],type:`string`}},required:[`content`,`status`,`priority`],type:`object`},type:`array`}},type:`object`},logicalPath:`ash:framework/todo`,name:`todo`,onCompact({ctx:e}){let t=e.get(fl);if(t===void 0||t.items.length===0)return{};let n=pl(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function _l(e){let t=new Le({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function vl(e){let t=e;return t=t.replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi,``),t=t.replace(/<\/(p|div|br|h[1-6]|li|tr|blockquote|pre|section|article|header|footer|nav|aside|main|figure|figcaption|details|summary)>/gi,`
79
79
  `),t=t.replace(/<br\s*\/?>/gi,`
@@ -85,4 +85,4 @@ A single tool or subagent call runs as one serial action. If you call multiple i
85
85
  `),execute:Tl,inputSchema:{additionalProperties:!1,properties:{format:{description:`The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".`,enum:[`markdown`,`text`,`html`],type:`string`},timeout:{description:`Optional timeout in seconds. Defaults to 30, max 120.`,type:`number`},url:{description:`The fully-formed URL to fetch content from. Must start with http:// or https://.`,type:`string`}},required:[`url`],type:`object`},logicalPath:`ash:framework/web-fetch`,name:`web_fetch`,sourceId:`ash:web-fetch-tool`,sourceKind:`module`},Dl={description:`Search the web for real-time information. Use this to find up-to-date information about current events, recent developments, or topics that may have changed since the knowledge cutoff.`,inputSchema:null,logicalPath:`ash:framework/web-search`,name:`web_search`,sourceId:`ash:web-search-tool`,sourceKind:`module`};async function Ol(e){let{filePath:t,content:n}=e;xc(t);let r=await q(),i=V(),a=J(t),o=Mc(a),s=await r.readTextFile({path:t});if(s===null)return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(jc,()=>({byTarget:{}})).byTarget[o];if(c===void 0)throw Error(`You must read file ${t} before overwriting it. Use the read_file tool first.`);let l=Nc({content:s,filePath:a});if(l.contentHash!==c.contentHash||l.byteLength!==c.byteLength)throw Error(`File ${t} has been modified since it was last read. Please read the file again before modifying it.`);return await r.writeTextFile({content:n,path:t}),Pc(i,o,Nc({content:n,filePath:a})),{existed:!0,path:a}}const kl={additionalProperties:!1,properties:{content:{description:`Complete replacement file contents.`,type:`string`},filePath:{description:`The absolute path to the file to write (must be absolute, not relative).`,type:`string`}},required:[`filePath`,`content`],type:`object`};async function Al(e){return Ol(e)}const jl=[bc,Ac,Kc,el,il,{description:[`Writes a file to the local filesystem.`,``,`Usage:`,`- This tool will overwrite the existing file if there is one at the provided path.`,`- If this is an existing file, you MUST use the read_file tool first to read the file's contents. This tool will fail if you did not read the file first.`,`- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.`,`- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.`,`- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`].join(`
86
86
  `),execute:Al,inputSchema:kl,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},gl,El,Dl,dl,Yo],Ml=new Map([[Yo,e=>e.hasConnections]]);function Nl(e){return jl.filter(t=>{let n=Ml.get(t);return n===void 0||n(e)})}function Pl(){return new Set(jl.map(e=>e.name))}function Fl(e){let t=[],n=[],r=new Map,i=[];for(let a of e){let e=a.lifecycle.session;e!==void 0&&t.push({slug:a.slug,handler:e});let o=a.lifecycle.turn;o!==void 0&&n.push({slug:a.slug,handler:o});for(let[e,t]of Object.entries(a.events)){let n={slug:a.slug,handler:t,eventType:e};if(e===`*`)i.push(n);else{let t=r.get(e)??[];t.push(n),r.set(e,t)}}}return{session:t,turn:n,streamEventsByType:r,streamEventsWildcard:i}}var X=class extends Error{logicalPath;sourceId;constructor(e,t={}){super(e),this.name=`ResolveAgentError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};function Il(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function Z(e){let t=e.nodeId??`__root__`,n=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(n===void 0)throw new X(`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`,{logicalPath:e.definition.logicalPath,sourceId:e.definition.sourceId});return await s(r(c(n,`Missing compiled module namespace for ${e.kindLabel} source "${e.definition.sourceId}" in node "${t}".`),{exportName:e.definition.exportName,logicalPath:e.definition.logicalPath}))}async function Ll(e,t,n){try{let r=si(await Z({definition:e,kindLabel:`channel`,moduleMap:t,nodeId:n}),`Expected the channel export "${e.exportName??`default`}" from "${e.logicalPath}" to match the public Ash shape.`),i=Il({exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId}),a=r.routes.find(t=>t.method.toUpperCase()===e.method.toUpperCase()&&t.path===e.urlPath),o=r.adapter;return o&&o.kind!==`http`&&(o.kind=`channel:${e.name}`),{name:e.name,method:e.method,urlPath:e.urlPath,fetch:async(e,t)=>a?a.handler(e,t):Response.json({error:`No matching route handler.`,ok:!1},{status:404}),handler:a?.handler,receive:r.receive,definition:r,adapter:o,...i}}catch(t){throw t instanceof X?t:new X(`Failed to attach the channel definition from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function Rl(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);Bi(`connection:${r.url}`,{kind:`connection`,name:e.connectionName});let i=r.auth!==void 0,a=r.headers!==void 0,o={connectionName:e.connectionName,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`,url:e.url};if(i)try{o.authorization=fi(r.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new X(p(t),{logicalPath:e.logicalPath,sourceId:e.sourceId})}return a&&(o.headers=r.headers),r.tools!==void 0&&(o.tools=r.tools),typeof r.approval==`function`&&(o.approval=r.approval),o}catch(t){throw t instanceof X?t:new X(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function zl(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:n}),Q(e,`to return an object`)),i={},a={},s=r.lifecycle;if(s!==void 0){let t=c(s,Q(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(i[n]=o(r,Q(e,`to provide a function for "lifecycle.${n}"`)))}}let l=r.events;if(l!==void 0){let t=c(l,Q(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(a[n]=o(r,Q(e,`to provide a function for "events.${n}"`)))}return{events:a,exportName:e.exportName,lifecycle:i,logicalPath:e.logicalPath,slug:e.slug,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof X?t:new X(`Failed to attach hook handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Q(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Bl=class e extends Error{backendName;templateKey;constructor(e){super(`Sandbox template "${e.templateKey}" is not provisioned for backend "${e.backendName}". Run \`ash build\` or invoke \`prewarmAppSandboxes()\` before serving traffic.`),this.name=`SandboxTemplateNotProvisionedError`,this.backendName=e.backendName,this.templateKey=e.templateKey}static is(t){return t instanceof e}};async function Vl(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function Hl(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Ul(e){return{id:e.id,resolvePath(t){return e.resolvePath(t)},async runCommand(t){return await e.runCommand(t)},async readFile(t){return await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)})},async readBinaryFile(t){let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:await Vl(n)},async readTextFile(t){Wl(t);let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:Kl(ql(await Vl(n),t.encoding??`utf-8`),t)},async writeFile(t){await e.writeFile({abortSignal:t.abortSignal,content:t.content,path:e.resolvePath(t.path)})},async writeBinaryFile(t){await e.writeFile({abortSignal:t.abortSignal,content:Hl(t.content),path:e.resolvePath(t.path)})},async writeTextFile(t){let n=Jl(t.content,t.encoding??`utf-8`);await e.writeFile({abortSignal:t.abortSignal,content:Hl(n),path:e.resolvePath(t.path)})}}}function Wl(e){let{startLine:t,endLine:n}=e;if(t!==void 0&&(!Number.isInteger(t)||t<1))throw Error(`startLine must be a positive integer (1-based).`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw Error(`endLine must be a positive integer (1-based).`);if(t!==void 0&&n!==void 0&&t>n)throw Error(`startLine must not be greater than endLine.`)}function Gl(e){let t=[],n=0;for(let r=0;r<e.length;r++)e[r]===`\r`?r+1<e.length&&e[r+1]===`
87
87
  `?(t.push(e.slice(n,r+2)),n=r+2,r++):(t.push(e.slice(n,r+1)),n=r+1):e[r]===`
88
- `&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Kl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Gl(e),r=n.length,i=t.startLine??1,a=Math.min(t.endLine??r,r);return i>r?``:n.slice(i-1,a).join(``)}function ql(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(t)}function Jl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Yl(e={}){return{name:`local`,async prewarm(e){let t=tu(Td(e.runtimeContext.appRoot),e.templateKey);if(await lu(t))return;let n=await Xl({sessionKey:e.templateKey,snapshotPath:t}),r=Ul(Ql(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}},async create(e){let t=Td(e.runtimeContext.appRoot),n=await su(tu(t,e.templateKey));if(n===null)throw new Bl({backendName:`local`,templateKey:e.templateKey});let r=uu(e.existingMetadata)??nu(t,e.sessionKey);return await lu(r)||await cu(r,n),Zl(await Xl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Xl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await su(e.snapshotPath),i=new n(ru(r));await iu(i),await au(i,r?.entries??[]);let a=new t({cwd:G,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await ou({filesystem:i,sandbox:a});return await cu(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${Y(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await $l(n,e.abortSignal):await n;return{exitCode:r.exitCode,stderr:r.stderr,stdout:r.stdout}},async readFileBytes(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async readFileText(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)},sessionKey:e.sessionKey,snapshotPath:e.snapshotPath,async writeFiles(e){for(let t of e){let e=b(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Zl(e){let t=Ul(Ql(e));return{session:t,useSessionFn:async()=>t,async captureState(){return{backendName:`local`,metadata:await e.captureSnapshot()??{},sessionKey:e.sessionKey}},async dispose(){await e.dispose()}}}function Ql(e){return{id:e.sessionKey,resolvePath:eu,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Hl(n)},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function $l(e,t){return await new Promise((n,r)=>{let i=()=>{r(new DOMException(`The operation was aborted.`,`AbortError`))};if(t.aborted){i();return}t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})})}function eu(e){return e.startsWith(`/`)?e:`${G}/${e}`}function tu(e,t){return x(e,`local`,`templates`,`${t}.json`)}function nu(e,t){return x(e,`local`,`sessions`,`${t}.json`)}function ru(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function iu(e){await e.mkdir(G,{recursive:!0})}async function au(e,t){let n=t.filter(e=>e.kind===`directory`).map(e=>e.path).sort((e,t)=>e.localeCompare(t));for(let t of n)t!==`/workspace`&&await e.mkdir(t,{recursive:!0})}async function ou(e){let t=[],n=e.filesystem.getAllPaths().sort((e,t)=>e.localeCompare(t));for(let r of n){let n=await e.filesystem.stat(r);if(n.isSymbolicLink)continue;if(n.isDirectory){t.push({kind:`directory`,path:r});continue}if(!n.isFile)continue;let i=await e.filesystem.readFileBuffer(r);t.push({contentBase64:Buffer.from(i).toString(`base64`),kind:`file`,path:r})}return{entries:t,env:{...e.sandbox.getEnv()},version:1}}async function su(e){if(!await lu(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function cu(e,t){await C(b(e),{recursive:!0}),await w(e,`${JSON.stringify(t,null,2)}\n`)}async function lu(e){try{return await me(e),!0}catch{return!1}}function uu(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function du(e){return Yl({createOptions:e})}function fu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:ku,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=Tu(n.tags,e.tags),a;try{a=await pu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Bl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${Ou(t)}`,{cause:t})}let o;try{o=await hu({createOptions:n,existingMetadata:e.existingMetadata,sandboxModule:await t(),sessionKey:e.sessionKey,snapshotId:a.snapshotId,tags:i})}catch(t){throw Error(`Failed to create sandbox session "${e.sessionKey}": ${Ou(t)}`,{cause:t})}return gu(o,e.sessionKey)},async prewarm(e){let i;try{i=await mu({bootstrap:e.bootstrap,createOptions:n,loadSandboxModule:t,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${Ou(t)}. Run \`vercel login\` and \`vercel link\` so the SDK can authenticate, or set VERCEL_TOKEN.`,{cause:t})}r.set(e.templateKey,i)}}}async function pu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await Su(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Bl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function mu(e){let t=await e.loadSandboxModule(),n=await Su(t,e.templateKey),r=Tu(e.createOptions.tags,e.tags);if(n===null){let i={...e.createOptions,name:e.templateKey,persistent:!1};r!==void 0&&(i.tags=r),n=await t.Sandbox.create(i)}else await Eu(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await yu(n,e.createOptions);let i=Ul(_u(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await n.update(e),i)});for(let t of e.seedFiles)typeof t.content==`string`?await i.writeTextFile({content:t.content,path:t.path}):await i.writeBinaryFile({content:t.content,path:t.path});let a=await n.snapshot();return{sandboxName:n.name,snapshotId:a.snapshotId,templateKey:e.templateKey}}async function hu(e){let t=wu(e.existingMetadata)??e.sessionKey,n=await Su(e.sandboxModule,t);if(n!==null)return await Eu(n,e.tags),n;let{runtime:r,...i}=e.createOptions,a={...i,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(a.tags=e.tags),await e.sandboxModule.Sandbox.create(a)}function gu(e,t){return{session:Ul(_u(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Ul(_u(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function _u(e,t){return{id:t,resolvePath:vu,async runCommand(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??`/workspace`,signal:t.abortSignal}),[r,i]=await Promise.all([n.stdout(),n.stderr()]);return{exitCode:n.exitCode,stderr:i,stdout:r}},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function vu(e){return e.startsWith(`/`)?e:`${G}/${e}`}async function yu(e,t){await bu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${G} && chown ${xu}:${xu} ${G}`}),t.networkPolicy!==`deny-all`&&await bu(e,{failureMessage:`Failed to install ripgrep in Vercel sandbox.`,script:`command -v rg >/dev/null 2>&1 || { dnf install -y spal-release && dnf install -y ripgrep; }`})}async function bu(e,t){let n=await e.runCommand({args:[`-lc`,t.script],cmd:`bash`,sudo:!0});if(n.exitCode!==0){let e=await n.stderr();throw Error(`${t.failureMessage} ${e}`.trim())}}const xu=`vercel-sandbox`;async function Su(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(Cu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${Ou(e)}`,{cause:e})}}function Cu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function wu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function Tu(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>Au)throw Error(`Vercel Sandbox supports at most ${Au} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function Eu(e,t){t===void 0||Du(e.tags,t)||await e.update({tags:t})}function Du(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function Ou(e){return e instanceof Error?e.message:String(e)}const ku=1800*1e3,Au=5;function ju(e){return fu({createOptions:e})}function Mu(e){return Ei(()=>process.env.VERCEL?ju(e?.vercel):du(e?.local))}async function Nu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Pu(r.backend,e.logicalPath),bootstrap:r.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:r.onSession,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof X?t:new X(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Pu(e,t){if(e===void 0)return Mu();if(typeof e==`function`)return Ei(e);if(typeof e!=`object`||!e)throw new X(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,{logicalPath:t});let n=e;if(typeof n.name!=`string`||n.name.length===0)throw new X(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new X(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function Fu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));Bi(`tool:${r.description}`,{kind:`tool`,name:e.name});let i=o(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:i,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Iu(r,e)}}catch(t){throw t instanceof X?t:new X(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Iu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=o(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=o(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=Lu(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=o(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&Ru(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function Lu(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new X($(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function $(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function Ru(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function zu(e){let t=e.manifest.skills.map(e=>({...e,metadata:e.metadata===void 0?void 0:{...e.metadata}})),n=[],r=[];for(let t of e.manifest.channels){if(t.kind===`disabled`){r.push(t.name);continue}n.push(await Ll(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Fu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>zl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Rl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await Nu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Bu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Vu(e.manifest),connections:o,disabledFrameworkChannels:r,disabledFrameworkTools:[...e.manifest.disabledFrameworkTools],hooks:a,metadata:{agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,diagnosticsSummary:e.manifest.diagnosticsSummary},sandbox:s,workspaceResourceRoot:l,skills:t,tools:i,workspaceSpec:{rootEntries:[...l.rootEntries]}};return c===void 0?u:{...u,instructions:c}}function Bu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Vu(e){let t={metadata:{...e.config.metadata},model:e.config.model.source===void 0?{id:e.config.model.id,contextWindowTokens:e.config.model.contextWindowTokens,providerOptions:e.config.model.providerOptions}:{contextWindowTokens:e.config.model.contextWindowTokens,id:e.config.model.id,providerOptions:e.config.model.providerOptions,source:{exportName:e.config.model.source.exportName,sourceKind:`module`,logicalPath:e.config.model.source.logicalPath,sourceId:e.config.model.source.sourceId}},name:e.config.name};if(e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}return e.config.source!==void 0&&(t.source=Il(e.config.source)),t}function Hu(e){return{sandbox:{definition:e.authoredSandbox??Uu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Uu(){return{backend:Mu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Wu=`load_skill`,Gu=Object.freeze({type:`object`,properties:Object.freeze({message:Object.freeze({type:`string`,description:`The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.`})}),required:Object.freeze([`message`]),additionalProperties:!1});function Ku(e){let t=[],n=new Ka(`subagent`,e.reservedToolNames??[]),r=new Map;for(let i of e.subagents){let e={logicalPath:i.logicalPath,sourceId:i.sourceId};if(r.has(i.nodeId))throw new H(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=qu(i),o={definition:i,prepared:a};n.register(i.name,o,{location:e,duplicateMessage:`Found multiple subagents named "${i.name}". Subagent names must be unique at runtime.`,reservedMessage:`Subagent "${i.name}" collides with another runtime-visible tool name.`}),t.push(a),r.set(i.nodeId,o)}return{preparedTools:t,subagentsByName:n.asMap(),subagentsByNodeId:r}}function qu(e){return{description:e.description,inputSchema:Gu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Ju(e,t={}){let n=[],r=new Ka(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Yu(t);r.register(t.name,{definition:t,prepared:e},{location:{logicalPath:t.logicalPath,sourceId:t.sourceId},duplicateMessage:`Found multiple authored tools named "${t.name}". Tool names must be unique at runtime.`,reservedMessage:`Tool "${t.name}" collides with another runtime-visible tool name.`}),n.push(e)}return{preparedTools:n,toolsByName:r.asMap()}}async function Yu(e){return{description:e.description,inputSchema:await Xu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Xu(e){return e.inputSchema}var Zu=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function Qu(e){let t=new Map,n=nd(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await $u({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:L,nodesByNodeId:t,subagentNodesById:r})}}async function $u(e){let t=rd(e.nodeId);if(e.nodesByNodeId.has(t))throw new Zu(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await zu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=Nl({hasConnections:r}),a=r?ad(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Pl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Zu(`agent/tools/${r}.ts exports disableTool() but "${r}" is not a framework tool. Rename the file to one of: ${[...s].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let l=new Set(n.disabledFrameworkTools),u=await Ju({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Wu]}),d=new Set(n.channels.map(e=>e.name)),f=hc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Zu(`agent/channels/${r}.ts exports disableRoute() but "${r}" is not a framework channel. Rename the file to one of: ${[...f].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let p=new Set(n.disabledFrameworkChannels),m=[...mc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Hu({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Ku({reservedToolNames:[Wu,...u.preparedTools.map(e=>e.name)],subagents:await ed({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Fl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:cs({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function ed(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new Zu(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:rd(e.parentNodeId),sourceId:r});t.push(await td({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function td(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:rd(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await $u({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}function nd(e){let t=new Map;for(let n of e.subagentEdges){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.childNodeId]);continue}e.push(n.childNodeId)}return t}function rd(e){return e===`__root__`?So:e}const id=Yo.name;function ad(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===id?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const od=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function sd(e){let[t,n]=await Promise.all([Eo({compiledArtifactsSource:e}),cd(e)]),r=await Qu({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Xa({channels:pd(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function cd(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await ld(e):await jo({compiledArtifactsSource:e})}async function ld(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(Te(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function ud(e){if(od)return sd(e);let t=uo(),n=no(e),r=await yo(e),i=t.bundleCacheKeyBySourceKey.get(n);i!==void 0&&i!==r&&t.bundleCache.delete(i),t.bundleCacheKeyBySourceKey.set(n,r);let a=t.bundleCache.get(r);if(a!==void 0)return a;let o=sd(e).catch(e=>{throw t.bundleCache.delete(r),t.bundleCacheKeyBySourceKey.get(n)===r&&t.bundleCacheKeyBySourceKey.delete(n),e});return t.bundleCache.set(r,o),o}async function dd(e){let t=await ud(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=Co(t.graph,e.nodeId);return{adapterRegistry:t.adapterRegistry,compiledArtifactsSource:t.compiledArtifactsSource,graph:{nodesByNodeId:t.graph.nodesByNodeId,root:n},hookRegistry:n.hookRegistry,moduleMap:t.moduleMap,nodeId:e.nodeId,resolvedAgent:n.agent,subagentRegistry:n.subagentRegistry,toolRegistry:n.toolRegistry,turnAgent:n.turnAgent}}function fd(){let e=uo();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function pd(e){let t=new Map;for(let n of e.nodesByNodeId.values())for(let e of n.channels)t.set(`${e.sourceId}:${e.name}`,e);return[...t.values()]}new B(`ash.channel`,{codec:{serialize(e){return{kind:Fa(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(md);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Za(n.adapterRegistry,e)}}});const md=new B(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return dd({compiledArtifactsSource:t,nodeId:n})}}});new B(`ash.session`);const hd=new B(`ash.sandbox`),gd=_(),_d={workflowId:`workflow//${gd.name}@${gd.version}//workflowEntry`};function vd(e=process.cwd()){return S(e)}function yd(e){return be(`sha256`).update(e).digest(`hex`).slice(0,12)}function bd(){return!!process.env.VERCEL}function xd(e,t=`all`){let n=x(e,`.ash`,`nitro`);return t===`all`?n:x(n,t)}function Sd(e,t){return x(e,`.ash`,`nitro-output`,t)}function Cd(e){let t=x(m(),`.ash`,`workflow-cache`);return wd(t),x(t,yd(e))}function wd(e){if(!xe(e))return;let t=_().version,n;try{n=Ce(e)}catch{return}for(let r of n){let n=x(e,r),i=x(n,`ash-cache.json`);if(xe(i))try{let e=JSON.parse(Se(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&we(n,{force:!0,recursive:!0})}catch{}}}function Td(e){return x(e,`.ash`,`sandbox-cache`)}function Ed(e){return bd()?x(e,`.vercel`,`output`):x(e,`.output`)}function Dd(e){return{appRoot:e,outputDir:Ed(e),workflowId:_d.workflowId,workflowBuildDir:Cd(e),workflowSourceDir:g(`src/execution`)}}export{Er as C,In as D,L as E,jr as S,Dr as T,no as _,Cd as a,ni as b,hc as c,Eo as d,So as f,to as g,eo as h,Sd as i,mc as l,U as m,vd as n,fd as o,go as p,xd as r,Qu as s,Dd as t,G as u,fa as v,Or as w,Nr as x,pa as y};
88
+ `&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Kl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Gl(e),r=n.length,i=t.startLine??1,a=Math.min(t.endLine??r,r);return i>r?``:n.slice(i-1,a).join(``)}function ql(e,t){return t===`utf-8`||t===`utf8`?new TextDecoder(`utf-8`,{fatal:!0}).decode(e):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(t)}function Jl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Yl(e={}){return{name:`local`,async prewarm(e){let t=tu(Ed(e.runtimeContext.appRoot),e.templateKey);if(await lu(t))return;let n=await Xl({sessionKey:e.templateKey,snapshotPath:t}),r=Ul(Ql(n));try{e.bootstrap!==void 0&&await e.bootstrap({use:async()=>r});for(let t of e.seedFiles)typeof t.content==`string`?await r.writeTextFile({content:t.content,path:t.path}):await r.writeBinaryFile({content:t.content,path:t.path});if(await n.captureSnapshot()===null)throw Error(`Failed to capture local sandbox template state for "${e.templateKey}".`)}finally{await n.dispose()}},async create(e){let t=Ed(e.runtimeContext.appRoot),n=await su(tu(t,e.templateKey));if(n===null)throw new Bl({backendName:`local`,templateKey:e.templateKey});let r=uu(e.existingMetadata)??nu(t,e.sessionKey);return await lu(r)||await cu(r,n),Zl(await Xl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Xl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await su(e.snapshotPath),i=new n(ru(r));await iu(i),await au(i,r?.entries??[]);let a=new t({cwd:G,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await ou({filesystem:i,sandbox:a});return await cu(e.snapshotPath,t),{snapshotPath:e.snapshotPath}},async dispose(){await a.dispose?.()},async executeCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${Y(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await $l(n,e.abortSignal):await n;return{exitCode:r.exitCode,stderr:r.stderr,stdout:r.stdout}},async readFileBytes(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async readFileText(e){let t;try{t=await i.readFileBuffer(e)}catch{return null}return new TextDecoder(`utf-8`,{fatal:!0}).decode(t)},sessionKey:e.sessionKey,snapshotPath:e.snapshotPath,async writeFiles(e){for(let t of e){let e=b(t.path);await i.mkdir(e,{recursive:!0}),await i.writeFile(t.path,t.content)}}}}function Zl(e){let t=Ul(Ql(e));return{session:t,useSessionFn:async()=>t,async captureState(){return{backendName:`local`,metadata:await e.captureSnapshot()??{},sessionKey:e.sessionKey}},async dispose(){await e.dispose()}}}function Ql(e){return{id:e.sessionKey,resolvePath:eu,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Hl(n)},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function $l(e,t){return await new Promise((n,r)=>{let i=()=>{r(new DOMException(`The operation was aborted.`,`AbortError`))};if(t.aborted){i();return}t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,i),n(e)},e=>{t.removeEventListener(`abort`,i),r(e)})})}function eu(e){return e.startsWith(`/`)?e:`${G}/${e}`}function tu(e,t){return x(e,`local`,`templates`,`${t}.json`)}function nu(e,t){return x(e,`local`,`sessions`,`${t}.json`)}function ru(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function iu(e){await e.mkdir(G,{recursive:!0})}async function au(e,t){let n=t.filter(e=>e.kind===`directory`).map(e=>e.path).sort((e,t)=>e.localeCompare(t));for(let t of n)t!==`/workspace`&&await e.mkdir(t,{recursive:!0})}async function ou(e){let t=[],n=e.filesystem.getAllPaths().sort((e,t)=>e.localeCompare(t));for(let r of n){let n=await e.filesystem.stat(r);if(n.isSymbolicLink)continue;if(n.isDirectory){t.push({kind:`directory`,path:r});continue}if(!n.isFile)continue;let i=await e.filesystem.readFileBuffer(r);t.push({contentBase64:Buffer.from(i).toString(`base64`),kind:`file`,path:r})}return{entries:t,env:{...e.sandbox.getEnv()},version:1}}async function su(e){if(!await lu(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function cu(e,t){await C(b(e),{recursive:!0}),await w(e,`${JSON.stringify(t,null,2)}\n`)}async function lu(e){try{return await me(e),!0}catch{return!1}}function uu(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function du(e){return Yl({createOptions:e})}function fu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:Au,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=Eu(n.tags,e.tags),a;try{a=await pu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Bl.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${ku(t)}`,{cause:t})}let o;try{o=await hu({createOptions:n,existingMetadata:e.existingMetadata,sandboxModule:await t(),sessionKey:e.sessionKey,snapshotId:a.snapshotId,tags:i})}catch(t){throw Error(`Failed to create sandbox session "${e.sessionKey}": ${ku(t)}`,{cause:t})}return gu(o,e.sessionKey)},async prewarm(e){let i;try{i=await mu({bootstrap:e.bootstrap,createOptions:n,loadSandboxModule:t,seedFiles:e.seedFiles,templateKey:e.templateKey})}catch(t){throw Error(`Failed to prewarm Vercel sandbox template "${e.templateKey}": ${ku(t)}. Run \`vercel login\` and \`vercel link\` so the SDK can authenticate, or set VERCEL_TOKEN.`,{cause:t})}r.set(e.templateKey,i)}}}async function pu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await Su(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Bl({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function mu(e){let t=await e.loadSandboxModule(),n=await Su(t,e.templateKey),r=Eu(e.createOptions.tags,e.tags);if(n===null){let i={...e.createOptions,name:e.templateKey,persistent:!1};r!==void 0&&(i.tags=r),n=await t.Sandbox.create(i)}else await Du(n,r);let i=wu(e.createOptions);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0&&n.currentSnapshotId!==i)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await yu(n,e.createOptions);let a=Ul(_u(n,e.templateKey));e.bootstrap!==void 0&&await e.bootstrap({use:async e=>(e!==void 0&&await n.update(e),a)});for(let t of e.seedFiles)typeof t.content==`string`?await a.writeTextFile({content:t.content,path:t.path}):await a.writeBinaryFile({content:t.content,path:t.path});let o=await n.snapshot();return{sandboxName:n.name,snapshotId:o.snapshotId,templateKey:e.templateKey}}async function hu(e){let t=Tu(e.existingMetadata)??e.sessionKey,n=await Su(e.sandboxModule,t);if(n!==null)return await Du(n,e.tags),n;let{runtime:r,source:i,...a}=e.createOptions,o={...a,name:t,persistent:!0,source:{snapshotId:e.snapshotId,type:`snapshot`}};return e.tags!==void 0&&(o.tags=e.tags),await e.sandboxModule.Sandbox.create(o)}function gu(e,t){return{session:Ul(_u(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Ul(_u(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function _u(e,t){return{id:t,resolvePath:vu,async runCommand(t){let n=await e.runCommand({args:[`-lc`,t.command],cmd:`bash`,cwd:t.workingDirectory??`/workspace`,signal:t.abortSignal}),[r,i]=await Promise.all([n.stdout(),n.stderr()]);return{exitCode:n.exitCode,stderr:i,stdout:r}},async readFile(t){return await e.readFile({path:t.path})??null},async writeFile(t){let n=await Vl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function vu(e){return e.startsWith(`/`)?e:`${G}/${e}`}async function yu(e,t){await bu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${G} && chown ${xu}:${xu} ${G}`}),t.networkPolicy!==`deny-all`&&await bu(e,{failureMessage:`Failed to install ripgrep in Vercel sandbox.`,script:`command -v rg >/dev/null 2>&1 || { dnf install -y spal-release && dnf install -y ripgrep; }`})}async function bu(e,t){let n=await e.runCommand({args:[`-lc`,t.script],cmd:`bash`,sudo:!0});if(n.exitCode!==0){let e=await n.stderr();throw Error(`${t.failureMessage} ${e}`.trim())}}const xu=`vercel-sandbox`;async function Su(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(Cu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${ku(e)}`,{cause:e})}}function Cu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function wu(e){let t=e.source;if(t?.type===`snapshot`&&typeof t.snapshotId==`string`)return t.snapshotId}function Tu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function Eu(e,t){let n={};if(e!==void 0)for(let[t,r]of Object.entries(e))n[t]=r;if(t!==void 0)for(let[e,r]of Object.entries(t))n[e]=r;let r=Object.keys(n).length;if(r!==0){if(r>ju)throw Error(`Vercel Sandbox supports at most ${ju} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function Du(e,t){t===void 0||Ou(e.tags,t)||await e.update({tags:t})}function Ou(e,t){let n=e??{},r=Object.entries(n),i=Object.entries(t);return r.length===i.length?i.every(([e,t])=>n[e]===t):!1}function ku(e){return e instanceof Error?e.message:String(e)}const Au=1800*1e3,ju=5;function Mu(e){return fu({createOptions:e})}function Nu(e){return Ei(()=>process.env.VERCEL?Mu(e?.vercel):du(e?.local))}async function Pu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Fu(r.backend,e.logicalPath),bootstrap:r.bootstrap,description:e.description,exportName:e.exportName,logicalPath:e.logicalPath,onSession:r.onSession,sourceId:e.sourceId,sourceKind:`module`}}catch(t){throw t instanceof X?t:new X(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Fu(e,t){if(e===void 0)return Nu();if(typeof e==`function`)return Ei(e);if(typeof e!=`object`||!e)throw new X(`Sandbox "${t}" exposed a non-object "backend" field. Use vercelBackend(), localBackend(), another factory that returns a SandboxBackend value, or a zero-arg callback returning one.`,{logicalPath:t});let n=e;if(typeof n.name!=`string`||n.name.length===0)throw new X(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new X(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function Iu(e,t,n){try{let r=c(await Z({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));Bi(`tool:${r.description}`,{kind:`tool`,name:e.name});let i=o(r.execute,$(e,`to provide an execute function`));return{description:e.description,execute:i,exportName:e.exportName,inputSchema:e.inputSchema,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:`module`,...Lu(r,e)}}catch(t){throw t instanceof X?t:new X(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Lu(e,t){let n={};e.onCompact!==void 0&&(n.onCompact=o(e.onCompact,$(t,`to provide an onCompact function`))),e.needsApproval!==void 0&&(n.needsApproval=o(e.needsApproval,$(t,`to provide a needsApproval function`)));let r=Ru(e,t);return r!==void 0&&(n.retentionPolicy=r),e.toModelOutput!==void 0&&(n.toModelOutput=o(e.toModelOutput,$(t,`to provide a toModelOutput function`))),e.inputSchema!==void 0&&zu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function Ru(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new X($(t,`to set retentionPolicy to "auto", "keep", or a function`),{logicalPath:t.logicalPath,sourceId:t.sourceId})}}function $(e,t){return`Expected the tool export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}function zu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function Bu(e){let t=e.manifest.skills.map(e=>({...e,metadata:e.metadata===void 0?void 0:{...e.metadata}})),n=[],r=[];for(let t of e.manifest.channels){if(t.kind===`disabled`){r.push(t.name);continue}n.push(await Ll(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Iu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>zl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Rl(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await Pu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Vu(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Hu(e.manifest),connections:o,disabledFrameworkChannels:r,disabledFrameworkTools:[...e.manifest.disabledFrameworkTools],hooks:a,metadata:{agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,diagnosticsSummary:e.manifest.diagnosticsSummary},sandbox:s,workspaceResourceRoot:l,skills:t,tools:i,workspaceSpec:{rootEntries:[...l.rootEntries]}};return c===void 0?u:{...u,instructions:c}}function Vu(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Hu(e){let t={metadata:{...e.config.metadata},model:e.config.model.source===void 0?{id:e.config.model.id,contextWindowTokens:e.config.model.contextWindowTokens,providerOptions:e.config.model.providerOptions}:{contextWindowTokens:e.config.model.contextWindowTokens,id:e.config.model.id,providerOptions:e.config.model.providerOptions,source:{exportName:e.config.model.source.exportName,sourceKind:`module`,logicalPath:e.config.model.source.logicalPath,sourceId:e.config.model.source.sourceId}},name:e.config.name};if(e.config.compaction!==void 0){let n={};e.config.compaction.model!==void 0&&(n.model=e.config.compaction.model.source===void 0?{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions}:{contextWindowTokens:e.config.compaction.model.contextWindowTokens,id:e.config.compaction.model.id,providerOptions:e.config.compaction.model.providerOptions,source:{exportName:e.config.compaction.model.source.exportName,sourceKind:`module`,logicalPath:e.config.compaction.model.source.logicalPath,sourceId:e.config.compaction.model.source.sourceId}}),e.config.compaction.thresholdPercent!==void 0&&(n.thresholdPercent=e.config.compaction.thresholdPercent),t.compaction=n}return e.config.source!==void 0&&(t.source=Il(e.config.source)),t}function Uu(e){return{sandbox:{definition:e.authoredSandbox??Wu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Wu(){return{backend:Nu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Gu=`load_skill`,Ku=Object.freeze({type:`object`,properties:Object.freeze({message:Object.freeze({type:`string`,description:`The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.`})}),required:Object.freeze([`message`]),additionalProperties:!1});function qu(e){let t=[],n=new Ka(`subagent`,e.reservedToolNames??[]),r=new Map;for(let i of e.subagents){let e={logicalPath:i.logicalPath,sourceId:i.sourceId};if(r.has(i.nodeId))throw new H(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Ju(i),o={definition:i,prepared:a};n.register(i.name,o,{location:e,duplicateMessage:`Found multiple subagents named "${i.name}". Subagent names must be unique at runtime.`,reservedMessage:`Subagent "${i.name}" collides with another runtime-visible tool name.`}),t.push(a),r.set(i.nodeId,o)}return{preparedTools:t,subagentsByName:n.asMap(),subagentsByNodeId:r}}function Ju(e){return{description:e.description,inputSchema:Ku,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Yu(e,t={}){let n=[],r=new Ka(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Xu(t);r.register(t.name,{definition:t,prepared:e},{location:{logicalPath:t.logicalPath,sourceId:t.sourceId},duplicateMessage:`Found multiple authored tools named "${t.name}". Tool names must be unique at runtime.`,reservedMessage:`Tool "${t.name}" collides with another runtime-visible tool name.`}),n.push(e)}return{preparedTools:n,toolsByName:r.asMap()}}async function Xu(e){return{description:e.description,inputSchema:await Zu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Zu(e){return e.inputSchema}var Qu=class extends Error{logicalPath;nodeId;sourceId;constructor(e,t={}){super(e),this.name=`ResolveRuntimeAgentGraphError`,t.logicalPath!==void 0&&(this.logicalPath=t.logicalPath),t.nodeId!==void 0&&(this.nodeId=t.nodeId),t.sourceId!==void 0&&(this.sourceId=t.sourceId)}};async function $u(e){let t=new Map,n=rd(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await ed({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:L,nodesByNodeId:t,subagentNodesById:r})}}async function ed(e){let t=id(e.nodeId);if(e.nodesByNodeId.has(t))throw new Qu(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await Bu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=Nl({hasConnections:r}),a=r?od(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Pl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Qu(`agent/tools/${r}.ts exports disableTool() but "${r}" is not a framework tool. Rename the file to one of: ${[...s].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let l=new Set(n.disabledFrameworkTools),u=await Yu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Gu]}),d=new Set(n.channels.map(e=>e.name)),f=hc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Qu(`agent/channels/${r}.ts exports disableRoute() but "${r}" is not a framework channel. Rename the file to one of: ${[...f].sort().join(`, `)}.`,{nodeId:t,sourceId:e.sourceId});let p=new Set(n.disabledFrameworkChannels),m=[...mc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=Uu({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=qu({reservedToolNames:[Gu,...u.preparedTools.map(e=>e.name)],subagents:await td({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Fl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:cs({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function td(e){let t=[],n=e.childNodeIdsByParentNodeId.get(e.parentNodeId)??[];for(let r of n){let n=e.subagentNodesById.get(r);if(n===void 0)throw new Qu(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:id(e.parentNodeId),sourceId:r});t.push(await nd({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function nd(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:id(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await ed({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,manifest:e.sourceRef.agent,moduleMap:e.moduleMap,nodeId:e.sourceRef.nodeId,nodesByNodeId:e.nodesByNodeId,sourceId:e.sourceRef.sourceId,subagentNodesById:e.subagentNodesById}),t}function rd(e){let t=new Map;for(let n of e.subagentEdges){let e=t.get(n.parentNodeId);if(e===void 0){t.set(n.parentNodeId,[n.childNodeId]);continue}e.push(n.childNodeId)}return t}function id(e){return e===`__root__`?So:e}const ad=Yo.name;function od(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===ad?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const sd=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function cd(e){let[t,n]=await Promise.all([Eo({compiledArtifactsSource:e}),ld(e)]),r=await $u({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Xa({channels:md(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function ld(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await ud(e):await jo({compiledArtifactsSource:e})}async function ud(e){if(e.moduleMapLoaderPath===void 0)throw Error(`Authored-source module map loading requires "moduleMapLoaderPath" in the compiled artifacts source.`);return await(await import(Te(e.moduleMapLoaderPath).href)).loadCompiledModuleMapFromAuthoredSource({compiledArtifactsSource:e})}async function dd(e){if(sd)return cd(e);let t=uo(),n=no(e),r=await yo(e),i=t.bundleCacheKeyBySourceKey.get(n);i!==void 0&&i!==r&&t.bundleCache.delete(i),t.bundleCacheKeyBySourceKey.set(n,r);let a=t.bundleCache.get(r);if(a!==void 0)return a;let o=cd(e).catch(e=>{throw t.bundleCache.delete(r),t.bundleCacheKeyBySourceKey.get(n)===r&&t.bundleCacheKeyBySourceKey.delete(n),e});return t.bundleCache.set(r,o),o}async function fd(e){let t=await dd(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=Co(t.graph,e.nodeId);return{adapterRegistry:t.adapterRegistry,compiledArtifactsSource:t.compiledArtifactsSource,graph:{nodesByNodeId:t.graph.nodesByNodeId,root:n},hookRegistry:n.hookRegistry,moduleMap:t.moduleMap,nodeId:e.nodeId,resolvedAgent:n.agent,subagentRegistry:n.subagentRegistry,toolRegistry:n.toolRegistry,turnAgent:n.turnAgent}}function pd(){let e=uo();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function md(e){let t=new Map;for(let n of e.nodesByNodeId.values())for(let e of n.channels)t.set(`${e.sourceId}:${e.name}`,e);return[...t.values()]}new B(`ash.channel`,{codec:{serialize(e){return{kind:Fa(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(hd);if(n===void 0)throw Error(`Cannot deserialize "ash.channel" before "ash.bundle". The runtime bundle must be present in context.`);return Za(n.adapterRegistry,e)}}});const hd=new B(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return fd({compiledArtifactsSource:t,nodeId:n})}}});new B(`ash.session`);const gd=new B(`ash.sandbox`),_d=_(),vd={workflowId:`workflow//${_d.name}@${_d.version}//workflowEntry`};function yd(e=process.cwd()){return S(e)}function bd(e){return be(`sha256`).update(e).digest(`hex`).slice(0,12)}function xd(){return!!process.env.VERCEL}function Sd(e,t=`all`){let n=x(e,`.ash`,`nitro`);return t===`all`?n:x(n,t)}function Cd(e,t){return x(e,`.ash`,`nitro-output`,t)}function wd(e){let t=x(m(),`.ash`,`workflow-cache`);return Td(t),x(t,bd(e))}function Td(e){if(!xe(e))return;let t=_().version,n;try{n=Ce(e)}catch{return}for(let r of n){let n=x(e,r),i=x(n,`ash-cache.json`);if(xe(i))try{let e=JSON.parse(Se(i,`utf8`));typeof e.ashVersion==`string`&&e.ashVersion!==t&&we(n,{force:!0,recursive:!0})}catch{}}}function Ed(e){return x(e,`.ash`,`sandbox-cache`)}function Dd(e){return xd()?x(e,`.vercel`,`output`):x(e,`.output`)}function Od(e){return{appRoot:e,outputDir:Dd(e),workflowId:vd.workflowId,workflowBuildDir:wd(e),workflowSourceDir:g(`src/execution`)}}export{Er as C,In as D,L as E,jr as S,Dr as T,no as _,wd as a,ni as b,hc as c,Eo as d,So as f,to as g,eo as h,Cd as i,mc as l,U as m,yd as n,pd as o,go as p,Sd as r,$u as s,Od as t,G as u,fa as v,Or as w,Nr as x,pa as y};
@@ -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-DxgjK2PI.js";import{t as m}from"./authored-module-loader-XcFLnl49.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-C6sp4T2U.js";import{t as m}from"./authored-module-loader-XcFLnl49.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,hasRun:e.hasRun,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.markdown===void 0?t:{...t,markdown:e.markdown}})}async function 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-DxgjK2PI.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-C6sp4T2U.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-BDf7A9G7.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-BDf7A9G7.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-DREC8e8Z.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-DREC8e8Z.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-DxgjK2PI.js";import{loadDevelopmentEnvironmentFiles as t}from"../../cli/dev/environment.js";import{a as n,n as r,t as i}from"../../chunks/client-CKsU8Li3.js";import{n as a}from"../../chunks/host-BDf7A9G7.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-C6sp4T2U.js";import{loadDevelopmentEnvironmentFiles as t}from"../../cli/dev/environment.js";import{a as n,n as r,t as i}from"../../chunks/client-CKsU8Li3.js";import{n as a}from"../../chunks/host-DREC8e8Z.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};
@@ -6,7 +6,7 @@ type VercelSandboxModule = typeof VercelSandboxSdk;
6
6
  /**
7
7
  * User-controllable subset of `Sandbox.create` parameters.
8
8
  */
9
- export type VercelSandboxCreateOptions = Omit<NonNullable<Parameters<typeof SdkSandbox.create>[0]>, "name" | "persistent" | "source" | "signal">;
9
+ export type VercelSandboxCreateOptions = Omit<NonNullable<Parameters<typeof SdkSandbox.create>[0]>, "name" | "persistent" | "signal">;
10
10
  /**
11
11
  * Construction input for {@link createVercelSandboxBackend}. Internal —
12
12
  * the public surface is the `vercelBackend()` factory under
@@ -115,7 +115,21 @@ async function ensureTemplate(input) {
115
115
  else {
116
116
  await ensureVercelSandboxTags(sandbox, tags);
117
117
  }
118
- if (typeof sandbox.currentSnapshotId === "string" && sandbox.currentSnapshotId.length > 0) {
118
+ /*
119
+ * A non-empty `currentSnapshotId` normally means "this template was
120
+ * prewarmed in a previous run — reuse it." But with an author-supplied
121
+ * `source: snapshot`, the SDK pre-populates `currentSnapshotId` with
122
+ * the *author's* snapshotId both on a fresh create and on every
123
+ * subsequent `getNamedSandbox` reuse until we run our own snapshot.
124
+ * So we ignore that exact value: it's the author's base layer, not a
125
+ * framework snapshot, and we still owe `ensureSandboxWorkingDirectory`,
126
+ * bootstrap, seed file writes, and `sandbox.snapshot()` on top.
127
+ */
128
+ const authorSnapshotId = extractAuthorSnapshotId(input.createOptions);
129
+ const hasFrameworkSnapshot = typeof sandbox.currentSnapshotId === "string" &&
130
+ sandbox.currentSnapshotId.length > 0 &&
131
+ sandbox.currentSnapshotId !== authorSnapshotId;
132
+ if (hasFrameworkSnapshot) {
119
133
  return {
120
134
  sandboxName: sandbox.name,
121
135
  snapshotId: sandbox.currentSnapshotId,
@@ -156,11 +170,16 @@ async function ensureSession(input) {
156
170
  await ensureVercelSandboxTags(existing, input.tags);
157
171
  return existing;
158
172
  }
159
- // The Vercel SDK rejects `runtime` when `source` is a snapshot — the
160
- // runtime is already baked into the snapshot's filesystem. Strip it
161
- // from the consumer-supplied create options for the session path
162
- // only; template prewarm still honors `runtime`.
163
- const { runtime: _runtime, ...sessionCreateOptions } = input.createOptions;
173
+ /*
174
+ * Strip both `source` and `runtime` from author-supplied create
175
+ * options for the session path. The framework owns the session
176
+ * source sessions always derive from the prewarmed template's
177
+ * snapshot, never the author's external source. And the Vercel SDK
178
+ * rejects `runtime` when `source` is a snapshot because the runtime
179
+ * is already baked into the snapshot's filesystem. Template prewarm
180
+ * still honors both fields.
181
+ */
182
+ const { runtime: _runtime, source: _source, ...sessionCreateOptions } = input.createOptions;
164
183
  const createParams = {
165
184
  ...sessionCreateOptions,
166
185
  name: sandboxName,
@@ -276,6 +295,19 @@ function isSandboxMissingError(error) {
276
295
  error.cause?.response?.status;
277
296
  return status === 404;
278
297
  }
298
+ /**
299
+ * Pulls the snapshotId out of an author-supplied `source: { type:
300
+ * "snapshot", ... }`. Returns undefined for git/tarball sources or when
301
+ * no source was supplied — those don't seed `currentSnapshotId` with a
302
+ * pre-existing value the way snapshot sources do.
303
+ */
304
+ function extractAuthorSnapshotId(createOptions) {
305
+ const source = createOptions.source;
306
+ if (source?.type === "snapshot" && typeof source.snapshotId === "string") {
307
+ return source.snapshotId;
308
+ }
309
+ return undefined;
310
+ }
279
311
  function getVercelSandboxName(metadata) {
280
312
  const sandboxName = metadata?.sandboxName;
281
313
  return typeof sandboxName === "string" ? sandboxName : undefined;
@@ -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.22.1";
9
+ const BUNDLED_FALLBACK_PACKAGE_VERSION = "0.22.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",
@@ -22,12 +22,12 @@ function normalizeEntrypoint(rootDir, entrypoint) {
22
22
  }
23
23
  return resolve(rootDir, entrypoint);
24
24
  }
25
- function isNextAshExperimentalServicesConfig(input) {
25
+ function resolveNextAshServicePrefix(input) {
26
26
  if (!isRecord(input.config) || !isRecord(input.config.experimentalServices)) {
27
- return false;
27
+ return undefined;
28
28
  }
29
29
  let hasNextService = false;
30
- let hasMatchingAshService = false;
30
+ let servicePrefix;
31
31
  for (const service of Object.values(input.config.experimentalServices)) {
32
32
  if (!isRecord(service)) {
33
33
  continue;
@@ -42,23 +42,24 @@ function isNextAshExperimentalServicesConfig(input) {
42
42
  const ashEntrypoint = normalizeEntrypoint(input.configRoot, service.entrypoint);
43
43
  const routePrefix = typeof service.routePrefix === "string" ? service.routePrefix.trim() : "";
44
44
  if (ashEntrypoint === input.appRoot && routePrefix.length > 0 && routePrefix !== "/") {
45
- hasMatchingAshService = true;
45
+ servicePrefix = routePrefix;
46
46
  }
47
47
  }
48
- return hasNextService && hasMatchingAshService;
48
+ return hasNextService ? servicePrefix : undefined;
49
49
  }
50
- async function shouldNormalizeVercelFunctionOutputForNextService(appRoot) {
50
+ async function resolveNextAshServicePrefixForVercelFunctionOutput(appRoot) {
51
51
  let currentDir = appRoot;
52
52
  while (true) {
53
53
  try {
54
54
  const configPath = join(currentDir, "vercel.json");
55
55
  const config = JSON.parse(await readFile(configPath, "utf8"));
56
- if (isNextAshExperimentalServicesConfig({
56
+ const servicePrefix = resolveNextAshServicePrefix({
57
57
  appRoot,
58
58
  configRoot: currentDir,
59
59
  config,
60
- })) {
61
- return true;
60
+ });
61
+ if (servicePrefix !== undefined) {
62
+ return servicePrefix;
62
63
  }
63
64
  }
64
65
  catch (error) {
@@ -68,7 +69,7 @@ async function shouldNormalizeVercelFunctionOutputForNextService(appRoot) {
68
69
  }
69
70
  const parentDir = dirname(currentDir);
70
71
  if (parentDir === currentDir) {
71
- return false;
72
+ return undefined;
72
73
  }
73
74
  currentDir = parentDir;
74
75
  }
@@ -160,8 +161,9 @@ export async function buildApplication(rootDir) {
160
161
  outputDir: outputDirectory,
161
162
  workflowBuildDir: preparedHost.workflowBuildDir,
162
163
  });
163
- if (await shouldNormalizeVercelFunctionOutputForNextService(preparedHost.appRoot)) {
164
- await normalizeAshVercelFunctionOutput(outputDirectory);
164
+ const servicePrefix = await resolveNextAshServicePrefixForVercelFunctionOutput(preparedHost.appRoot);
165
+ if (servicePrefix !== undefined) {
166
+ await normalizeAshVercelFunctionOutput(outputDirectory, { servicePrefix });
165
167
  }
166
168
  await emitVercelAgentSummary({
167
169
  manifest: preparedHost.compileResult.manifest,
@@ -0,0 +1,4 @@
1
+ export declare const ASH_SHARED_SERVER_FUNCTION_PATH = "ash/__server.func";
2
+ export declare function isAshVercelFunctionPath(path: string): boolean;
3
+ export declare function normalizeAshVercelRoutes(routes: readonly unknown[], servicePrefix: string | undefined): unknown[];
4
+ export declare function applyAshServiceRoutePrefixWrapper(functionPath: string, servicePrefix: string): Promise<void>;
@@ -0,0 +1,134 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ export const ASH_SHARED_SERVER_FUNCTION_PATH = "ash/__server.func";
4
+ const ASH_SHARED_SERVER_ROUTE_DESTINATION = "/ash/__server";
5
+ const ASH_SERVICE_ROUTE_PREFIX_WRAPPER = "index.__ash_service_route_prefix.mjs";
6
+ const ASH_VERCEL_FUNCTION_PREFIXES = ["ash/", ".well-known/workflow/"];
7
+ function isRecord(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ export function isAshVercelFunctionPath(path) {
11
+ return ASH_VERCEL_FUNCTION_PREFIXES.some((prefix) => path.startsWith(prefix));
12
+ }
13
+ export function normalizeAshVercelRoutes(routes, servicePrefix) {
14
+ return routes
15
+ .filter(isAshVercelRoute)
16
+ .map((route) => normalizeAshVercelRoute(route, servicePrefix));
17
+ }
18
+ function isAshVercelRoute(route) {
19
+ if (!isRecord(route)) {
20
+ return true;
21
+ }
22
+ if ("handle" in route) {
23
+ return true;
24
+ }
25
+ const src = typeof route.src === "string" ? route.src : "";
26
+ const dest = typeof route.dest === "string" ? route.dest : "";
27
+ return isAshVercelRoutePath(src) || isAshVercelRoutePath(dest);
28
+ }
29
+ function isAshVercelRoutePath(path) {
30
+ return path.includes("/ash/v1") || path.includes("/.well-known/workflow/");
31
+ }
32
+ function isAshProtocolRoutePath(path) {
33
+ return path.includes("/ash/v1");
34
+ }
35
+ function normalizeAshVercelRoute(route, servicePrefix) {
36
+ if (!isRecord(route) || "handle" in route || typeof route.src !== "string") {
37
+ return route;
38
+ }
39
+ const shouldUseSharedServerFunction = isAshProtocolRoutePath(route.src) ||
40
+ (typeof route.dest === "string" && isAshProtocolRoutePath(route.dest));
41
+ const nextRoute = {
42
+ ...route,
43
+ src: prefixAshVercelRoutePath(route.src, servicePrefix),
44
+ };
45
+ if (shouldUseSharedServerFunction) {
46
+ nextRoute.dest = ASH_SHARED_SERVER_ROUTE_DESTINATION;
47
+ }
48
+ return nextRoute;
49
+ }
50
+ function prefixAshVercelRoutePath(path, servicePrefix) {
51
+ if (servicePrefix === undefined ||
52
+ servicePrefix === "/" ||
53
+ !isAshVercelRoutePath(path) ||
54
+ path.includes(servicePrefix)) {
55
+ return path;
56
+ }
57
+ const normalizedPrefix = servicePrefix.endsWith("/") ? servicePrefix.slice(0, -1) : servicePrefix;
58
+ const escapedPrefix = normalizedPrefix.replaceAll("/", "\\/");
59
+ if (path.includes(escapedPrefix)) {
60
+ return path;
61
+ }
62
+ if (path.startsWith("^(?:/")) {
63
+ return `^(?:${normalizedPrefix}${path.slice(4)}`;
64
+ }
65
+ if (path.startsWith("^/")) {
66
+ return `^${normalizedPrefix}${path.slice(1)}`;
67
+ }
68
+ if (path.startsWith("/")) {
69
+ return `${normalizedPrefix}${path}`;
70
+ }
71
+ return path;
72
+ }
73
+ export async function applyAshServiceRoutePrefixWrapper(functionPath, servicePrefix) {
74
+ const configPath = join(functionPath, ".vc-config.json");
75
+ const wrapperPath = join(functionPath, ASH_SERVICE_ROUTE_PREFIX_WRAPPER);
76
+ const rawConfig = JSON.parse(await readFile(configPath, "utf8"));
77
+ const config = isRecord(rawConfig) ? rawConfig : {};
78
+ await writeFile(wrapperPath, createAshServiceRoutePrefixWrapper(servicePrefix));
79
+ await writeFile(configPath, `${JSON.stringify({
80
+ ...config,
81
+ handler: ASH_SERVICE_ROUTE_PREFIX_WRAPPER,
82
+ }, null, 2)}\n`);
83
+ }
84
+ function createAshServiceRoutePrefixWrapper(servicePrefix) {
85
+ return `
86
+ import { Server } from "node:http";
87
+
88
+ const SERVICE_PREFIX = ${JSON.stringify(normalizeServiceRoutePrefix(servicePrefix))};
89
+ const PATCH_SYMBOL = Symbol.for("ash.service.route-prefix-strip.patch");
90
+
91
+ function stripServiceRoutePrefix(requestUrl) {
92
+ if (typeof requestUrl !== "string" || requestUrl === "*") {
93
+ return requestUrl;
94
+ }
95
+
96
+ const queryIndex = requestUrl.indexOf("?");
97
+ const rawPath = queryIndex === -1 ? requestUrl : requestUrl.slice(0, queryIndex);
98
+ const query = queryIndex === -1 ? "" : requestUrl.slice(queryIndex);
99
+ const path = rawPath.startsWith("/") ? rawPath : \`/\${rawPath}\`;
100
+
101
+ if (path === SERVICE_PREFIX) {
102
+ return \`/\${query}\`;
103
+ }
104
+
105
+ if (path.startsWith(\`\${SERVICE_PREFIX}/\`)) {
106
+ return path.slice(SERVICE_PREFIX.length) + query;
107
+ }
108
+
109
+ return path + query;
110
+ }
111
+
112
+ if (!globalThis[PATCH_SYMBOL]) {
113
+ globalThis[PATCH_SYMBOL] = true;
114
+ const originalEmit = Server.prototype.emit;
115
+ Server.prototype.emit = function patchedEmit(event, request, ...args) {
116
+ if (event === "request" && request && typeof request.url === "string") {
117
+ request.url = stripServiceRoutePrefix(request.url);
118
+ }
119
+
120
+ return originalEmit.call(this, event, request, ...args);
121
+ };
122
+ }
123
+
124
+ const originalModule = await import("./index.mjs");
125
+ const entrypoint = originalModule?.default ?? originalModule;
126
+
127
+ export default entrypoint;
128
+ `.trimStart();
129
+ }
130
+ function normalizeServiceRoutePrefix(servicePrefix) {
131
+ const prefixed = servicePrefix.startsWith("/") ? servicePrefix : `/${servicePrefix}`;
132
+ const normalized = prefixed.replace(/\/+$/, "");
133
+ return normalized.length === 0 ? "/" : normalized;
134
+ }
@@ -40,7 +40,9 @@ export declare function copyNitroFunctionDirectory(input: {
40
40
  * that model by copying the shared target once into the Ash-owned tree and
41
41
  * repointing Ash route aliases at it before pruning the root target.
42
42
  */
43
- export declare function normalizeAshVercelFunctionOutput(outputDir: string): Promise<void>;
43
+ export declare function normalizeAshVercelFunctionOutput(outputDir: string, options?: {
44
+ readonly servicePrefix?: string;
45
+ }): Promise<void>;
44
46
  /**
45
47
  * Bundles one package-owned workflow handler into a standalone Vercel function
46
48
  * directory without inheriting Nitro's hosted server chunks.
@@ -1,6 +1,7 @@
1
1
  import { cp, mkdir, readdir, readFile, realpath, rename, rm, symlink, writeFile, } from "node:fs/promises";
2
2
  import { basename, dirname, extname, join, relative } from "node:path";
3
3
  import { buildWithNitroRolldown, getSingleRolldownChunk, } from "#internal/bundler/nitro-rolldown.js";
4
+ import { applyAshServiceRoutePrefixWrapper, ASH_SHARED_SERVER_FUNCTION_PATH, isAshVercelFunctionPath, normalizeAshVercelRoutes, } from "#internal/workflow-bundle/ash-service-route-output.js";
4
5
  // just-bash exposes native optional codecs for xz/zstd support. Those packages
5
6
  // are feature-gated at runtime and should stay external so workflow step
6
7
  // bundles do not try to inline platform-specific `.node` artifacts.
@@ -12,8 +13,6 @@ export const WORKFLOW_STEP_EXTERNAL_PACKAGES = ["@mongodb-js/zstd", "node-liblzm
12
13
  */
13
14
  export const WORKFLOW_BUILDER_DEFERRED_PACKAGES = ["@chat-adapter/slack", "chat"];
14
15
  const WORKFLOW_FUNCTION_NODE_OPTIONS = "--experimental-require-module";
15
- const ASH_VERCEL_FUNCTION_PREFIXES = ["ash/", ".well-known/workflow/"];
16
- const ASH_SHARED_SERVER_FUNCTION_PATH = "ash/__server.func";
17
16
  /**
18
17
  * Builds the environment block every generated Vercel workflow function needs.
19
18
  */
@@ -79,14 +78,17 @@ export async function copyNitroFunctionDirectory(input) {
79
78
  * that model by copying the shared target once into the Ash-owned tree and
80
79
  * repointing Ash route aliases at it before pruning the root target.
81
80
  */
82
- export async function normalizeAshVercelFunctionOutput(outputDir) {
81
+ export async function normalizeAshVercelFunctionOutput(outputDir, options = {}) {
83
82
  const functionsDir = join(outputDir, "functions");
84
83
  const sharedFunctionPath = await prepareSharedAshServerFunction(functionsDir);
85
84
  if (sharedFunctionPath !== null) {
85
+ if (options.servicePrefix !== undefined) {
86
+ await applyAshServiceRoutePrefixWrapper(sharedFunctionPath, options.servicePrefix);
87
+ }
86
88
  await repointAshFunctionSymlinksInDirectory(functionsDir, sharedFunctionPath);
87
89
  }
88
90
  await pruneNonAshFunctionEntries(functionsDir, functionsDir);
89
- await pruneNonAshVercelRoutes(outputDir);
91
+ await pruneNonAshVercelRoutes(outputDir, options.servicePrefix);
90
92
  }
91
93
  async function prepareSharedAshServerFunction(functionsDir) {
92
94
  const rootServerFunctionPath = join(functionsDir, "__server.func");
@@ -180,7 +182,7 @@ async function pruneNonAshFunctionEntries(functionsDir, directoryPath) {
180
182
  }
181
183
  }));
182
184
  }
183
- async function pruneNonAshVercelRoutes(outputDir) {
185
+ async function pruneNonAshVercelRoutes(outputDir, servicePrefix) {
184
186
  const configPath = join(outputDir, "config.json");
185
187
  let parsed;
186
188
  try {
@@ -195,29 +197,12 @@ async function pruneNonAshVercelRoutes(outputDir) {
195
197
  if (!isRecord(parsed) || !Array.isArray(parsed.routes)) {
196
198
  return;
197
199
  }
198
- parsed.routes = parsed.routes.filter(isAshVercelRoute);
200
+ parsed.routes = normalizeAshVercelRoutes(parsed.routes, servicePrefix);
199
201
  await writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`);
200
202
  }
201
203
  function normalizeVercelOutputPath(path) {
202
204
  return path.replaceAll("\\", "/");
203
205
  }
204
- function isAshVercelFunctionPath(path) {
205
- return ASH_VERCEL_FUNCTION_PREFIXES.some((prefix) => path.startsWith(prefix));
206
- }
207
- function isAshVercelRoute(route) {
208
- if (!isRecord(route)) {
209
- return true;
210
- }
211
- if ("handle" in route) {
212
- return true;
213
- }
214
- const src = typeof route.src === "string" ? route.src : "";
215
- const dest = typeof route.dest === "string" ? route.dest : "";
216
- return isAshVercelRoutePath(src) || isAshVercelRoutePath(dest);
217
- }
218
- function isAshVercelRoutePath(path) {
219
- return path.includes("/ash/v1") || path.includes("/.well-known/workflow/");
220
- }
221
206
  /**
222
207
  * Bundles one package-owned workflow handler into a standalone Vercel function
223
208
  * directory without inheriting Nitro's hosted server chunks.
@@ -83,10 +83,15 @@ async function resolveExistingRewrites(rewrites) {
83
83
  }
84
84
  function mergeRewriteRules(existing, ashRules) {
85
85
  if (existing === undefined) {
86
- return ashRules;
86
+ return {
87
+ beforeFiles: ashRules,
88
+ };
87
89
  }
88
90
  if (!isRewriteSections(existing)) {
89
- return [...ashRules, ...existing];
91
+ return {
92
+ afterFiles: existing,
93
+ beforeFiles: ashRules,
94
+ };
90
95
  }
91
96
  return {
92
97
  ...existing,
@@ -8,6 +8,13 @@ import type { VercelSandboxBootstrapUseOptions, VercelSandboxCreateOptions, Verc
8
8
  * (template at prewarm, session at first-time create). On resume
9
9
  * (`Sandbox.get`), no create happens, so opts are not re-applied.
10
10
  *
11
+ * `opts.source`, if supplied, is used only on the template create —
12
+ * the author's snapshot, git revision, or tarball becomes the base
13
+ * layer of the template. Bootstrap, seed files, and framework setup
14
+ * still run on top, and every session derives from the resulting
15
+ * Ash-owned snapshot. `source` is stripped from session creates so the
16
+ * framework's snapshot always wins.
17
+ *
11
18
  * `bootstrap({ use })` applies its options to the template via
12
19
  * `sandbox.update(...)`; those settings persist into the snapshot.
13
20
  * `onSession({ use })` applies its options to the live session via the
@@ -7,6 +7,13 @@ import { createVercelSandboxBackend } from "#execution/sandbox/bindings/vercel.j
7
7
  * (template at prewarm, session at first-time create). On resume
8
8
  * (`Sandbox.get`), no create happens, so opts are not re-applied.
9
9
  *
10
+ * `opts.source`, if supplied, is used only on the template create —
11
+ * the author's snapshot, git revision, or tarball becomes the base
12
+ * layer of the template. Bootstrap, seed files, and framework setup
13
+ * still run on top, and every session derives from the resulting
14
+ * Ash-owned snapshot. `source` is stripped from session creates so the
15
+ * framework's snapshot always wins.
16
+ *
10
17
  * `bootstrap({ use })` applies its options to the template via
11
18
  * `sandbox.update(...)`; those settings persist into the snapshot.
12
19
  * `onSession({ use })` applies its options to the live session via the
@@ -6,11 +6,21 @@ import type { Sandbox as SdkSandbox, SandboxUpdateParams } from "#compiled/@verc
6
6
  * session-create). Skipped on resume (`Sandbox.get`) since no create
7
7
  * happens there.
8
8
  *
9
- * Framework-injected fields (`name`, `persistent`, `source`, `signal`)
10
- * are excluded — the framework owns those and overrides any author-
11
- * supplied values.
9
+ * Framework-injected fields (`name`, `persistent`, `signal`) are
10
+ * excluded — the framework owns those and overrides any author-supplied
11
+ * values.
12
+ *
13
+ * `source` is honored only on the template create at prewarm time, so
14
+ * an author-supplied snapshot, git revision, or tarball becomes the
15
+ * base layer for the template. Bootstrap, seed files, and framework
16
+ * setup (workspace dir, ripgrep) all run on top, and the resulting
17
+ * framework-owned snapshot is what every later session derives from —
18
+ * so `source` is stripped from the session-create path. Ash does not
19
+ * detect external snapshot changes; to pick up a rebuilt external
20
+ * snapshot, force a template rebuild (e.g. by changing the sandbox
21
+ * definition so its template key changes).
12
22
  */
13
- export type VercelSandboxCreateOptions = Omit<NonNullable<Parameters<typeof SdkSandbox.create>[0]>, "name" | "persistent" | "source" | "signal">;
23
+ export type VercelSandboxCreateOptions = Omit<NonNullable<Parameters<typeof SdkSandbox.create>[0]>, "name" | "persistent" | "signal">;
14
24
  /**
15
25
  * Options accepted by the Vercel backend's `bootstrap({ use })` hook.
16
26
  * Aliases the Vercel SDK's `SandboxUpdateParams` because bootstrap
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "experimental-ash",
3
- "version": "0.22.1",
3
+ "version": "0.22.2",
4
4
  "bin": {
5
5
  "ash": "./bin/ash.js",
6
6
  "experimental-ash": "./bin/ash.js"