experimental-ash 0.20.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/docs/public/channels/README.md +3 -1
- package/dist/docs/public/hooks.md +37 -0
- package/dist/docs/public/tools.md +4 -0
- package/dist/src/chunks/{dev-authored-source-watcher-BR7XYOW0.js → dev-authored-source-watcher-XmRMDVDO.js} +1 -1
- package/dist/src/chunks/{host-Dxf7CGaE.js → host-CyC15ErG.js} +6 -6
- package/dist/src/chunks/{paths-BcM3el4Q.js → paths-BgL4fqtv.js} +4 -4
- package/dist/src/chunks/{prewarm-vAT2QBqc.js → prewarm-Om8D2hpG.js} +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/run.js +1 -1
- package/dist/src/evals/cli/eval.js +1 -1
- package/dist/src/harness/attachment-staging.js +5 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/routes/workflow-route-helpers.d.ts +4 -4
- package/dist/src/internal/nitro/routes/workflow-route-helpers.js +6 -5
- package/dist/src/internal/nitro/routes/workflow-run-events.d.ts +1 -1
- package/dist/src/internal/nitro/routes/workflow-run-events.js +1 -1
- package/dist/src/internal/nitro/routes/workflow-run-steps.d.ts +1 -1
- package/dist/src/internal/nitro/routes/workflow-run-steps.js +1 -1
- package/dist/src/internal/nitro/routes/workflow-run.d.ts +1 -1
- package/dist/src/internal/nitro/routes/workflow-run.js +1 -1
- package/dist/src/internal/nitro/routes/workflow-runs.d.ts +1 -1
- package/dist/src/internal/nitro/routes/workflow-runs.js +1 -1
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +2 -0
- package/dist/src/public/next/index.d.ts +74 -0
- package/dist/src/public/next/index.js +150 -0
- package/dist/src/public/next/server.d.ts +6 -0
- package/dist/src/public/next/server.js +348 -0
- package/dist/src/public/next/vercel-json.d.ts +8 -0
- package/dist/src/public/next/vercel-json.js +76 -0
- package/dist/src/public/tool-result-narrowing.d.ts +68 -0
- package/dist/src/public/tool-result-narrowing.js +58 -0
- package/dist/src/public/tools/index.d.ts +1 -0
- package/dist/src/public/tools/index.js +1 -0
- package/dist/src/runtime/resolve-connection.js +2 -0
- package/dist/src/runtime/resolve-tool.js +2 -0
- package/package.json +11 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# experimental-ash
|
|
2
2
|
|
|
3
|
+
## 0.21.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 261c968: Add `experimental-ash/next` with `withAsh()` for proxying Next.js Ash endpoints to a separate Ash service. The helper starts or reuses local `ash dev`, writes Next rewrites for Ash protocol routes including channel and workflow run endpoints, uses a stable local production port for serialized `next build` rewrites, and ensures Vercel `experimentalServices` are configured for the Next.js and Ash services.
|
|
8
|
+
- cc714d2: Add `toolResultFrom` for typed tool result narrowing. Import from `experimental-ash/tools` and pass an authored `ToolDefinition` to get typed output, or an `McpClientConnectionDefinition` to match any tool from that connection.
|
|
9
|
+
|
|
3
10
|
## 0.20.1
|
|
4
11
|
|
|
5
12
|
### Patch Changes
|
|
@@ -84,7 +84,9 @@ helpers. Each route handler receives the raw `Request` and a helpers object:
|
|
|
84
84
|
- `waitUntil(promise)` -- extend the request lifetime for background work.
|
|
85
85
|
|
|
86
86
|
Event handlers like `"message.completed"` are declared under the `events` key on the config object.
|
|
87
|
-
They receive `(eventData, ctx)` where `ctx` carries platform handles and `ctx.session`.
|
|
87
|
+
They receive `(eventData, ctx)` where `ctx` carries platform handles and `ctx.session`. Use
|
|
88
|
+
`toolResultFrom` from `experimental-ash/tools` to narrow tool results (see
|
|
89
|
+
[Hooks — Narrowing tool results](../hooks.md#narrowing-tool-results)).
|
|
88
90
|
|
|
89
91
|
## The Ash Channel
|
|
90
92
|
|
|
@@ -65,6 +65,43 @@ Hooks read and write durable state through `ctx.ash.set(...)` /
|
|
|
65
65
|
`ctx.ash.get(...)`. The hooks surface deliberately introduces no parallel
|
|
66
66
|
state-patch channel — one `AshContext`, one set of keys.
|
|
67
67
|
|
|
68
|
+
### Narrowing tool results
|
|
69
|
+
|
|
70
|
+
`toolResultFrom` narrows an `action.result` event to a specific authored
|
|
71
|
+
tool or MCP connection and returns typed output. Import it from
|
|
72
|
+
`experimental-ash/tools`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { defineHook } from "experimental-ash/hooks";
|
|
76
|
+
import { toolResultFrom } from "experimental-ash/tools";
|
|
77
|
+
import getWeather from "../tools/get-weather";
|
|
78
|
+
import linear from "../connections/linear";
|
|
79
|
+
|
|
80
|
+
export default defineHook({
|
|
81
|
+
events: {
|
|
82
|
+
"action.result"(event) {
|
|
83
|
+
// Authored tool — output is typed as the tool's return type
|
|
84
|
+
const weather = toolResultFrom(event.data.result, getWeather);
|
|
85
|
+
if (weather) {
|
|
86
|
+
console.log(weather.output.temperature);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// MCP connection — output is unknown, toolName is qualified
|
|
90
|
+
const linearResult = toolResultFrom(event.data.result, linear);
|
|
91
|
+
if (linearResult) {
|
|
92
|
+
console.log(linearResult.connectionToolName, linearResult.output);
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Returns `undefined` when the result doesn't match, or when `isError` is
|
|
100
|
+
`true`. For authored tools the return includes `{ output, toolName,
|
|
101
|
+
callId }` with `output` typed as the tool's `TOutput`. For connections
|
|
102
|
+
it includes `{ output, toolName, connectionToolName, callId }` with
|
|
103
|
+
`output` as `unknown`.
|
|
104
|
+
|
|
68
105
|
## Lifecycle
|
|
69
106
|
|
|
70
107
|
Lifecycle hooks share one signature:
|
|
@@ -366,6 +366,10 @@ events, regardless of whether `toModelOutput` is defined. This lets channels ren
|
|
|
366
366
|
platform-specific output (e.g. Slack Block Kit) from structured tool data that the model never
|
|
367
367
|
needs to see.
|
|
368
368
|
|
|
369
|
+
Use `toolResultFrom(result, toolDefinition)` to narrow an `action.result` to a specific tool and
|
|
370
|
+
get typed output. See [Hooks — Narrowing tool results](./hooks.md#narrowing-tool-results) for the
|
|
371
|
+
full API.
|
|
372
|
+
|
|
369
373
|
Note: `retentionPolicy` and `onCompact` operate on the projected output (what the model sees),
|
|
370
374
|
not the full `execute` return.
|
|
371
375
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as e}from"./paths-BcM3el4Q.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-vAT2QBqc.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-BgL4fqtv.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-Om8D2hpG.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-
|
|
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-BgL4fqtv.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-Om8D2hpG.js";import{builtinModules as ce}from"node:module";import{dirname as _,extname as le,isAbsolute as ue,join as v,relative as y,resolve as b,sep as de}from"node:path";import{cp as x,mkdir as S,readFile as C,readdir as fe,realpath as pe,rename as w,rm as T,writeFile as E}from"node:fs/promises";import{randomUUID as me}from"node:crypto";import{existsSync as D,readFileSync as he}from"node:fs";import{fileURLToPath as ge}from"node:url";import{build as _e,copyPublicAssets as ve,createDevServer as ye,createNitro as be,prepare as xe,prerender as Se}from"nitro/builder";import{Buffer as Ce}from"node:buffer";const we=`ash-cache.json`;async function Te(e){let t=await Ee(e),n=h().version;t!==null&&t===n||await T(e,{force:!0,recursive:!0})}async function O(e){await S(e,{recursive:!0}),await E(v(e,we),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Ee(e){try{let t=JSON.parse(await C(v(e,we),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const De=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Oe(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await ke(e.filename,e.source),n=je(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Ke(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=qe(r,t.name);i.steps??={};let c=i.steps[e.filename]??={};if(c[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;a.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(s=!0,o.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):o.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${r}//${t.name}`;i.workflows??={};let c=i.workflows[e.filename]??={};c[t.name]={workflowId:n},e.mode===`workflow`?(a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),o.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(a.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let c=`/**__internal_workflows${JSON.stringify(i)}*/;`,l=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!l)return{code:`${c}\n${Ae(e.source,t,n,r)}`,workflowManifest:i};let u=Ie(e.source,a),d=e.mode===`workflow`?await Le(e.filename,u):u;return{code:`${s?`import { registerStepFunction } from "workflow/internal/private";\n${c}\n`:`${c}\n`}${d}${o.length>0?`\n${o.join(`
|
|
2
2
|
`)}\n`:``}`,workflowManifest:i}}async function ke(e,t){let{parseAst:n}=await o();return n(t,{astType:`ts`,lang:Ge(e),range:!0,sourceType:`module`},e)}function Ae(e,t,n,r){let i=Re(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=qe(r,e.name);return`${t}var ${e.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`}),o=[...i,...a];return o.length>0?`${o.join(`
|
|
3
3
|
`)}\n`:``}function je(e){let t=[];for(let n of e.body??[]){let e=Me(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Pe(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Fe(a[0]);o!==null&&t.push({directive:o.value,directiveEnd:o.end,directiveStart:o.start,exportPrefix:e.exported?`export `:``,name:i,rangeEnd:e.end,rangeStart:e.start})}return t}function Me(e){return e.type===`FunctionDeclaration`?Ne(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Ne(e.declaration,!0,e)}function Ne(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function Pe(e){return e===void 0||Array.isArray(e)?e:e.body}function Fe(e){let t=e?.directive??(e?.type===`ExpressionStatement`&&e.expression?.type===`Literal`?e.expression.value:void 0);return t!==`use workflow`&&t!==`use step`||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function Ie(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}async function Le(e,t){let n=await ke(e,t),r=He(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=Ve(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:We(t,e.end),start:e.start,text:``})}return i.length>0?Ie(t,i):t}function Re(e,t){let n=[];for(let r of t.body??[])r.type===`ExportNamedDeclaration`&&r.declaration?.type===`VariableDeclaration`&&r.declaration.kind===`const`&&r.start!==void 0&&r.end!==void 0&&(r.declaration.declarations??[]).every(ze)&&n.push(e.slice(r.start,r.end).trim());return n}function ze(e){return Be(e.init)}function Be(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?Be(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function Ve(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function He(e){let t=new Set;return k(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function k(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Ue(e)&&k(e,t);else Ue(n)&&k(n,t)}}function Ue(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function We(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
|
|
4
4
|
`?n+2:e[n]===`
|
|
@@ -10,13 +10,13 @@ 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 xt(e.outfile,t);return}let n=s(await l({cwd:e.workingDir,input:ot,external:e=>e===`@aws-sdk/credential-provider-web-identity`,platform:`node`,plugins:[ft(t)],write:!1,output:{comments:!1,format:e.format,sourcemap:!1}}),`final workflow bundle for "${e.outfile}"`);await xt(e.outfile,n.code)}function _t(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={stepId:i.stepId}}return t}function vt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={graph:{edges:[],nodes:[]},workflowId:i.workflowId}}return t}function yt(e){let t={};for(let[n,r]of Object.entries(e??{})){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]={classId:i.classId}}return t}function bt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`./`)||n.startsWith(`../`)?n:`./${n}`}function I(e){for(let t of e)if(D(t))return{id:b(t)}}async function xt(e,t){await S(_(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await E(n,t),await w(n,e)}function St(e,t){e.steps=L(e.steps,t.steps),e.workflows=L(e.workflows,t.workflows),e.classes=L(e.classes,t.classes)}function L(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function Ct(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function wt(e){return/\.(?:[cm]?[jt]sx?)$/.test(e)}async function R(e,t){let n=`${e}.tmp-${process.pid}-${Date.now().toString(36)}`;await E(n,t),await Tt(n,e)}async function Tt(e,t){if(process.platform!==`win32`){await w(e,t);return}for(let n=0;n<10;n+=1)try{await w(e,t);return}catch(e){if(!(e instanceof Error&&`code`in e&&(e.code===`EPERM`||e.code===`EACCES`||e.code===`EBUSY`))||n===9)throw e;await new Promise(e=>setTimeout(e,10*(n+1)))}}async function Et(e){let t=[...e.discoveredEntries.discoveredSteps].sort(),n=new Set(t),r=[...e.discoveredEntries.discoveredSerdeFiles].sort().filter(e=>!n.has(e)),i=await Ot({projectRoot:e.projectRoot,stepFiles:t,serdeOnlyFiles:r,workingDir:e.workingDir}),a=_(e.outfile),o=[`// Generated by Ash. Do not edit by hand.`,...Dt({builtinsImportSpecifier:e.builtinsPath===void 0?`workflow/internal/builtins`:z({outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,targetPath:e.builtinsPath}),outfileDirectory:a,preferAbsoluteFileImports:e.preferAbsoluteFileImports??!1,serdeOnlyFiles:r,stepFiles:t}),`export const __steps_registered = true;`,``].join(`
|
|
13
|
-
`);return await S(a,{recursive:!0}),await Mt(e.outfile)!==o&&await E(e.outfile,o),i}function Dt(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function z(e){return e.preferAbsoluteFileImports?t(e.targetPath):jt(e.outfileDirectory,e.targetPath)}async function Ot(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await C(r,`utf8`);kt(t,(await j(At(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function kt(e,t){e.steps=B(e.steps,t.steps),e.workflows=B(e.workflows,t.workflows),e.classes=B(e.classes,t.classes)}function B(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function At(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function jt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Mt(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const Nt=[`@mongodb-js/zstd`,`node-liblzma`],Pt=[`@chat-adapter/slack`,`chat`];function Ft(e){let t={};return It(e)&&Object.assign(t,e),t}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Lt(e){await T(e,{force:!0,recursive:!0}),await S(e,{recursive:!0})}async function Rt(e){try{return await pe(e.sourcePath)}catch{return await pe(e.fallbackPath)}}async function zt(e){let t=await Rt({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await Lt(e.targetPath),await x(t,e.targetPath,{dereference:!0,recursive:!0})}function Bt(e){let t=y(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function Vt(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
|
|
13
|
+
`);return await S(a,{recursive:!0}),await Mt(e.outfile)!==o&&await E(e.outfile,o),i}function Dt(e){return[e.builtinsImportSpecifier,...e.stepFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t})),...e.serdeOnlyFiles.map(t=>z({outfileDirectory:e.outfileDirectory,preferAbsoluteFileImports:e.preferAbsoluteFileImports,targetPath:t}))].map(e=>`import ${JSON.stringify(e)};`)}function z(e){return e.preferAbsoluteFileImports?t(e.targetPath):jt(e.outfileDirectory,e.targetPath)}async function Ot(e){let t={},n=[...e.stepFiles,...e.serdeOnlyFiles];for(let r of n){let n=await C(r,`utf8`);kt(t,(await j(At(e.workingDir,r),n,`step`,r,e.projectRoot)).workflowManifest)}return t}function kt(e,t){e.steps=B(e.steps,t.steps),e.workflows=B(e.workflows,t.workflows),e.classes=B(e.classes,t.classes)}function B(e,t){if(t===void 0)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]={...n[e],...r};return n}function At(e,t){let n=t.replaceAll(`\\`,`/`),r=y(e.replaceAll(`\\`,`/`),n).replaceAll(`\\`,`/`);return r.startsWith(`../`)&&(r=r.split(`/`).filter(e=>e!==`..`).join(`/`)),r}function jt(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function Mt(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}const Nt=[`@mongodb-js/zstd`,`node-liblzma`],Pt=[`@chat-adapter/slack`,`chat`];function Ft(e){let t={};return It(e)&&Object.assign(t,e),t.NODE_OPTIONS=`--experimental-require-module`,t}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Lt(e){await T(e,{force:!0,recursive:!0}),await S(e,{recursive:!0})}async function Rt(e){try{return await pe(e.sourcePath)}catch{return await pe(e.fallbackPath)}}async function zt(e){let t=await Rt({fallbackPath:e.fallbackPath,sourcePath:e.sourcePath});await Lt(e.targetPath),await x(t,e.targetPath,{dereference:!0,recursive:!0})}function Bt(e){let t=y(e.fromDirectoryPath,e.toFilePath).replaceAll(`\\`,`/`);return t.startsWith(`.`)?t:`./${t}`}function Vt(e){return[`import nitroHandler from ${JSON.stringify(e.delegateImportPath)};`,``,`function invokeNitroHandler(request, context) {`,` if (typeof nitroHandler === "function") {`,` return nitroHandler(request, context);`,` }`,``,` if (nitroHandler !== null && typeof nitroHandler === "object" && "fetch" in nitroHandler) {`,` const fetch = nitroHandler.fetch;`,` if (typeof fetch === "function") {`,` return fetch.call(nitroHandler, request, context);`,` }`,` }`,``,` throw new TypeError("Expected Nitro handler to export a function or an object with fetch(request, context).");`,`}`,``,`const workflowRoutePath = ${JSON.stringify(e.workflowRoutePath)};`,``,`function rewriteRequestToWorkflowRoute(request) {`,` const sourceUrl = new URL(request.url);`,` const routedUrl = new URL(workflowRoutePath, sourceUrl);`,` routedUrl.search = sourceUrl.search;`,` return new Request(routedUrl, request);`,`}`,``,`export default {`,` fetch(request, context) {`,` return invokeNitroHandler(rewriteRequestToWorkflowRoute(request), context);`,` },`,`};`,``].join(`
|
|
14
14
|
`)}async function Ht(e){try{let t=JSON.parse(await C(v(e,`.vc-config.json`),`utf8`));if(typeof t.handler==`string`&&t.handler.length>0)return t.handler}catch{}return`index.mjs`}async function Ut(e){let t=await Ht(e.functionDirectoryPath),n=v(e.functionDirectoryPath,t),r=_(n),i=le(t),a=v(r,`__ash_nitro_handler__${i.length>0?i:`.mjs`}`),o=Bt({fromDirectoryPath:r,toFilePath:a});await w(n,a),await E(n,Vt({delegateImportPath:o,workflowRoutePath:e.workflowRoutePath}))}const Wt=new Map;var Gt=class{#e;#t;config;#n=new WeakMap;constructor(e){this.config={buildTarget:`standalone`,dirs:[m(`src/execution`)],externalPackages:[...Nt,...Pt],projectRoot:e.appRoot,watch:e.watch,workingDir:e.rootDir},this.#e=e.compiledArtifactsBootstrapPath,this.#t=e.outDir}async build(e={}){let t=(Wt.get(this.#t)??Promise.resolve()).then(()=>this.#r(e));Wt.set(this.#t,t.catch(()=>{})),await t}async#r(e){await Te(this.#t);let t=await this.#i();if(t.length===0)throw Error(`Expected the execution workflow source file under "${m(`src/execution`)}".`);let n=await this.findTsConfigPath();await S(this.#t,{recursive:!0});let r=await this.discoverEntries(t,this.#t,n),i=v(this.#t,`workflows.mjs`),{manifest:a}=await this.createWorkflowsBundle({discoveredEntries:r,keepInterimBundleContext:!1,outfile:i,bundleFinalOutput:!1,format:`esm`,inputFiles:t,tsconfigPath:n}),o=v(this.#t,`steps.mjs`),s=await Et({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:o,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),c=e.nitroStepOutfile;c!==void 0&&c!==o&&await Et({builtinsPath:u(`workflow/internal/builtins`),discoveredEntries:r,outfile:c,preferAbsoluteFileImports:!0,projectRoot:this.config.projectRoot??this.config.workingDir,workingDir:this.config.workingDir}),await Kt(i,o),await qt(i),await Jt(i);let l=e.nitroWorkflowOutfile;l!==void 0&&l!==i&&(await S(_(l),{recursive:!0}),await tn(i,l),c!==void 0&&(await Kt(l,c),await qt(l),await Jt(l))),await this.createManifest({workflowBundlePath:v(this.#t,`workflows.mjs`),manifestDir:this.#t,manifest:{steps:{...s.steps,...a.steps},workflows:{...s.workflows,...a.workflows},classes:{...s.classes,...a.classes}}}),await O(this.#t)}get transformProjectRoot(){return this.config.projectRoot??this.config.workingDir}async findTsConfigPath(){let e=this.config.workingDir;for(;;){for(let t of[`tsconfig.json`,`jsconfig.json`]){let n=v(e,t);try{return await C(n),n}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}}let t=_(e);if(t===e)return;e=t}}async getInputFiles(){let e=this.config.dirs.map(e=>b(this.config.workingDir,e));return(await Promise.all(e.map(e=>ut(e)))).flat()}async discoverEntries(e,t,n){let r=this.#n.get(e);if(r!==void 0)return r;let i={discoveredSerdeFiles:[],discoveredSteps:[],discoveredWorkflows:[]};for(let t of e){let e=Xe(await C(t,`utf8`));e.hasUseStep&&i.discoveredSteps.push(t),e.hasUseWorkflow&&i.discoveredWorkflows.push(t),e.hasSerde&&i.discoveredSerdeFiles.push(t)}return this.#n.set(e,i),i}async createWorkflowsBundle({bundleFinalOutput:e=!0,discoveredEntries:t,format:n=`cjs`,inputFiles:r,keepInterimBundleContext:i=this.config.watch,outfile:a,tsconfigPath:o}){let c=t??await this.discoverEntries(r,_(a),o),u=[...c.discoveredWorkflows].sort(),d=new Set(u),f=[...c.discoveredSerdeFiles].sort().filter(e=>!d.has(e)),p={},m=[...u.map(e=>dt(e,this.config.workingDir)),...f.map(e=>dt(e,this.config.workingDir))].join(`
|
|
15
15
|
`);return await gt({bundleFinalOutput:e,code:s(await l({cwd:this.config.workingDir,input:ot,platform:`neutral`,plugins:[ft(m),pt(),mt(this.config.workingDir,{workflowCondition:!0}),ht({manifest:p,projectRoot:this.transformProjectRoot,sideEffectFiles:[...u,...f],workingDir:this.config.workingDir})],resolve:{conditionNames:[`ash-source`,`workflow`,`node`,`import`,`default`],extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`],mainFields:[`module`,`main`]},tsconfig:o??!1,write:!1,output:{banner:`globalThis.__private_workflows = new Map();`,codeSplitting:!1,comments:!1,format:`cjs`,sourcemap:`inline`}}),`intermediate workflow bundle for "${a}"`).code,format:n,outfile:a,workingDir:this.config.workingDir}),i?{bundleFinal:async t=>{await gt({bundleFinalOutput:e,code:t,format:n,outfile:a,workingDir:this.config.workingDir})},interimBundleCtx:void 0,manifest:p}:{manifest:p}}async createManifest({manifest:e,manifestDir:t}){let n={version:`1.0.0`,steps:_t(e.steps),workflows:vt(e.workflows),classes:yt(e.classes)},r=JSON.stringify(n,null,2);return await S(t,{recursive:!0}),await E(v(t,`manifest.json`),r),r}async buildVercelOutput(e){await this.build();let t=v(this.#t,`vercel-build-output`,`functions`,`.well-known`,`workflow`,`v1`),n=v(t,`flow.func`),r=v(e.outputDir,`functions`,`.well-known`,`workflow`,`v1`),i=v(e.flowNitroOutputDir,`functions`,`__server.func`),a=v(e.flowNitroOutputDir,`functions`,`.well-known`,`workflow`,`v1`,`flow.func`),o=v(r,`flow.func`),s=v(r,`step.func`),c=v(r,`webhook`,`[token].func`);await zt({fallbackPath:i,sourcePath:a,targetPath:n}),await Promise.all([this.#a(n,{experimentalTriggers:Array.from([Je]),maxDuration:`max`,runtime:e.runtime??null,shouldAddHelpers:!1}),x(v(this.#t,`manifest.json`),v(t,`manifest.json`))]),await Ut({functionDirectoryPath:n,workflowRoutePath:`/.well-known/workflow/v1/flow`}),await Promise.all([T(o,{force:!0,recursive:!0}),T(s,{force:!0,recursive:!0}),T(c,{force:!0,recursive:!0})]),await S(r,{recursive:!0}),await Promise.all([x(n,o,{recursive:!0}),x(v(t,`manifest.json`),v(r,`manifest.json`))])}async#i(){return[...await this.getInputFiles(),this.#e]}async#a(e,t){let n=v(e,`.vc-config.json`),r=await this.#o(n),i={...r};i.environment=Ft(r.environment),t.runtime!==null&&(i.runtime=t.runtime),t.maxDuration!==void 0&&(i.maxDuration=t.maxDuration),t.shouldAddHelpers!==void 0&&(i.shouldAddHelpers=t.shouldAddHelpers),t.shouldAddSourcemapSupport!==void 0&&(i.shouldAddSourcemapSupport=t.shouldAddSourcemapSupport),t.experimentalTriggers!==void 0&&(i.experimentalTriggers=[...t.experimentalTriggers]),await E(n,`${JSON.stringify(i,null,2)}\n`)}async#o(e){try{let t=JSON.parse(await C(e,`utf8`));if(typeof t==`object`&&t)return t}catch{}return{}}};async function Kt(e,t){let n=await V(e);if(n===null||n.includes(`__ashWorkflowStepsRegistered`))return;let r=$t(_(e),t),i=[`import { __steps_registered as __ashWorkflowStepsRegistered } from ${JSON.stringify(r)};`,`void __ashWorkflowStepsRegistered;`,``].join(`
|
|
16
16
|
`),a=n.match(/^import\s.+?;\n/m);if(a===null||a.index===void 0){await R(e,`${i}${n}`);return}let o=a.index+a[0].length;await R(e,`${n.slice(0,o)}${i}${n.slice(o)}`)}async function qt(e){let t=await V(e);if(t===null)return;let n=t;for(let e of[`workflow`,`workflow/api`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`]){let t=Qt(u(e));n=Zt(n,e,t)}n!==t&&await R(e,n)}async function Jt(e){let t=await V(e);if(t===null)return;let n=t.indexOf(`const workflowCode = `),r=t.lastIndexOf(`;
|
|
17
17
|
|
|
18
18
|
export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)return;let i=n+21,a=t.slice(i,r);if(!a.trimStart().startsWith("`"))return;let o=Xt(a,e),s=`${t.slice(0,i)}${Yt(o)}${t.slice(r)}`;s!==t&&await R(e,s)}function Yt(e){let t=Ce.from(e,`utf8`).toString(`base64`).match(/.{1,16384}/g)??[``];return`Buffer.from(${JSON.stringify(t)}.join(""), "base64").toString("utf8")`}function Xt(e,t){let n=e.trim();if(!n.startsWith("`")||!n.endsWith("`"))throw Error(`Expected generated workflow code literal in "${t}" to be a template.`);let r=n.slice(1,-1),i=``;for(let e=0;e<r.length;e+=1){let t=r[e];if(t!==`\\`){i+=t;continue}let n=r[e+1];if(n===`\\`||n==="`"||n===`$`){i+=n,e+=1;continue}i+=t}return i}function Zt(e,t,n){return e.replaceAll(JSON.stringify(t),JSON.stringify(n)).replaceAll(`'${t}'`,JSON.stringify(n))}function Qt(e){return t(e)}function $t(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function V(e){try{return await C(e,`utf8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function en(e){try{return await C(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}async function tn(e,t){let n=await C(e),r=await en(t);r!==null&&r.equals(n)||await R(t,n)}const nn=`\0ash-pruned-local-sandbox-backend`,rn=/[/\\]bindings[/\\]local\.js$/;function an(){return{name:`ash-hosted-sandbox-backend-prune`,load(e){return e===nn?[`export function createLocalSandboxBackend() {`,` throw new Error("The local sandbox backend is pruned from hosted server bundles.");`,`}`,``].join(`
|
|
19
|
-
`):null},resolveId(e){return rn.test(e)?nn:null}}}function
|
|
20
|
-
`)}function W(e){return v(e.options.buildDir,`workflow`)}function
|
|
21
|
-
`)}function
|
|
22
|
-
`)}async function fn(e,n,r){if(sn(r.surface)){let t=f(),i=new Gt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:H(r.surface)?v(W(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&H(r.surface)?v(W(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});on(r.surface)&&(U(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),U(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),dn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=W(e),o=H(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await ln(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function pn(){return`${g}/cron/${me()}`}function mn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=pn())}function hn(e){return{plugins:[c(),...e]}}function gn(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 _n=`@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 yn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],bn=Symbol(`ash.workflow-transform-patched`),xn=[`@napi-rs/keyring`];function Sn(){let e={};for(let t of yn)e[t]=u(t);return e}function Cn(e){if(!e&&process.env.VERCEL)return`vercel`}function wn(e){return e===`all`||e===`app`}function G(e){return e===`all`||e===`flow`}function K(e){return G(e)}function Tn(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function En(e){let t=e.compileResult.manifest.config.build;return[...new Set([...xn,..._n,...t?.externalDependencies??[]])].filter(e=>e!==p)}function q(e){return e.replaceAll(`\\`,`/`)}function Dn(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 On(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function J(e,t){return t.startsWith(`file://`)?q(On(Dn(ge(t)))):ue(t)?q(On(Dn(t))):q(On(Dn(b(e,t))))}function kn(e,t){let n=q(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function An(e){let t=q(e);return process.platform===`win32`?t.toLowerCase():t}function jn(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 Mn(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of jn(n)){let n=Y(t,i,e);n!==null&&r.add(An(n))}return r}async function Nn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Mn(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 Pn(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 Fn(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=>kn(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function In(e,t){let n=null,r=async()=>(n===null&&(n=await Mn(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(An(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Ln(e,t){let n=null,r=async()=>(n===null&&(n=await Mn(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(An(a))?{code:(await j(Pn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function Rn(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 zn(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[bn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return kn(t,n)?null:r.call(this,e,t,...i)},t[bn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&wn(r)&&e.scheduleRegistrations.length>0,o=Cn(t),s=o===`vercel`?an():null,c=s===null?[]:[s],l=hn(c),u=hn(c),f=En(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Te(p);let g=await be({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:K(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:vn(o===`vercel`&&wn(r))},t?{watch:!0}:void 0);if(await O(p),gn(g),G(r)){let t=Sn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Fn(g,e.workflowBuildDir),zn(g,e.workflowBuildDir)}if(K(r)){let t=Tn(g,e);In(g,{stepEntrypointPath:t}),Ln(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&Rn(g,e.compiledArtifacts.instrumentationSourcePath),t&&G(r)){let t=e.workflowBuildDir,n=new Set([q(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(q(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(mn(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}),K(r)&&await Nn(g,Tn(g,e)),g}function Bn(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 Vn(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?Wn(t.instructions):null,schedules:t.schedules.map(Gn),tools:t.tools.map(Kn),skills:t.skills.map(qn),connections:t.connections.map(Jn),channels:t.channels.filter(Un).map(Yn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Xn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Hn(e){let t=Vn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await E(n,`${JSON.stringify(t,null,2)}\n`),n}function Un(e){return e.kind===`channel`}function Wn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Gn(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Kn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function qn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Jn(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 Yn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Bn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Xn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Zn(){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 Qn(e){return Zn()?(await se(e),!0):!1}function $n(e){return e.replace(/[\\/]+$/,``)}async function er(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function tr(e){let t=new Gt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await er(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function nr(e){let t=$n(e.options.output.dir);return await Te(t),await xe(e),await ve(e),await Se(e),await _e(e),await O(t),t}async function rr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await nr(n)}finally{await n.close()}}async function ir(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await nr(e);return await Hn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await nr(n);await Qn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await rr(t,`flow`);return await tr({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Hn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,ar=new Set([`[::]`,`::`,`0.0.0.0`]);function or(e){let t=new URL(e);return ar.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function sr(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function cr(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 lr(){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 ur(e){let t=cr(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 dr(e){let t=process.env[Q],n=process.env[$],r=new URL(or(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 fr(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function pr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=fr(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function mr(e){let t=ur({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(()=>{}),!sr(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 hr(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=ye(i);pr(a);let o=t.host??i.options.devServer.hostname,s=t.port??lr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await mr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=dr(e.url),await xe(i),await _e(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-BR7XYOW0.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:or(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var gr=e({buildHost:()=>_r,startHost:()=>vr});async function _r(e){return await ir(e)}async function vr(e,t={}){return await hr(e,t)}export{vr as n,gr as t};
|
|
19
|
+
`):null},resolveId(e){return rn.test(e)?nn:null}}}const on=`${g}/runs`,sn=`${g}/runs/:runId`,cn=`${g}/runs/:runId/steps`,ln=`${g}/runs/:runId/events`;function un(e){return e===`all`||e===`app`}function dn(e){return H(e)}function H(e){return e===`all`||e===`flow`}function U(e,t){let r=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,i=n(t.handlerPath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import handler from ${i};`,`export default handler;`].join(`
|
|
20
|
+
`)}function W(e){return v(e.options.buildDir,`workflow`)}function fn(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function pn(e,t){let n=v(W(e),`${t.bundleName}-handler.mjs`),r=_(n),i=fn(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=fn(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await E(n,mn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function mn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = await __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
21
|
+
`)}function hn(e,t){let r=`#ash-route${t.route}`,i=n(t.modulePath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import { ${t.handlerExport} } from ${i};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
22
|
+
`)}async function gn(e,n,r){if(dn(r.surface)){let t=f(),i=new Gt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:H(r.surface)?v(W(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&H(r.surface)?v(W(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});un(r.surface)&&(U(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),U(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),hn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:on}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:sn}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:cn}),U(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:ln}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=W(e),o=H(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await pn(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function _n(){return`${g}/cron/${me()}`}function vn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=_n())}function yn(e){return{plugins:[c(),...e]}}function bn(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const xn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function Sn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const Cn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],wn=Symbol(`ash.workflow-transform-patched`),Tn=[`@napi-rs/keyring`];function En(){let e={};for(let t of Cn)e[t]=u(t);return e}function Dn(e){if(!e&&process.env.VERCEL)return`vercel`}function On(e){return e===`all`||e===`app`}function G(e){return e===`all`||e===`flow`}function K(e){return G(e)}function kn(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function An(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Tn,...xn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function q(e){return e.replaceAll(`\\`,`/`)}function jn(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Mn(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function J(e,t){return t.startsWith(`file://`)?q(Mn(jn(ge(t)))):ue(t)?q(Mn(jn(t))):q(Mn(jn(b(e,t))))}function Nn(e,t){let n=q(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function Pn(e){let t=q(e);return process.platform===`win32`?t.toLowerCase():t}function Fn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function Y(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?J(n===void 0?e:_(J(e,n)),t):null}async function In(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of Fn(n)){let n=Y(t,i,e);n!==null&&r.add(Pn(n))}return r}async function Ln(e,t){if(e.options.noExternals===!0)return;let n;try{n=await In(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Rn(e,t){let n=q(e).replace(/\/$/,``),r=q(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function zn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>J(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=Y(e.options.rootDir,t,r)??J(e.options.rootDir,t);return n.some(e=>Nn(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Bn(e,t){let n=null,r=async()=>(n===null&&(n=await In(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=Y(e.options.rootDir,t,n);return i===null||!(await r()).has(Pn(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Vn(e,t){let n=null,r=async()=>(n===null&&(n=await In(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=J(e.options.rootDir,n);return i.has(Pn(a))?{code:(await j(Rn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function Hn(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return q(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Un(e,t){let n=q(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[wn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return Nn(t,n)?null:r.call(this,e,t,...i)},t[wn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&On(r)&&e.scheduleRegistrations.length>0,o=Dn(t),s=o===`vercel`?an():null,c=s===null?[]:[s],l=yn(c),u=yn(c),f=An(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await Te(p);let g=await be({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:K(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:Sn(o===`vercel`&&On(r))},t?{watch:!0}:void 0);if(await O(p),bn(g),G(r)){let t=En();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;zn(g,e.workflowBuildDir),Un(g,e.workflowBuildDir)}if(K(r)){let t=kn(g,e);Bn(g,{stepEntrypointPath:t}),Vn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&Hn(g,e.compiledArtifacts.instrumentationSourcePath),t&&G(r)){let t=e.workflowBuildDir,n=new Set([q(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(q(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(vn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await gn(g,e,{surface:r}),K(r)&&await Ln(g,kn(g,e)),g}function Wn(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}function Gn(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:2,generatorVersion:e.generatorVersion??h().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?Jn(t.instructions):null,schedules:t.schedules.map(Yn),tools:t.tools.map(Xn),skills:t.skills.map(Zn),connections:t.connections.map(Qn),channels:t.channels.filter(qn).map($n),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(er),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Kn(e){let t=Gn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await E(n,`${JSON.stringify(t,null,2)}\n`),n}function qn(e){return e.kind===`channel`}function Jn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Yn(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Xn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Zn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Qn(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type:`mcp`};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function $n(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Wn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function er(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function tr(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function nr(e){return tr()?(await se(e),!0):!1}function rr(e){return e.replace(/[\\/]+$/,``)}async function ir(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function ar(e){let t=new Gt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await ir(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function or(e){let t=rr(e.options.output.dir);return await Te(t),await xe(e),await ve(e),await Se(e),await _e(e),await O(t),t}async function sr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await or(n)}finally{await n.close()}}async function cr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await or(e);return await Kn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await or(n);await nr({appRoot:t.appRoot,log(e){console.log(e)}});let r=await sr(t,`flow`);return await ar({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Kn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,lr=new Set([`[::]`,`::`,`0.0.0.0`]);function ur(e){let t=new URL(e);return lr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function dr(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function fr(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function pr(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function mr(e){let t=fr(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function hr(e){let t=process.env[Q],n=process.env[$],r=new URL(ur(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function gr(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function _r(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=gr(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function vr(e){let t=mr({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!dr(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function yr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=ye(i);_r(a);let o=t.host??i.options.devServer.hostname,s=t.port??pr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await vr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=hr(e.url),await xe(i),await _e(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-XmRMDVDO.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:ur(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var br=e({buildHost:()=>xr,startHost:()=>Sr});async function xr(e){return await cr(e)}async function Sr(e,t={}){return await yr(e,t)}export{Sr as n,br as t};
|
|
@@ -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 Ys=[`GET`,`POST`];function Xs(){return Ys.map(e=>Qs(e))}function Zs(){return new Set(Ys.map($s))}function Qs(e){let t=$s(e);return{name:t,method:e,urlPath:se,fetch:ec,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function $s(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function ec(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 tc(e);try{await Ee(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return Js()}async function tc(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 nc(){let e=Rs({auth:ic()}),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(...Xs()),t}function rc(){return new Set([`ash`,...Zs()])}function ic(){return process.env.VERCEL?bs():vs()}const ac=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:oc,...sc}=y.toJSONSchema(ac),cc={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:sc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function K(){let e=B().get(
|
|
65
|
+
</html>`,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`},status:200})}const Ys=[`GET`,`POST`];function Xs(){return Ys.map(e=>Qs(e))}function Zs(){return new Set(Ys.map($s))}function Qs(e){let t=$s(e);return{name:t,method:e,urlPath:se,fetch:ec,logicalPath:`framework://channels/${t}`,sourceId:`ash:framework:connection-callback-${e.toLowerCase()}`,sourceKind:`module`}}function $s(e){return`.well-known/ash/v1/connections/callback/${e.toLowerCase()}`}async function ec(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 tc(e);try{await Ee(r,i)}catch{return Response.json({error:`Connection callback not pending.`,ok:!1},{status:404})}return Js()}async function tc(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 nc(){let e=Rs({auth:ic()}),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(...Xs()),t}function rc(){return new Set([`ash`,...Zs()])}function ic(){return process.env.VERCEL?bs():vs()}const ac=oe.omit({action:!0,display:!0,requestId:!0}),{$schema:oc,...sc}=y.toJSONSchema(ac),cc={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:sc,logicalPath:`ash:framework/ask-question`,name:`ask_question`,sourceId:`ash:ask-question-tool`,sourceKind:`module`};async function K(){let e=B().get(id);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 lc(e){if(!e.startsWith(`/`))throw Error(`filePath must be an absolute path. Received: "${e}". Use an absolute path such as /workspace/foo.ts.`)}function uc(e){return fc(e,`head`)}function dc(e){return fc(e,`tail`)}function fc(e,t){let n=e.split(`
|
|
66
66
|
`),r=mc(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=pc(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 pc(e){return e.length<=2e3?e:e.slice(0,2e3)+` [truncated]`}function mc(e){return e.length>0&&e[e.length-1]===``?e.length-1:e.length}async function hc(e){let t=await(await K()).runCommand({command:e.command}),n=dc(t.stdout),r=dc(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 gc={additionalProperties:!1,properties:{command:{description:`The shell command to execute.`,type:`string`}},required:[`command`],type:`object`};async function _c(e){return hc(e)}const vc={description:`Execute a shell command in the shared workspace environment.`,execute:_c,inputSchema:gc,logicalPath:`ash:framework/bash`,name:`bash`,sourceId:`ash:bash-tool`,sourceKind:`module`},yc=new z(`ash.readFile`);function q(e){return de.normalize(e)}function bc(e){return e}function xc(e){let t=be(`sha256`).update(e.content,`utf8`).digest(`hex`);return{byteLength:Buffer.byteLength(e.content,`utf8`),contentHash:t,filePath:e.filePath}}function Sc(e,t,n){let r=e.ensure(yc,()=>({byTarget:{}}));e.set(yc,{byTarget:{...r.byTarget,[t]:n}})}function Cc(e){e.set(yc,{byTarget:{}})}const wc=new Map;async function Tc(e){let t=wc.get(e.id);if(t!==void 0)return t;let n=Ec(e);wc.set(e.id,n);try{return await n}catch{return wc.delete(e.id),!1}}async function Ec(e){return(await e.runCommand({command:`command -v rg >/dev/null 2>&1`})).exitCode===0}function J(e){return`'${e.replace(/'/g,`'\\''`)}'`}async function Dc(e){let t=e.path??`/workspace`;lc(t);let n=q(t),r=Math.min(Math.max(1,e.limit??100),1e3),i=await K(),a=await Tc(i)?Oc({normalizedPath:n,pattern:e.pattern}):kc({normalizedPath:n,pattern:e.pattern}),o=await i.runCommand({command:a});if(o.exitCode!==0&&o.exitCode!==1)throw jc(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=q(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:Vc,inputSchema:Bc,logicalPath:`ash:framework/grep`,name:`grep`,sourceId:`ash:grep-tool`,sourceKind:`module`};async function Uc(e){let{filePath:t,offset:n,limit:r}=e;lc(t);let i=await K(),a=q(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=xc({content:c,filePath:a}),f=bc(a);Sc(B(),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}: ${pc(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 Wc={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 Gc(e){return Uc(e)}const Kc={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:Gc,inputSchema:Wc,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Cc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},qc=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function Jc(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 Yc(e,t){Jc(t);let n=await Xc(e),r=Zc(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(qc,``)}async function Xc(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 Zc(e,t){return`${W}/skills/${e}/${t}`}async function Qc(e){let t=B().get(
|
|
76
|
+
`),execute:Gc,inputSchema:Wc,logicalPath:`ash:framework/read-file`,name:`read_file`,onCompact({ctx:e}){return Cc(e),{}},sourceId:`ash:read-file-tool`,sourceKind:`module`},qc=/^---\r?\n[\s\S]*?\r?\n---\r?\n?/;function Jc(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 Yc(e,t){Jc(t);let n=await Xc(e),r=Zc(t,`SKILL.md`),i=await n.readTextFile({path:r});if(i===null)throw Error(`No skill named "${t}" at ${r}.`);return i.replace(qc,``)}async function Xc(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 Zc(e,t){return`${W}/skills/${e}/${t}`}async function Qc(e){let t=B().get(id);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 Yc(t,n)}const $c={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=>Qc(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`},el=new z(`ash.todo`);function tl(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 nl(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 rl(e){let t=B(),{todos:n}=e??{};if(n!==void 0){let e={items:[...n]};return t.set(el,e),nl(e)}return nl(t.ensure(el,()=>({items:[]})))}const il={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=>rl(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(el);if(t===void 0||t.items.length===0)return{};let n=tl(t);return n===void 0?{}:{messages:[{content:n,role:`user`}]}},sourceId:`ash:todo-tool`,sourceKind:`module`};function al(e){let t=new Ie({bulletListMarker:`-`,codeBlockStyle:`fenced`,emDelimiter:`*`,headingStyle:`atx`,hr:`---`});return t.remove([`script`,`style`,`meta`,`link`]),t.turndown(e)}function ol(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,`
|
|
@@ -83,6 +83,6 @@ A single tool or subagent call runs as one serial action. If you call multiple i
|
|
|
83
83
|
|
|
84
84
|
`).trim(),t}const sl={"&":`&`,">":`>`,"<":`<`," ":` `,""":`"`,"'":`'`,"'":`'`,"/":`/`},cl=new RegExp(Object.keys(sl).join(`|`),`gi`);function ll(e){return e.replace(cl,e=>sl[e.toLowerCase()]??e)}const ul=5*1024*1024;async function dl(e){let{url:t,format:n=`markdown`,timeout:r}=e;if(!t.startsWith(`http://`)&&!t.startsWith(`https://`))throw Error(`URL must start with http:// or https://`);let i=Math.min(r===void 0?3e4:r*1e3,12e4),a=AbortSignal.timeout(i),o=fl(n),s=await fetch(t,{headers:o,signal:a}),c=s.status===403&&s.headers.get(`cf-mitigated`)===`challenge`?await fetch(t,{headers:{...o,"User-Agent":h},signal:a}):s;if(!c.ok)throw Error(`Request failed with status code: ${c.status}`);let l=c.headers.get(`content-length`);if(l!==null&&parseInt(l,10)>ul)throw Error(`Response too large (exceeds 5 MB limit).`);let u=await c.arrayBuffer();if(u.byteLength>ul)throw Error(`Response too large (exceeds 5 MB limit).`);let d=c.headers.get(`content-type`)??``,f=d.includes(`text/html`),p=new TextDecoder().decode(u),m;m=n===`markdown`&&f?al(p):n===`text`&&f?ol(p):p;let{output:g,truncated:_}=uc(m);return{content:g,contentType:d,truncated:_,url:t}}function fl(e){let t;return t=e===`markdown`?`text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1`:e===`text`?`text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1`:`text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1`,{Accept:t,"Accept-Language":`en-US,en;q=0.9`,"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36`}}async function pl(e){return dl(e)}const ml={description:[`Fetch a webpage and return its content in the requested format. Use this to retrieve and analyze content from URLs.`,``,`Usage notes:`,`- The URL must be a fully-formed valid URL starting with http:// or https://`,`- HTML responses are automatically converted to markdown or plain text based on the requested format`,`- Format options: "markdown" (default), "text", or "html"`,`- Default timeout is 30 seconds (max 120 seconds)`,`- Maximum response size is 5 MB; content is further capped at the shared tool-output budget (50 KB / 2000 lines)`,`- This tool is read-only and does not modify any files`].join(`
|
|
85
85
|
`),execute:pl,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`},hl={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 gl(e){let{filePath:t,content:n}=e;lc(t);let r=await K(),i=B(),a=q(t),o=bc(a),s=await r.readTextFile({path:t});if(s===null)return await r.writeTextFile({content:n,path:t}),Sc(i,o,xc({content:n,filePath:a})),{existed:!1,path:a};let c=i.ensure(yc,()=>({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=xc({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}),Sc(i,o,xc({content:n,filePath:a})),{existed:!0,path:a}}const _l={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 vl(e){return gl(e)}const yl=[cc,vc,Pc,Hc,Kc,{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
|
-
`),execute:vl,inputSchema:_l,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},il,ml,hl,$c,Lo],bl=new Map([[Lo,e=>e.hasConnections]]);function xl(e){return yl.filter(t=>{let n=bl.get(t);return n===void 0||n(e)})}function Sl(){return new Set(yl.map(e=>e.name))}function Cl(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 Y=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 wl(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function X(e){let t=e.nodeId??`__root__`,n=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(n===void 0)throw new Y(`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 Tl(e,t,n){try{let r=oi(await X({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=wl({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 Y?t:new Y(`Failed to attach the channel definition from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function
|
|
86
|
+
`),execute:vl,inputSchema:_l,logicalPath:`ash:framework/write-file`,name:`write_file`,sourceId:`ash:write-file-tool`,sourceKind:`module`},il,ml,hl,$c,Lo],bl=new Map([[Lo,e=>e.hasConnections]]);function xl(e){return yl.filter(t=>{let n=bl.get(t);return n===void 0||n(e)})}function Sl(){return new Set(yl.map(e=>e.name))}function Cl(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 Y=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 wl(e){return{exportName:e.exportName,logicalPath:e.logicalPath,sourceId:e.sourceId,sourceKind:`module`}}async function X(e){let t=e.nodeId??`__root__`,n=e.moduleMap.nodes[t]?.modules[e.definition.sourceId];if(n===void 0)throw new Y(`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 Tl(e,t,n){try{let r=oi(await X({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=wl({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 Y?t:new Y(`Failed to attach the channel definition from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}const El=Symbol(`ash.definitionSource`);function Dl(e,t){Object.defineProperty(e,El,{value:t})}async function Ol(e,t,n){try{let r=c(await X({definition:e,kindLabel:`connection`,moduleMap:t,nodeId:n}),`Expected the connection export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);Dl(r,{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=di(r.auth,`Connection "${e.connectionName}" at "${e.logicalPath}":`)}catch(t){throw new Y(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 Y?t:new Y(`Failed to resolve connection "${e.connectionName}" from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}async function kl(e,t,n){try{let r=c(await X({definition:e,kindLabel:`hook`,moduleMap:t,nodeId:n}),Z(e,`to return an object`)),i={},a={},s=r.lifecycle;if(s!==void 0){let t=c(s,Z(e,"to expose `lifecycle` as an object"));for(let n of[`session`,`turn`]){let r=t[n];r!==void 0&&(i[n]=o(r,Z(e,`to provide a function for "lifecycle.${n}"`)))}}let l=r.events;if(l!==void 0){let t=c(l,Z(e,"to expose `events` as an object"));for(let[n,r]of Object.entries(t))r!==void 0&&(a[n]=o(r,Z(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 Y?t:new Y(`Failed to attach hook handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Z(e,t){return`Expected the hook export "${e.exportName??`default`}" from "${e.logicalPath}" ${t}.`}var Al=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 jl(e){let t=[];for await(let n of e)t.push(n);return Buffer.concat(t)}function Ml(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function Q(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 jl(n)},async readTextFile(t){Nl(t);let n=await e.readFile({abortSignal:t.abortSignal,path:e.resolvePath(t.path)});return n===null?null:Fl(Il(await jl(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:Ml(t.content),path:e.resolvePath(t.path)})},async writeTextFile(t){let n=Ll(t.content,t.encoding??`utf-8`);await e.writeFile({abortSignal:t.abortSignal,content:Ml(n),path:e.resolvePath(t.path)})}}}function Nl(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 Pl(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 Nl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Ml(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 Pl(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 Fl(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Il(e={}){return{name:`local`,async prewarm(e){let t=Hl(fd(e.runtimeContext.appRoot),e.templateKey);if(await Xl(t))return;let n=await Ll({sessionKey:e.templateKey,snapshotPath:t}),r=Q(zl(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=fd(e.runtimeContext.appRoot),n=await Jl(Hl(t,e.templateKey));if(n===null)throw new Ol({backendName:`local`,templateKey:e.templateKey});let r=Zl(e.existingMetadata)??Ul(t,e.sessionKey);return await Xl(r)||await Yl(r,n),Rl(await Ll({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function Ll(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await Jl(e.snapshotPath),i=new n(Wl(r));await Gl(i),await Kl(i,r?.entries??[]);let a=new t({cwd:W,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await ql({filesystem:i,sandbox:a});return await Yl(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 ${J(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await Bl(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 Rl(e){let t=Q(zl(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 zl(e){return{id:e.sessionKey,resolvePath:Vl,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Al(n)},async writeFile(t){let n=await kl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function Bl(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 Vl(e){return e.startsWith(`/`)?e:`${W}/${e}`}function Hl(e,t){return x(e,`local`,`templates`,`${t}.json`)}function Ul(e,t){return x(e,`local`,`sessions`,`${t}.json`)}function Wl(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function Gl(e){await e.mkdir(W,{recursive:!0})}async function Kl(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 ql(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 Jl(e){if(!await Xl(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function Yl(e,t){await C(b(e),{recursive:!0}),await w(e,`${JSON.stringify(t,null,2)}\n`)}async function Xl(e){try{return await me(e),!0}catch{return!1}}function Zl(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function Ql(e){return Il({createOptions:e})}function $l(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:gu,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=fu(n.tags,e.tags),a;try{a=await eu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Ol.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${hu(t)}`,{cause:t})}let o;try{o=await nu({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}": ${hu(t)}`,{cause:t})}return ru(o,e.sessionKey)},async prewarm(e){let i;try{i=await tu({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}": ${hu(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 eu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await lu(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Ol({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function tu(e){let t=await e.loadSandboxModule(),n=await lu(t,e.templateKey),r=fu(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 pu(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await ou(n,e.createOptions);let i=Q(iu(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 nu(e){let t=du(e.existingMetadata)??e.sessionKey,n=await lu(e.sandboxModule,t);if(n!==null)return await pu(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 ru(e,t){return{session:Q(iu(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Q(iu(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function iu(e,t){return{id:t,resolvePath:au,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 kl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function au(e){return e.startsWith(`/`)?e:`${W}/${e}`}async function ou(e,t){await su(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${W} && chown ${cu}:${cu} ${W}`}),t.networkPolicy!==`deny-all`&&await su(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 su(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 cu=`vercel-sandbox`;async function lu(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(uu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${hu(e)}`,{cause:e})}}function uu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function du(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function fu(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>_u)throw Error(`Vercel Sandbox supports at most ${_u} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function pu(e,t){t===void 0||mu(e.tags,t)||await e.update({tags:t})}function mu(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 hu(e){return e instanceof Error?e.message:String(e)}const gu=1800*1e3,_u=5;function vu(e){return $l({createOptions:e})}function yu(e){return Ti(()=>process.env.VERCEL?vu(e?.vercel):Ql(e?.local))}async function bu(e,t,n){try{let r=c(await X({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:xu(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 Y?t:new Y(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function xu(e,t){if(e===void 0)return yu();if(typeof e==`function`)return Ti(e);if(typeof e!=`object`||!e)throw new Y(`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 Y(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new Y(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function Su(e,t,n){try{let r=c(await X({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`)),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`,...Cu(r,e)}}catch(t){throw t instanceof Y?t:new Y(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Cu(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=wu(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&&Tu(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function wu(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new Y($(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 Tu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function Eu(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 Tl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>Su(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>Dl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>El(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await bu(e.manifest.sandbox,e.moduleMap,e.nodeId),c=Du(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Ou(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 Du(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Ou(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=wl(e.config.source)),t}function ku(e){return{sandbox:{definition:e.authoredSandbox??Au(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Au(){return{backend:yu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const ju=`load_skill`,Mu=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 Nu(e){let t=[],n=new Pa(`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 V(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Pu(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 Pu(e){return{description:e.description,inputSchema:Mu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Fu(e,t={}){let n=[],r=new Pa(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Iu(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 Iu(e){return{description:e.description,inputSchema:await Lu(e),kind:`authored-tool`,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId}}async function Lu(e){return e.inputSchema}var Ru=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 zu(e){let t=new Map,n=Uu(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await Bu({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:I,nodesByNodeId:t,subagentNodesById:r})}}async function Bu(e){let t=Wu(e.nodeId);if(e.nodesByNodeId.has(t))throw new Ru(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await Eu({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=xl({hasConnections:r}),a=r?Ku(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Sl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Ru(`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 Fu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[ju]}),d=new Set(n.channels.map(e=>e.name)),f=rc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Ru(`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=[...nc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=ku({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Nu({reservedToolNames:[ju,...u.preparedTools.map(e=>e.name)],subagents:await Vu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Cl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Xo({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function Vu(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 Ru(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Wu(e.parentNodeId),sourceId:r});t.push(await Hu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function Hu(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Wu(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await Bu({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 Uu(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 Wu(e){return e===`__root__`?lo:e}const Gu=Lo.name;function Ku(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===Gu?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const qu=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Ju(e){let[t,n]=await Promise.all([mo({compiledArtifactsSource:e}),Yu(e)]),r=await zu({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Ra({channels:ed(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function Yu(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await Xu(e):await yo({compiledArtifactsSource:e})}async function Xu(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 Zu(e){if(qu)return Ju(e);let t=Qa(),n=Wa(e),r=await oo(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=Ju(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 Qu(e){let t=await Zu(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=uo(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 $u(){let e=Qa();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function ed(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 z(`ash.channel`,{codec:{serialize(e){return{kind:Ca(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(td);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 td=new z(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return Qu({compiledArtifactsSource:t,nodeId:n})}}});new z(`ash.session`);const nd=new z(`ash.sandbox`),rd=_(),id={workflowId:`workflow//${rd.name}@${rd.version}//workflowEntry`};function ad(e=process.cwd()){return S(e)}function od(e){return be(`sha256`).update(e).digest(`hex`).slice(0,12)}function sd(){return!!process.env.VERCEL}function cd(e,t=`all`){let n=x(e,`.ash`,`nitro`);return t===`all`?n:x(n,t)}function ld(e,t){return x(e,`.ash`,`nitro-output`,t)}function ud(e){let t=x(m(),`.ash`,`workflow-cache`);return dd(t),x(t,od(e))}function dd(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 fd(e){return x(e,`.ash`,`sandbox-cache`)}function pd(e){return sd()?x(e,`.vercel`,`output`):x(e,`.output`)}function md(e){return{appRoot:e,outputDir:pd(e),workflowId:id.workflowId,workflowBuildDir:ud(e),workflowSourceDir:g(`src/execution`)}}export{Tr as C,Fn as D,I as E,Ar as S,Er as T,Wa as _,ud as a,ti as b,rc as c,mo as d,lo as f,Ua as g,Ha as h,ld as i,nc as l,H as m,ad as n,$u as o,ro as p,cd as r,zu as s,md as t,W as u,ea as v,Dr as w,Mr as x,ta as y};
|
|
88
|
+
`&&(t.push(e.slice(n,r+1)),n=r+1);return n<e.length&&t.push(e.slice(n)),t}function Fl(e,t){if(t.startLine===void 0&&t.endLine===void 0)return e;let n=Pl(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 Il(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 Ll(e,t){return t===`utf-8`||t===`utf8`?new TextEncoder().encode(e):Buffer.from(e,t)}function Rl(e={}){return{name:`local`,async prewarm(e){let t=Wl(md(e.runtimeContext.appRoot),e.templateKey);if(await Ql(t))return;let n=await zl({sessionKey:e.templateKey,snapshotPath:t}),r=Q(Vl(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=md(e.runtimeContext.appRoot),n=await Xl(Wl(t,e.templateKey));if(n===null)throw new Al({backendName:`local`,templateKey:e.templateKey});let r=$l(e.existingMetadata)??Gl(t,e.sessionKey);return await Ql(r)||await Zl(r,n),Bl(await zl({sessionKey:e.sessionKey,snapshotPath:r}))}}}async function zl(e){let{Bash:t,InMemoryFs:n}=await import(`#compiled/just-bash/index.js`),r=await Xl(e.snapshotPath),i=new n(Kl(r));await ql(i),await Jl(i,r?.entries??[]);let a=new t({cwd:W,env:r?.env,fs:i,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureSnapshot(){let t=await Yl({filesystem:i,sandbox:a});return await Zl(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 ${J(e.workingDirectory)} && ${e.command} )`,n=a.exec(t),r=e.abortSignal?await Hl(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 Bl(e){let t=Q(Vl(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 Vl(e){return{id:e.sessionKey,resolvePath:Ul,async runCommand(t){return await e.executeCommand(t)},async readFile(t){let n=await e.readFileBytes(t.path);return n===null?null:Ml(n)},async writeFile(t){let n=await jl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}async function Hl(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 Ul(e){return e.startsWith(`/`)?e:`${W}/${e}`}function Wl(e,t){return x(e,`local`,`templates`,`${t}.json`)}function Gl(e,t){return x(e,`local`,`sessions`,`${t}.json`)}function Kl(e){let t={};for(let n of e?.entries??[])n.kind===`file`&&(t[n.path]=Buffer.from(n.contentBase64,`base64`));return t}async function ql(e){await e.mkdir(W,{recursive:!0})}async function Jl(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 Yl(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 Xl(e){if(!await Ql(e))return null;let t=JSON.parse(await ge(e,`utf8`));return t.version===1?t:null}async function Zl(e,t){await C(b(e),{recursive:!0}),await w(e,`${JSON.stringify(t,null,2)}\n`)}async function Ql(e){try{return await me(e),!0}catch{return!1}}function $l(e){let t=e?.snapshotPath;return typeof t==`string`?t:void 0}function eu(e){return Rl({createOptions:e})}function tu(e={}){let t=e.loadSandboxModule??(async()=>await import(`#compiled/@vercel/sandbox/index.js`)),n={timeout:vu,...e.createOptions},r=new Map;return{name:`vercel`,async create(e){let i=mu(n.tags,e.tags),a;try{a=await nu({loadSandboxModule:t,prewarmedTemplates:r,templateKey:e.templateKey})}catch(t){throw Al.is(t)?t:Error(`Failed to read sandbox template "${e.templateKey}": ${_u(t)}`,{cause:t})}let o;try{o=await iu({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}": ${_u(t)}`,{cause:t})}return au(o,e.sessionKey)},async prewarm(e){let i;try{i=await ru({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}": ${_u(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 nu(e){let t=e.prewarmedTemplates.get(e.templateKey);if(t!==void 0)return t;let n=await du(await e.loadSandboxModule(),e.templateKey);if(n===null||typeof n.currentSnapshotId!=`string`)throw new Al({backendName:`vercel`,templateKey:e.templateKey});return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey}}async function ru(e){let t=await e.loadSandboxModule(),n=await du(t,e.templateKey),r=mu(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 hu(n,r);if(typeof n.currentSnapshotId==`string`&&n.currentSnapshotId.length>0)return{sandboxName:n.name,snapshotId:n.currentSnapshotId,templateKey:e.templateKey};await cu(n,e.createOptions);let i=Q(ou(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 iu(e){let t=pu(e.existingMetadata)??e.sessionKey,n=await du(e.sandboxModule,t);if(n!==null)return await hu(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 au(e,t){return{session:Q(ou(e,t)),useSessionFn:async n=>(n!==void 0&&await e.update(n),Q(ou(e,t))),async captureState(){return{backendName:`vercel`,metadata:{sandboxName:e.name},sessionKey:t}},async dispose(){}}}function ou(e,t){return{id:t,resolvePath:su,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 jl(t.content);await e.writeFiles([{content:n,path:t.path}])}}}function su(e){return e.startsWith(`/`)?e:`${W}/${e}`}async function cu(e,t){await lu(e,{failureMessage:`Failed to initialize Vercel sandbox workspace.`,script:`mkdir -p ${W} && chown ${uu}:${uu} ${W}`}),t.networkPolicy!==`deny-all`&&await lu(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 lu(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 uu=`vercel-sandbox`;async function du(e,t){try{return await e.Sandbox.get({name:t})}catch(e){if(fu(e))return null;throw Error(`Failed to look up Vercel sandbox "${t}": ${_u(e)}`,{cause:e})}}function fu(e){return e instanceof Error?(e.response?.status??e.cause?.response?.status)===404:!1}function pu(e){let t=e?.sandboxName;return typeof t==`string`?t:void 0}function mu(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>yu)throw Error(`Vercel Sandbox supports at most ${yu} tags. Ash reserves "agent", "channel", and "sessionId"; remove or consolidate custom tags passed to vercelBackend().`);return n}}async function hu(e,t){t===void 0||gu(e.tags,t)||await e.update({tags:t})}function gu(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 _u(e){return e instanceof Error?e.message:String(e)}const vu=1800*1e3,yu=5;function bu(e){return tu({createOptions:e})}function xu(e){return Ti(()=>process.env.VERCEL?bu(e?.vercel):eu(e?.local))}async function Su(e,t,n){try{let r=c(await X({definition:e,kindLabel:`sandbox`,moduleMap:t,nodeId:n}),`Expected the sandbox export "${e.exportName??`default`}" from "${e.logicalPath}" to return an object.`);return{backend:Cu(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 Y?t:new Y(`Failed to attach the sandbox lifecycle handlers from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Cu(e,t){if(e===void 0)return xu();if(typeof e==`function`)return Ti(e);if(typeof e!=`object`||!e)throw new Y(`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 Y(`Sandbox "${t}" backend is missing a non-empty string "name" identifier.`,{logicalPath:t});if(typeof n.create!=`function`)throw new Y(`Sandbox "${t}" backend is missing a "create" function.`,{logicalPath:t});return n}async function wu(e,t,n){try{let r=c(await X({definition:e,kindLabel:`tool`,moduleMap:t,nodeId:n}),$(e,`to return an object`));Dl(r,{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`,...Tu(r,e)}}catch(t){throw t instanceof Y?t:new Y(`Failed to attach the tool execute function from "${e.logicalPath}": ${p(t)}`,{logicalPath:e.logicalPath,sourceId:e.sourceId})}}function Tu(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=Eu(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&&Du(e.inputSchema)&&(n.inputStandardSchema=e.inputSchema),n}function Eu(e,t){let n=e.retentionPolicy;if(n!==void 0){if(n===`auto`||n===`keep`||typeof n==`function`)return n;throw new Y($(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 Du(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}async function Ou(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 Tl(t,e.moduleMap,e.nodeId))}let i=await Promise.all(e.manifest.tools.map(t=>wu(t,e.moduleMap,e.nodeId))),a=await Promise.all(e.manifest.hooks.map(t=>kl(t,e.moduleMap,e.nodeId))),o=await Promise.all(e.manifest.connections.map(t=>Ol(t,e.moduleMap,e.nodeId))),s=e.manifest.sandbox===null?null:await Su(e.manifest.sandbox,e.moduleMap,e.nodeId),c=ku(e.manifest.instructions),l=e.manifest.workspaceResourceRoot,u={channels:n,config:Au(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 ku(e){if(e!==void 0)return{name:e.name,logicalPath:e.logicalPath,markdown:e.markdown,sourceId:e.sourceId,sourceKind:e.sourceKind}}function Au(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=wl(e.config.source)),t}function ju(e){return{sandbox:{definition:e.authoredSandbox??Mu(),workspaceResourceRoot:e.workspaceResourceRoot}}}function Mu(){return{backend:xu(),logicalPath:`ash:framework/default-sandbox`,sourceId:`ash:default-sandbox`,sourceKind:`module`}}const Nu=`load_skill`,Pu=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 Fu(e){let t=[],n=new Pa(`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 V(`subagent`,`Found multiple runtime subagents mapped to node id "${i.nodeId}".`,{...e,entryName:i.name});let a=Iu(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 Iu(e){return{description:e.description,inputSchema:Pu,kind:`subagent`,logicalPath:e.logicalPath,name:e.name,nodeId:e.nodeId,sourceId:e.sourceId}}async function Lu(e,t={}){let n=[],r=new Pa(`tool`,t.reservedToolNames??[]);for(let t of e.tools){let e=await Ru(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 Ru(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 Bu=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 Vu(e){let t=new Map,n=Gu(e.manifest),r=new Map(e.manifest.subagents.map(e=>[e.nodeId,e]));return{nodesByNodeId:t,root:await Hu({childNodeIdsByParentNodeId:n,manifest:e.manifest,moduleMap:e.moduleMap,nodeId:I,nodesByNodeId:t,subagentNodesById:r})}}async function Hu(e){let t=Ku(e.nodeId);if(e.nodesByNodeId.has(t))throw new Bu(`Found multiple runtime agent nodes for node id "${t}".`,{nodeId:t,sourceId:e.sourceId});let n=await Ou({manifest:e.manifest,moduleMap:e.moduleMap,nodeId:e.nodeId}),r=n.connections.length>0,i=xl({hasConnections:r}),a=r?Ju(i,n.connections):i,o=new Set(a.map(e=>e.name)),s=Sl(),c=new Set(n.tools.map(e=>e.name));for(let r of n.disabledFrameworkTools)if(!s.has(r))throw new Bu(`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 Lu({tools:[...a.filter(e=>!c.has(e.name)&&!l.has(e.name)),...n.tools]},{reservedToolNames:o.has(`load_skill`)||c.has(`load_skill`)?[]:[Nu]}),d=new Set(n.channels.map(e=>e.name)),f=rc();for(let r of n.disabledFrameworkChannels)if(!f.has(r))throw new Bu(`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=[...nc().filter(e=>!d.has(e.name)&&!p.has(e.name)),...n.channels],h=ju({authoredSandbox:n.sandbox,workspaceResourceRoot:n.workspaceResourceRoot}),g=Fu({reservedToolNames:[Nu,...u.preparedTools.map(e=>e.name)],subagents:await Uu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,parentNodeId:e.nodeId,subagentNodesById:e.subagentNodesById})}),_={agent:n,channels:m,hookRegistry:Cl(n.hooks),nodeId:t,sandboxRegistry:h,sourceId:e.sourceId,subagentRegistry:g,toolRegistry:u,turnAgent:Xo({agent:n,nodeId:t,tools:[...u.preparedTools,...g.preparedTools]})};return e.nodesByNodeId.set(t,_),_}async function Uu(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 Bu(`Missing compiled subagent node "${r}" while resolving runtime subagents.`,{nodeId:Ku(e.parentNodeId),sourceId:r});t.push(await Wu({childNodeIdsByParentNodeId:e.childNodeIdsByParentNodeId,moduleMap:e.moduleMap,nodesByNodeId:e.nodesByNodeId,sourceRef:n,subagentNodesById:e.subagentNodesById}))}return t}async function Wu(e){let t={description:e.sourceRef.description,logicalPath:e.sourceRef.logicalPath,name:e.sourceRef.name,nodeId:Ku(e.sourceRef.nodeId),sourceId:e.sourceRef.sourceId,sourceKind:`module`};return await Hu({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 Gu(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 Ku(e){return e===`__root__`?lo:e}const qu=Lo.name;function Ju(e,t){let n=t.map(e=>e.connectionName).join(`, `);return e.map(e=>e.name===qu?{...e,description:`${e.description} Available connections: ${n}.`}:e)}const Yu=process.env.ASH_DISABLE_AGENT_CACHE===`1`;async function Xu(e){let[t,n]=await Promise.all([mo({compiledArtifactsSource:e}),Zu(e)]),r=await Vu({manifest:t,moduleMap:n}),i=r.root;return{adapterRegistry:Ra({channels:nd(r)}),compiledArtifactsSource:e,graph:r,hookRegistry:i.hookRegistry,moduleMap:n,resolvedAgent:i.agent,subagentRegistry:i.subagentRegistry,toolRegistry:i.toolRegistry,turnAgent:i.turnAgent}}async function Zu(e){return e.kind===`disk`&&e.moduleMapLoadMode===`authored-source`?await Qu(e):await yo({compiledArtifactsSource:e})}async function Qu(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 $u(e){if(Yu)return Xu(e);let t=Qa(),n=Wa(e),r=await oo(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=Xu(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 ed(e){let t=await $u(e.compiledArtifactsSource);if(e.nodeId===void 0)return t;let n=uo(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 td(){let e=Qa();e.bundleCache.clear(),e.bundleCacheKeyBySourceKey.clear()}function nd(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 z(`ash.channel`,{codec:{serialize(e){return{kind:Ca(e),state:e.state?{...e.state}:{}}},deserialize(e,t){let n=t.get(rd);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 rd=new z(`ash.bundle`,{codec:{serialize:e=>({nodeId:e.nodeId,source:e.compiledArtifactsSource}),deserialize:e=>{let{source:t,nodeId:n}=e;return ed({compiledArtifactsSource:t,nodeId:n})}}});new z(`ash.session`);const id=new z(`ash.sandbox`),ad=_(),od={workflowId:`workflow//${ad.name}@${ad.version}//workflowEntry`};function sd(e=process.cwd()){return S(e)}function cd(e){return be(`sha256`).update(e).digest(`hex`).slice(0,12)}function ld(){return!!process.env.VERCEL}function ud(e,t=`all`){let n=x(e,`.ash`,`nitro`);return t===`all`?n:x(n,t)}function dd(e,t){return x(e,`.ash`,`nitro-output`,t)}function fd(e){let t=x(m(),`.ash`,`workflow-cache`);return pd(t),x(t,cd(e))}function pd(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 md(e){return x(e,`.ash`,`sandbox-cache`)}function hd(e){return ld()?x(e,`.vercel`,`output`):x(e,`.output`)}function gd(e){return{appRoot:e,outputDir:hd(e),workflowId:od.workflowId,workflowBuildDir:fd(e),workflowSourceDir:g(`src/execution`)}}export{Tr as C,Fn as D,I as E,Ar as S,Er as T,Wa as _,fd as a,ti as b,rc as c,mo as d,lo as f,Ua as g,Ha as h,dd as i,nc as l,H as m,sd as n,td as o,ro as p,ud as r,Vu as s,gd as t,W as u,ea as v,Dr as w,Mr as x,ta as y};
|