experimental-ash 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/src/chunks/client-CKsU8Li3.js +4 -0
  3. package/dist/src/chunks/{dev-authored-source-watcher-CG6kri3T.js → dev-authored-source-watcher-DtLxnrXI.js} +1 -1
  4. package/dist/src/chunks/{host-CIU0NATc.js → host-Dor4C8jo.js} +2 -2
  5. package/dist/src/chunks/{paths-CvbqpwTh.js → paths-AVYgVLR3.js} +1 -1
  6. package/dist/src/chunks/{prewarm-C_Vd0JR7.js → prewarm-DsMkM8wg.js} +1 -1
  7. package/dist/src/cli/commands/info.js +1 -1
  8. package/dist/src/cli/dev/repl.js +1 -1
  9. package/dist/src/cli/run.js +1 -1
  10. package/dist/src/client/client.js +2 -1
  11. package/dist/src/client/index.d.ts +3 -0
  12. package/dist/src/client/index.js +1 -0
  13. package/dist/src/client/message-reducer-types.d.ts +130 -0
  14. package/dist/src/client/message-reducer-types.js +1 -0
  15. package/dist/src/client/message-reducer.d.ts +14 -0
  16. package/dist/src/client/message-reducer.js +462 -0
  17. package/dist/src/client/open-stream.js +2 -4
  18. package/dist/src/client/reducer.d.ts +63 -0
  19. package/dist/src/client/reducer.js +1 -0
  20. package/dist/src/client/session.js +3 -5
  21. package/dist/src/client/url.d.ts +8 -0
  22. package/dist/src/client/url.js +34 -0
  23. package/dist/src/compiler/module-map.js +12 -0
  24. package/dist/src/evals/cli/eval.js +1 -1
  25. package/dist/src/internal/application/package.js +1 -1
  26. package/dist/src/react/index.d.ts +3 -0
  27. package/dist/src/react/index.js +3 -0
  28. package/dist/src/react/use-ash-agent.d.ts +79 -0
  29. package/dist/src/react/use-ash-agent.js +330 -0
  30. package/package.json +15 -2
  31. package/dist/src/chunks/client-BeZ_W7vl.js +0 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # experimental-ash
2
2
 
3
+ ## 0.18.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0d710b6: Fix `ResolveAgentError: Missing compiled module namespace for schedule
8
+ source ...` when a Nitro cron fires a TypeScript schedule that declares
9
+ an `async run({ ... })` handler.
10
+
11
+ The compiler's runtime module map (`.ash/compile/module-map.mjs`) lists
12
+ every module-backed authored source the runtime needs to load lazily.
13
+ It already collected channels, connections, tools, hooks, the sandbox,
14
+ the agent config, and the model — but it silently dropped schedules.
15
+
16
+ Markdown schedules (and TypeScript schedules whose only body is a
17
+ `markdown` string) execute via the pre-compiled `markdown` captured in
18
+ the manifest, so they never tripped the gap. Schedules with a `run`
19
+ handler, on the other hand, must load their default export at dispatch
20
+ time — and that load went straight to `ResolveAgentError` because the
21
+ module map had no entry for `schedules/<name>.ts`.
22
+
23
+ Module-sourced schedules with `hasRun: true` are now included in the
24
+ compiled module map. Markdown schedules and `markdown`-only module
25
+ schedules are still omitted (their body lives in the manifest and the
26
+ dispatcher never loads the source).
27
+
3
28
  ## 0.18.0
4
29
 
5
30
  ### Minor Changes
@@ -0,0 +1,4 @@
1
+ import{i as e,t}from"./chunk-8L7ocgPr.js";import{_ as n,f as r,g as i,l as a,p as o,v as s}from"./types-MZUhN0Zy.js";import{n as c,r as l,t as u}from"./token-util-CHjOk3A7.js";var d=class extends Error{status;body;constructor(e,t){super(t||`Server returned ${e}.`),this.name=`ClientError`,this.status=e,this.body=t}};function f(e){if(e instanceof DOMException)return e.name===`AbortError`;if(!(e instanceof Error))return!1;let t=`code`in e&&typeof e.code==`string`?e.code:void 0;return e.name===`AbortError`||e.message===`terminated`||t===`UND_ERR_SOCKET`||/abort|cancel|disconnect|premature close|socket|terminated/i.test(e.message)}async function*p(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let e=await t.read();if(e.done){r+=n.decode();break}e.value&&(r+=n.decode(e.value,{stream:!0}));let i=r.indexOf(`
2
+ `);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e.length>0&&(yield JSON.parse(e)),i=r.indexOf(`
3
+ `)}}let e=r.trim();e.length>0&&(yield JSON.parse(e))}finally{t.releaseLock()}}function m(e,t,n){let r=t.startsWith(`/`)?t:`/${t}`,i=_(n);if(h(e)){let t=new URL(e);return t.pathname=`${g(t.pathname)}${r}`,t.search=i,t.hash=``,t.toString()}return`${g(e)}${r}${i}`}function h(e){return/^[a-z][a-z\d+\-.]*:/i.test(e)}function g(e){return e===`/`?``:e.endsWith(`/`)?e.slice(0,-1):e}function _(e){return!e||Object.keys(e).length===0?``:`?${new URLSearchParams(e).toString()}`}async function*v(e){let t=e.startIndex,n=e.maxReconnectAttempts;for(;;){let r=m(e.host,s(e.sessionId),t>0?{startIndex:String(t)}:void 0),i=await e.resolveHeaders(),a=await fetch(r,{headers:i,signal:e.signal??null});if(!a.ok){let e=await a.text();throw new d(a.status,e)}if(!a.body)throw new d(a.status,`Response body is null.`);let o=!1;try{for await(let e of p(a.body))t+=1,yield e}catch(e){if(!f(e))throw e;o=!0}if(!o||n<=0)return;--n}}var y=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>d}),t.exports=c(l);let u=Symbol.for(`@vercel/request-context`);function d(){return globalThis[u]?.get?.()??{}}})),b=t(((t,n)=>{var r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},c=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},u=e=>c(r({},`__esModule`,{value:!0}),e),d={};s(d,{getVercelOidcToken:()=>m,getVercelOidcTokenSync:()=>h}),n.exports=u(d);var f=y(),p=l();async function m(t){let n=``,r;try{n=h()}catch(e){r=e}try{let[{getTokenPayload:r,isExpired:i},{refreshToken:a}]=await Promise.all([await import(`./token-util-CHjOk3A7.js`).then(t=>e(t.t())),await import(`./token-DtoyQZy2.js`).then(t=>e(t.default))]);(!n||i(r(n),t?.expirationBufferMs))&&(await a(t),n=h())}catch(e){let t=r instanceof Error?r.message:``;throw e instanceof Error&&(t=`${t}
4
+ ${e.message}`),t?new p.VercelOidcTokenError(t):e}return n}function h(){let e=(0,f.getContext)().headers?.[`x-vercel-oidc-token`]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);return e}})),x=t(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},l=e=>s(n({},`__esModule`,{value:!0}),e),d={};o(d,{AccessTokenMissingError:()=>m.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>m.RefreshAccessTokenFailedError,getContext:()=>p.getContext,getVercelOidcToken:()=>f.getVercelOidcToken,getVercelOidcTokenSync:()=>f.getVercelOidcTokenSync,getVercelToken:()=>h.getVercelToken}),t.exports=l(d);var f=b(),p=y(),m=c(),h=u()})),S=x();const C=`${i}/`,w=new Set([`localhost`,`127.0.0.1`,`0.0.0.0`,`::1`,`[::1]`]);function T(e){return w.has(e.hostname)}const E=`x-vercel-protection-bypass`,D=`x-vercel-trusted-oidc-idp-token`;function O(e){return e.pathname.endsWith(`/ash/v1`)||e.pathname.includes(C)}async function k(e){let t=A(e),n=await M(t,e.resourceUrl);return n!==null&&j(t,n),t}function A(e){let t=new Headers(F(e.headers)),n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();return n&&O(e.resourceUrl)&&t.set(E,n),t}function j(e,t){e.has(`authorization`)||e.set(`authorization`,`Bearer ${t}`),e.set(D,t)}async function M(e,t){return N(t)?e.get(`x-vercel-oidc-token`)?.trim()||await P():null}function N(e){return!(!O(e)||T(e))}async function P(){let e=process.env.VERCEL_OIDC_TOKEN?.trim();try{let e=(await(0,S.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{return e??null}return e??null}function F(e){if(e!==void 0)return e instanceof Headers?e:Array.isArray(e)?e.map(([e,t])=>[e,t]):e}function I(){return{streamIndex:0}}function L(e){let t=B(e.events),n=e.session.streamIndex+e.events.length;return t?.type===`session.waiting`?{continuationToken:e.continuationToken??e.session.continuationToken,sessionId:e.sessionId,streamIndex:n}:I()}function R(e){let t;for(let n of e)V(n)&&(t=n.data.message??void 0);return t}function z(e){let t=B(e);return t?.type===`session.waiting`?`waiting`:t?.type===`session.failed`?`failed`:`completed`}function B(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&a(n))return n}}function V(e){return e.type===`message.completed`&&e.data.finishReason!==`tool-calls`}var H=class{continuationToken;sessionId;#e=!1;#t;constructor(e){this.continuationToken=e.continuationToken,this.sessionId=e.sessionId,this.#t=e.createStream}async result(){let e=[];for await(let t of this)e.push(t);return{events:e,message:R(e),sessionId:this.sessionId,status:z(e)}}[Symbol.asyncIterator](){if(this.#e)throw Error(`MessageResponse has already been consumed.`);return this.#e=!0,this.#t()}},U=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get state(){return this.#t}async sendMessage(e,t){return this.send({message:e},t)}async send(e,t){let n=this.#t,{continuationToken:r,sessionId:i}=await this.#n(e,n,t);return new H({continuationToken:r,createStream:()=>this.#r(i,r,n,t),sessionId:i})}openStream(e){let t=this.#t.sessionId;if(!t)throw Error(`Session has no session ID. Send a message first.`);return v({host:this.#e.host,maxReconnectAttempts:this.#e.maxReconnectAttempts,resolveHeaders:()=>this.#e.resolveHeaders(),sessionId:t,signal:e?.signal,startIndex:e?.startIndex??this.#t.streamIndex})}async#n(e,t,i){let a=t.sessionId?n(t.sessionId):r,o=m(this.#e.host,a),s=await this.#e.resolveHeaders(i?.headers);s.set(`content-type`,`application/json`);let c=W({input:e,session:t});if(c===null)throw Error(`Session.send requires a non-empty message, inputResponses, or both.`);let l=await fetch(o,{body:JSON.stringify(c),headers:s,method:`POST`,signal:i?.signal??null});if(!l.ok){let e=await l.text();throw new d(l.status,e)}let u=await l.json(),f=(typeof u.sessionId==`string`?u.sessionId:void 0)??l.headers.get(`x-ash-session-id`)?.trim()??t.sessionId;if(!f)throw Error(`Message route did not return a session id.`);return{continuationToken:typeof u.continuationToken==`string`?u.continuationToken:void 0,sessionId:f}}async*#r(e,t,n,r){let i=[];try{let t=n.sessionId===e?n.streamIndex:0,o=this.#e.maxReconnectAttempts;for(;;){let n=await this.#i(e,t,r?.signal),s=!1;try{for await(let e of p(n))if(i.push(e),t+=1,yield e,a(e)){s=!0;break}}catch(e){if(!f(e))throw e}if(s||o<=0)break;--o}}finally{this.#t=L({continuationToken:t,events:i,sessionId:e,session:n})}}async#i(e,t,n){let r=m(this.#e.host,s(e),t>0?{startIndex:String(t)}:void 0),i=await this.#e.resolveHeaders(),a=await fetch(r,{headers:i,signal:n??null});if(!a.ok){let e=await a.text();throw new d(a.status,e)}if(!a.body)throw new d(a.status,`Response body is null.`);return a.body}};function W(e){let t={};return e.input.message!==void 0&&(t.message=e.input.message),e.input.inputResponses!==void 0&&e.input.inputResponses.length>0&&(t.inputResponses=e.input.inputResponses),e.session.continuationToken!==void 0&&(t.continuationToken=e.session.continuationToken),Object.keys(t).length===0||e.session.continuationToken===void 0&&t.message===void 0||`continuationToken`in t&&Object.keys(t).length===1?null:t}var G=class{#e;#t;#n;#r;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.maxReconnectAttempts??3}async health(){let e=m(this.#n,o),t=await this.#i(),n=await fetch(e,{headers:t});if(!n.ok){let e=await n.text();throw new d(n.status,e)}return await n.json()}session(e){let t;return t=typeof e==`string`?{continuationToken:e,streamIndex:0}:e||I(),new U({host:this.#n,maxReconnectAttempts:this.#r,resolveHeaders:e=>this.#i(e)},t)}async#i(e){let t=new Headers,n=await q(this.#t);for(let[e,r]of Object.entries(n))t.set(e,r);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);let r=await this.#a();return r&&t.set(`authorization`,r),t}async#a(){let e=this.#e;if(e){if(`bearer`in e){let t=(await K(e.bearer)).trim();return t.length===0?void 0:`Bearer ${t}`}if(`basic`in e){let t=await K(e.basic.password);return`Basic ${J(e.basic.username,t)}`}}}};async function K(e){return typeof e==`function`?e():e}async function q(e){return e===void 0?{}:typeof e==`function`?await e():e}function J(e,t){let n=new TextEncoder().encode(`${e}:${t}`),r=Array.from(n,e=>String.fromCodePoint(e)).join(``);return btoa(r)}export{x as a,k as i,E as n,v as o,D as r,d as s,G as t};
@@ -1,4 +1,4 @@
1
- import{o as e}from"./paths-CvbqpwTh.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-C_Vd0JR7.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-AVYgVLR3.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-DsMkM8wg.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-CvbqpwTh.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-C_Vd0JR7.js";import{builtinModules as ce}from"node:module";import{dirname as _,extname as le,isAbsolute as ue,join as v,relative as y,resolve as b,sep as de}from"node:path";import{cp as x,mkdir as S,readFile as C,readdir as fe,realpath as pe,rename as me,rm as w,writeFile as T}from"node:fs/promises";import{randomUUID as he}from"node:crypto";import{existsSync as ge,readFileSync as _e}from"node:fs";import{fileURLToPath as ve}from"node:url";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";import{Buffer as Te}from"node:buffer";const Ee=`ash-cache.json`;async function E(e){let t=await Oe(e),n=h().version;t!==null&&t===n||await w(e,{force:!0,recursive:!0})}async function De(e){await S(e,{recursive:!0}),await T(v(e,Ee),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Oe(e){try{let t=JSON.parse(await C(v(e,Ee),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const ke=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Ae(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await je(e.filename,e.source),n=Ne(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Je(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Ye(r,t.name);i.steps??={};let c=i.steps[e.filename]??={};if(c[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;a.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(s=!0,o.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):o.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${r}//${t.name}`;i.workflows??={};let c=i.workflows[e.filename]??={};c[t.name]={workflowId:n},e.mode===`workflow`?(a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),o.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(a.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let c=`/**__internal_workflows${JSON.stringify(i)}*/;`,l=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!l)return{code:`${c}\n${Me(e.source,t,n,r)}`,workflowManifest:i};let u=Re(e.source,a),d=e.mode===`workflow`?await ze(e.filename,u):u;return{code:`${s?`import { registerStepFunction } from "workflow/internal/private";\n${c}\n`:`${c}\n`}${d}${o.length>0?`\n${o.join(`
1
+ import{n as e}from"./chunk-8L7ocgPr.js";import{C as t,T as n,i as r,r as i,w as a}from"./paths-AVYgVLR3.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-DsMkM8wg.js";import{builtinModules as ce}from"node:module";import{dirname as _,extname as le,isAbsolute as ue,join as v,relative as y,resolve as b,sep as de}from"node:path";import{cp as x,mkdir as S,readFile as C,readdir as fe,realpath as pe,rename as me,rm as w,writeFile as T}from"node:fs/promises";import{randomUUID as he}from"node:crypto";import{existsSync as ge,readFileSync as _e}from"node:fs";import{fileURLToPath as ve}from"node:url";import{build as ye,copyPublicAssets as be,createDevServer as xe,createNitro as Se,prepare as Ce,prerender as we}from"nitro/builder";import{Buffer as Te}from"node:buffer";const Ee=`ash-cache.json`;async function E(e){let t=await Oe(e),n=h().version;t!==null&&t===n||await w(e,{force:!0,recursive:!0})}async function De(e){await S(e,{recursive:!0}),await T(v(e,Ee),`${JSON.stringify({ashVersion:h().version},null,2)}\n`)}async function Oe(e){try{let t=JSON.parse(await C(v(e,Ee),`utf8`));return typeof t.ashVersion==`string`?t.ashVersion:null}catch(e){return e instanceof Error&&`code`in e&&e.code,null}}const ke=new Set([`__builtin_response_array_buffer`,`__builtin_response_json`,`__builtin_response_text`]);async function Ae(e){if(e.mode===!1)return{code:e.source,workflowManifest:{}};let t=await je(e.filename,e.source),n=Ne(t);if(n.length===0)return{code:e.source,workflowManifest:{}};let r=e.moduleSpecifier??`./${Je(e.filename)}`,i={},a=[],o=[],s=!1;for(let t of n){if(t.directive===`use step`){let n=Ye(r,t.name);i.steps??={};let c=i.steps[e.filename]??={};if(c[t.name]={stepId:n},e.mode===`workflow`){let e=t.exportPrefix.length>0?`export `:``;a.push({end:t.rangeEnd,start:t.rangeStart,text:`${e}var ${t.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`})}else a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),e.mode===`step`?(s=!0,o.push(`registerStepFunction(${JSON.stringify(n)}, ${t.name});`)):o.push(`${t.name}.stepId = ${JSON.stringify(n)};`);continue}let n=`workflow//${r}//${t.name}`;i.workflows??={};let c=i.workflows[e.filename]??={};c[t.name]={workflowId:n},e.mode===`workflow`?(a.push({end:t.directiveEnd,start:t.directiveStart,text:``}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`),o.push(`globalThis.__private_workflows.set(${JSON.stringify(n)}, ${t.name});`)):(a.push({end:t.directiveEnd,start:t.directiveStart,text:`throw new Error(${JSON.stringify(`You attempted to execute workflow ${t.name} function directly. To start a workflow, use start(${t.name}) from workflow/api`)});`}),o.push(`${t.name}.workflowId = ${JSON.stringify(n)};`))}let c=`/**__internal_workflows${JSON.stringify(i)}*/;`,l=n.some(e=>e.directive===`use workflow`);if(e.mode===`workflow`&&!l)return{code:`${c}\n${Me(e.source,t,n,r)}`,workflowManifest:i};let u=Re(e.source,a),d=e.mode===`workflow`?await ze(e.filename,u):u;return{code:`${s?`import { registerStepFunction } from "workflow/internal/private";\n${c}\n`:`${c}\n`}${d}${o.length>0?`\n${o.join(`
2
2
  `)}\n`:``}`,workflowManifest:i}}async function je(e,t){let{parseAst:n}=await o();return n(t,{astType:`ts`,lang:qe(e),range:!0,sourceType:`module`},e)}function Me(e,t,n,r){let i=Be(e,t),a=n.filter(e=>e.directive===`use step`).map(e=>{let t=e.exportPrefix.length>0?`export `:``,n=Ye(r,e.name);return`${t}var ${e.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(n)});`}),o=[...i,...a];return o.length>0?`${o.join(`
3
3
  `)}\n`:``}function Ne(e){let t=[];for(let n of e.body??[]){let e=Pe(n);if(e===null)continue;let r=e.fn,i=r.id?.name,a=Ie(r.body);if(r.async!==!0||i===void 0||a===void 0)continue;let o=Le(a[0]);o!==null&&t.push({directive:o.value,directiveEnd:o.end,directiveStart:o.start,exportPrefix:e.exported?`export `:``,name:i,rangeEnd:e.end,rangeStart:e.start})}return t}function Pe(e){return e.type===`FunctionDeclaration`?Fe(e,!1,e):e.type!==`ExportNamedDeclaration`||e.declaration?.type!==`FunctionDeclaration`?null:Fe(e.declaration,!0,e)}function Fe(e,t,n){return e.start===void 0||e.end===void 0||n.start===void 0||n.end===void 0?null:{end:n.end,exported:t,fn:e,start:n.start}}function Ie(e){return e===void 0||Array.isArray(e)?e:e.body}function Le(e){let t=e?.directive??(e?.type===`ExpressionStatement`&&e.expression?.type===`Literal`?e.expression.value:void 0);return t!==`use workflow`&&t!==`use step`||e?.start===void 0||e.end===void 0?null:{end:e.end,start:e.start,value:t}}function Re(e,t){let n=``,r=0;for(let i of[...t].sort((e,t)=>e.start-t.start))n+=e.slice(r,i.start),n+=i.text,r=i.end;return n+e.slice(r)}async function ze(e,t){let n=await je(e,t),r=We(n),i=[];for(let e of n.body??[]){if(e.type!==`ImportDeclaration`||e.start===void 0||e.end===void 0)continue;let n=Ue(e);n.length>0&&n.every(e=>!r.has(e))&&i.push({end:Ke(t,e.end),start:e.start,text:``})}return i.length>0?Re(t,i):t}function Be(e,t){let n=[];for(let r of t.body??[])r.type===`ExportNamedDeclaration`&&r.declaration?.type===`VariableDeclaration`&&r.declaration.kind===`const`&&r.start!==void 0&&r.end!==void 0&&(r.declaration.declarations??[]).every(Ve)&&n.push(e.slice(r.start,r.end).trim());return n}function Ve(e){return He(e.init)}function He(e){return e==null?!1:e.type===`Literal`?e.value===null||typeof e.value==`boolean`||typeof e.value==`number`||typeof e.value==`string`:e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`||e.type===`TSTypeAssertion`?He(e.expression):e.type===`UnaryExpression`&&e.argument?.type===`Literal`?typeof e.argument.value==`number`:!1}function Ue(e){return e.importKind===`type`?[]:(e.specifiers??[]).filter(e=>e.importKind!==`type`).map(e=>e.local?.name).filter(e=>e!==void 0)}function We(e){let t=new Set;return D(e,e=>{e.type===`Identifier`&&typeof e.name==`string`&&t.add(e.name)}),t}function D(e,t){if(!(e.type===`ImportDeclaration`||e.type?.startsWith(`TS`))){t(e);for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Ge(e)&&D(e,t);else Ge(n)&&D(n,t)}}function Ge(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function Ke(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n+=1;return e[n]===`\r`&&e[n+1]===`
4
4
  `?n+2:e[n]===`
@@ -19,4 +19,4 @@ export const POST = workflowEntrypoint(workflowCode);`);if(n===-1||r===-1||r<=n)
19
19
  `):null},resolveId(e){return an.test(e)?rn:null}}}function sn(e){return e===`all`||e===`app`}function cn(e){return z(e)}function z(e){return e===`all`||e===`flow`}function B(e,t){let r=`#ash-route-handler/${t.method??`ALL`} ${t.route}`,i=n(t.handlerPath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import handler from ${i};`,`export default handler;`].join(`
20
20
  `)}function V(e){return v(e.options.buildDir,`workflow`)}function ln(e,t){let n=y(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function un(e,t){let n=v(V(e),`${t.bundleName}-handler.mjs`),r=_(n),i=ln(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=ln(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await S(r,{recursive:!0}),await T(n,dn({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function dn(e){let t=[`// Generated by Ash. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__ashWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __ashGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __ashWorkflowWorld = __ashGetWorkflowWorld();`,` if (typeof __ashWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __ashWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[ash] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
21
21
  `)}function fn(e,t){let r=`#ash-route${t.route}`,i=n(t.modulePath);e.options.handlers.push({handler:r,method:t.method,route:t.route}),e.options.virtual[r]=[`import { ${t.handlerExport} } from ${i};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
22
- `)}async function pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[c(),...e]}}function _n(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const vn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function Nn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>q(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=q(e.options.rootDir,n);return i.has(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}function zn(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:2,generatorVersion:e.generatorVersion??h().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?Hn(t.instructions):null,schedules:t.schedules.map(Un),tools:t.tools.map(Wn),skills:t.skills.map(Gn),connections:t.connections.map(Kn),channels:t.channels.filter(Vn).map(qn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Jn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Bn(e){let t=zn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await T(n,`${JSON.stringify(t,null,2)}\n`),n}function Vn(e){return e.kind===`channel`}function Hn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Un(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Wn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Gn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Kn(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type:`mcp`};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function qn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Rn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Jn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Yn(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function Xn(e){return Yn()?(await se(e),!0):!1}function Zn(e){return e.replace(/[\\/]+$/,``)}async function Qn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function $n(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Qn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function er(e){let t=Zn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function tr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await er(n)}finally{await n.close()}}async function nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await er(e);return await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await er(n);await Xn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await tr(t,`flow`);return await $n({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,rr=new Set([`[::]`,`::`,`0.0.0.0`]);function ir(e){let t=new URL(e);return rr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function ar(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function or(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function sr(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function cr(e){let t=or(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function lr(e){let t=process.env[Q],n=process.env[$],r=new URL(ir(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function ur(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function dr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=ur(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function fr(e){let t=cr({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!ar(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function pr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=xe(i);dr(a);let o=t.host??i.options.devServer.hostname,s=t.port??sr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await fr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=lr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-CG6kri3T.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:ir(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var mr=e({buildHost:()=>hr,startHost:()=>gr});async function hr(e){return await nr(e)}async function gr(e,t={}){return await pr(e,t)}export{gr as n,mr as t};
22
+ `)}async function pn(e,n,r){if(cn(r.surface)){let t=f(),i=new Kt({appRoot:n.appRoot,compiledArtifactsBootstrapPath:n.compiledArtifacts.bootstrapPath,outDir:n.workflowBuildDir,rootDir:t,watch:e.options.dev}),a=Promise.resolve(),o=async()=>{await i.build({nitroStepOutfile:z(r.surface)?v(V(e),`steps.mjs`):void 0,nitroWorkflowOutfile:e.options.dev&&z(r.surface)?v(V(e),`workflows.mjs`):void 0})},s=async()=>{let e=a.then(o);a=e.catch(()=>{}),await e},c=!0;await s(),e.hooks.hook(`build:before`,async()=>{if(c){c=!1;return}await s()}),e.options.dev&&e.hooks.hook(`dev:reload`,async()=>{await s()})}let i=re({appRoot:n.appRoot,dev:e.options.dev});sn(r.surface)&&(B(e,{handlerPath:d(`src/internal/nitro/routes/index.ts`),method:`GET`,route:`/`}),B(e,{handlerPath:d(`src/internal/nitro/routes/health.ts`),method:`GET`,route:te}),fn(e,{args:JSON.stringify({appRoot:i.appRoot}),handlerExport:`handleAgentInfoRequest`,method:`GET`,modulePath:d(`src/internal/nitro/routes/info.ts`),route:ee}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-runs.ts`),method:`GET`,route:`/api/runs`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run.ts`),method:`GET`,route:`/api/runs/:runId`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-steps.ts`),method:`GET`,route:`/api/runs/:runId/steps`}),B(e,{handlerPath:d(`src/internal/nitro/routes/workflow-run-events.ts`),method:`GET`,route:`/api/runs/:runId/events`}),ae(e,{artifactsConfig:i,registrations:ne(n)}));let a=V(e),o=z(r.surface)?e.options.dev?v(a,`workflows.mjs`):v(n.workflowBuildDir,`workflows.mjs`):void 0,s=e.options.dev&&o!==void 0?[{bundlePath:o,queuePrefix:`__wkf_workflow_`}]:[],c=s.length>0?t(u(`workflow/runtime`)):void 0;o&&await un(e,{bundleName:`workflows`,bundlePath:o,directHandlers:s,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:c}),e.routing.sync()}function mn(){return`${g}/cron/${he()}`}function hn(e){e.options.vercel!==void 0&&(e.options.vercel.cronHandlerRoute=mn())}function gn(e){return{plugins:[c(),...e]}}function _n(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:nitro-routing-import-specifiers`,transform(e,t){if(t!==`#nitro/virtual/routing`&&t!==`#nitro/virtual/routing-meta`)return null;let n=a(e);return n===e?null:{code:n,map:null}}})})}const vn=`@alinea/generated.@appsignal/nodejs.@aws-sdk/client-s3.@aws-sdk/s3-presigned-post.@blockfrost/blockfrost-js.@highlight-run/node.@huggingface/transformers.@jpg-store/lucid-cardano.@libsql/client.@mikro-orm/core.@mikro-orm/knex.@node-rs/argon2.@node-rs/bcrypt.@prisma/client.@react-pdf/renderer.@sentry/profiling-node.@sparticuz/chromium.@sparticuz/chromium-min.@statsig/statsig-node-core.@swc/core.@xenova/transformers.@zenstackhq/runtime.argon2.autoprefixer.aws-crt.bcrypt.better-sqlite3.canvas.chromadb-default-embed.config.cpu-features.cypress.dd-trace.eslint.express.firebase-admin.htmlrewriter.import-in-the-middle.isolated-vm.jest.jsdom.keyv.libsql.mdx-bundler.mongodb.mongoose.newrelic.next-mdx-remote.next-seo.node-cron.node-pty.node-web-audio-api.onnxruntime-node.oslo.pg.pino.pino-pretty.pino-roll.playwright.playwright-core.postcss.prettier.prisma.puppeteer.puppeteer-core.ravendb.require-in-the-middle.rimraf.sharp.shiki.sqlite3.thread-stream.ts-morph.ts-node.typescript.vscode-oniguruma.webpack.websocket.zeromq`.split(`.`);function yn(e){if(e)return{config:{version:3,framework:{version:h().version}}}}const bn=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],xn=Symbol(`ash.workflow-transform-patched`),Sn=[`@napi-rs/keyring`];function Cn(){let e={};for(let t of bn)e[t]=u(t);return e}function wn(e){if(!e&&process.env.VERCEL)return`vercel`}function Tn(e){return e===`all`||e===`app`}function H(e){return e===`all`||e===`flow`}function U(e){return H(e)}function En(e,t){return e.options.dev?v(e.options.buildDir,`workflow`,`steps.mjs`):v(t.workflowBuildDir,`steps.mjs`)}function Dn(e){let t=e.compileResult.manifest.config.build;return[...new Set([...Sn,...vn,...t?.externalDependencies??[]])].filter(e=>e!==p)}function W(e){return e.replaceAll(`\\`,`/`)}function G(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function K(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function q(e,t){return t.startsWith(`file://`)?W(K(G(ve(t)))):ue(t)?W(K(G(t))):W(K(G(b(e,t))))}function On(e,t){let n=W(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function J(e){let t=W(e);return process.platform===`win32`?t.toLowerCase():t}function kn(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function An(e,t,n){return t.startsWith(`workflow`)?u(t):t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`file://`)?q(n===void 0?e:_(q(e,n)),t):null}async function Y(e,t){let n=await C(e,`utf8`),r=new Set;for(let i of kn(n)){let n=An(t,i,e);n!==null&&r.add(J(n))}return r}async function jn(e,t){if(e.options.noExternals===!0)return;let n;try{n=await Y(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function Mn(e,t){let n=W(e).replace(/\/$/,``),r=W(t),i=n.toLowerCase(),a=r.toLowerCase();if(a.startsWith(`${i}/`))return r.slice(n.length+1);if(a===i)return`.`;let o=y(n,r).replaceAll(`\\`,`/`);if(o.startsWith(`../`)&&(o=o.split(`/`).filter(e=>e!==`..`).join(`/`)),o.includes(`:`)||o.startsWith(`/`)){let e=r.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return o}function Nn(e,t){let n=[t,v(e.options.buildDir,`workflow`)].map(t=>q(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,r)=>{Array.isArray(r.plugins)&&r.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,r){let i=An(e.options.rootDir,t,r)??q(e.options.rootDir,t);return n.some(e=>On(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function Pn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let i=An(e.options.rootDir,t,n);return i===null||!(await r()).has(J(i))?null:{id:i,moduleSideEffects:`no-treeshake`}}})})}function Fn(e,t){let n=null,r=async()=>(n===null&&(n=await Y(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let i=await r(),a=q(e.options.rootDir,n);return i.has(J(a))?{code:(await k(Mn(e.options.rootDir,a),t,`step`,a,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function In(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return W(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function Ln(e,t){let n=W(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[xn]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return On(t,n)?null:r.call(this,e,t,...i)},t[xn]=!0}})}async function X(e,t,n={}){let r=n.surface??`all`,a=(!t||n.schedules===!0)&&Tn(r)&&e.scheduleRegistrations.length>0,o=wn(t),s=o===`vercel`?on():null,c=s===null?[]:[s],l=gn(c),u=gn(c),f=Dn(e),p=i(e.appRoot,r),h=e.compiledArtifacts.instrumentationPluginPath===void 0?[e.compiledArtifacts.bootstrapPath]:[e.compiledArtifacts.instrumentationPluginPath,e.compiledArtifacts.bootstrapPath];await E(p);let g=await Se({_cli:{command:t?`dev`:`build`},buildDir:p,dev:t,logLevel:t?1:void 0,output:n.outputDir===void 0?void 0:{dir:n.outputDir},preset:o,plugins:h,publicAssets:[],scanDirs:U(r)?[m(`src/execution`)]:void 0,rolldownConfig:l,rollupConfig:u,rootDir:e.appRoot,serverDir:!1,traceDeps:f,vercel:yn(o===`vercel`&&Tn(r))},t?{watch:!0}:void 0);if(await De(p),_n(g),H(r)){let t=Cn();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;Nn(g,e.workflowBuildDir),Ln(g,e.workflowBuildDir)}if(U(r)){let t=En(g,e);Pn(g,{stepEntrypointPath:t}),Fn(g,{stepEntrypointPath:t})}if(e.compiledArtifacts.instrumentationSourcePath!==void 0&&In(g,e.compiledArtifacts.instrumentationSourcePath),t&&H(r)){let t=e.workflowBuildDir,n=new Set([W(v(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let r=t.external;t.external=(e,...t)=>{if(n.has(W(e)))return!0;if(typeof r==`function`)return r(e,...t)}})}return a&&(hn(g),oe(g,{artifactsConfig:re({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:d(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await pn(g,e,{surface:r}),U(r)&&await jn(g,En(g,e)),g}function Rn(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}function zn(e){let{manifest:t}=e;return{kind:`vercel-ash-agent-summary`,schemaVersion:2,generatorVersion:e.generatorVersion??h().version,agent:{name:t.config.name,description:t.config.description,modelId:t.config.model.id},instructions:t.instructions?Hn(t.instructions):null,schedules:t.schedules.map(Un),tools:t.tools.map(Wn),skills:t.skills.map(Gn),connections:t.connections.map(Kn),channels:t.channels.filter(Vn).map(qn),sandbox:t.sandbox===null?null:{logicalPath:t.sandbox.logicalPath},subagents:t.subagents.map(Jn),diagnostics:{errors:t.diagnosticsSummary.errors,warnings:t.diagnosticsSummary.warnings}}}async function Bn(e){let t=zn({generatorVersion:e.generatorVersion,manifest:e.manifest}),n=v(e.appRoot,`.ash/agent-summary.json`);return await S(_(n),{recursive:!0}),await T(n,`${JSON.stringify(t,null,2)}\n`),n}function Vn(e){return e.kind===`channel`}function Hn(e){return{logicalPath:e.logicalPath,sourceKind:e.sourceKind,markdown:e.markdown}}function Un(e){return{name:e.name,cron:e.cron,logicalPath:e.logicalPath}}function Wn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Gn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath,sourceKind:e.sourceKind}}function Kn(e){let t={name:e.connectionName,description:e.description,url:e.url,logicalPath:e.logicalPath,type:`mcp`};return e.vercelConnect===void 0?t:{...t,vercelConnect:{connector:e.vercelConnect.connector}}}function qn(e){let t={name:e.name,method:e.method,urlPath:e.urlPath,type:Rn(e.adapterKind),logicalPath:e.logicalPath};return e.adapterKind===void 0?t:{...t,adapterKind:e.adapterKind}}function Jn(e){return{name:e.name,description:e.description,logicalPath:e.logicalPath}}function Yn(){let e=process.env.VERCEL?.trim(),t=process.env.VERCEL_DEPLOYMENT_ID?.trim();return typeof e==`string`&&e.length>0&&typeof t==`string`&&t.length>0}async function Xn(e){return Yn()?(await se(e),!0):!1}function Zn(e){return e.replace(/[\\/]+$/,``)}async function Qn(e){try{return JSON.parse(await C(v(e,`functions`,`__server.func`,`.vc-config.json`),`utf8`)).runtime}catch{return}}async function $n(e){let t=new Kt({appRoot:e.appRoot,compiledArtifactsBootstrapPath:e.compiledArtifactsBootstrapPath,outDir:e.workflowBuildDir,rootDir:f(),watch:!1}),n=await Qn(e.outputDir);await t.buildVercelOutput({flowNitroOutputDir:e.flowNitroOutputDir,outputDir:e.outputDir,runtime:n})}async function er(e){let t=Zn(e.options.output.dir);return await E(t),await Ce(e),await be(e),await we(e),await ye(e),await De(t),t}async function tr(e,t){let n=await X(e,!1,{outputDir:r(e.appRoot,t),surface:t});try{return await er(n)}finally{await n.close()}}async function nr(e){let t=await ie(e);if(!process.env.VERCEL){let e=await X(t,!1);try{let n=await er(e);return await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),n}finally{await e.close()}}let n=await X(t,!1,{surface:`app`});try{let e=await er(n);await Xn({appRoot:t.appRoot,log(e){console.log(e)}});let r=await tr(t,`flow`);return await $n({appRoot:t.appRoot,compiledArtifactsBootstrapPath:t.compiledArtifacts.bootstrapPath,flowNitroOutputDir:r,outputDir:e,workflowBuildDir:t.workflowBuildDir}),await Bn({manifest:t.compileResult.manifest,appRoot:t.appRoot}),e}finally{await n.close()}}const Z=65535,Q=`WORKFLOW_LOCAL_BASE_URL`,$=`PORT`,rr=new Set([`[::]`,`::`,`0.0.0.0`]);function ir(e){let t=new URL(e);return rr.has(t.hostname)?(t.hostname=`127.0.0.1`,t.toString()):e}function ar(e){return e instanceof Error&&`code`in e&&e.code===`EADDRINUSE`}function or(e){let t=typeof e==`string`?Number(e):e??3e3;if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid development server port "${String(e)}". Expected an integer between 0 and ${Z}.`);return t}function sr(){let e=process.env[$];if(e===void 0||e.trim()===``)return;let t=Number(e);if(!Number.isInteger(t)||t<0||t>Z)throw Error(`Invalid ${$} environment variable "${e}". Expected an integer between 0 and ${Z}.`);return t}function cr(e){let t=or(e.port);if(t===0||!e.retryOnAddressInUse)return[t];let n=[];for(let e=0;e<10;e+=1){let r=t+e;if(r>65535)break;n.push(r)}return n}function lr(e){let t=process.env[Q],n=process.env[$],r=new URL(ir(e));return process.env[Q]=r.origin,r.port&&(process.env[$]=r.port),()=>{t===void 0?delete process.env[Q]:process.env[Q]=t,n===void 0?delete process.env[$]:process.env[$]=n}}function ur(e){let t=()=>{};return e.once(`error`,t),()=>{e.off(`error`,t)}}function dr(e){let t=e.upgrade.bind(e);e.upgrade=async(e,n,r)=>{let i=ur(n);try{await t(e,n,r)}catch{n.destroyed||n.destroy()}finally{i()}}}async function fr(e){let t=cr({port:e.port,retryOnAddressInUse:e.retryOnAddressInUse}),n;for(let r of t){let t=e.devServer.listen({hostname:e.host,port:r,silent:!0});try{return await t.ready(),t}catch(r){if(n=r,await t.close().catch(()=>{}),!ar(r)||!e.retryOnAddressInUse)throw r}}throw Error(`Failed to start Nitro dev server after ${t.length} attempts. Tried ports ${t.join(`, `)}.`,{cause:n})}async function pr(e,t={}){let n=t.schedules===!0,r=await ie(e);await se({appRoot:r.appRoot,log:e=>console.log(e)});let i=await X(r,!0,{schedules:n}),a=xe(i);dr(a);let o=t.host??i.options.devServer.hostname,s=t.port??sr(),c=s??i.options.devServer.port,l=s===void 0,u;try{let e=await fr({devServer:a,host:o,port:c,retryOnAddressInUse:l});if(!e.url)throw Error(`Nitro dev server did not expose a URL.`);u=lr(e.url),await Ce(i),await ye(i);let{startAuthoredSourceWatcher:t}=await import(`./dev-authored-source-watcher-DtLxnrXI.js`),s=await t({nitro:i,preparedHost:r,schedulesEnabled:n}),d=u;if(d===void 0)throw Error(`Workflow local queue environment was not initialized.`);return{async close(){try{await s.close(),await a.close(),await i.close()}finally{d()}},url:ir(e.url)}}catch(e){throw u?.(),await a.close().catch(()=>{}),await i.close().catch(()=>{}),e}}var mr=e({buildHost:()=>hr,startHost:()=>gr});async function hr(e){return await nr(e)}async function gr(e,t={}){return await pr(e,t)}export{gr as n,mr as t};
@@ -1,7 +1,7 @@
1
1
  import{i as e}from"./chunk-8L7ocgPr.js";import{t}from"./gray-matter-BxS7ZG-J.js";import{c as n,d as r,f as i,l as a,o,p as s,s as c,t as l,u}from"./authored-module-loader-XcFLnl49.js";import{n as d,t as f}from"./guards-CjJ3lmju.js";import{t as p}from"./errors-DsO9xmQL.js";import{n as m,o as h,r as g,t as _}from"./package-DmsQgn4v.js";import{a as v,b as ee,i as te,n as ne,o as re,r as ie,s as ae,t as oe,u as se,y as ce}from"./types-MZUhN0Zy.js";import{t as le}from"./runtime-model-BWu6M_hq.js";import{z as y}from"#compiled/zod/index.js";import{basename as ue,dirname as b,join as x,posix as de,relative as fe,resolve as S,sep as pe}from"node:path";import{access as me,cp as he,mkdir as C,readFile as ge,readdir as _e,rm as ve,stat as ye,writeFile as w}from"node:fs/promises";import{createHash as be}from"node:crypto";import{pathToFileURL as xe}from"node:url";import"#compiled/@workflow/errors/index.js";import{resumeHook as Se}from"#compiled/@workflow/core/runtime.js";import{AsyncLocalStorage as Ce}from"node:async_hooks";import{SpanStatusCode as we,trace as Te}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage as Ee}from"#compiled/@ai-sdk/provider/index.js";import{inspect as De}from"node:util";import{fromError as Oe}from"#compiled/zod-validation-error/index.js";import{createRemoteJWKSet as ke,decodeJwt as Ae,jwtVerify as je}from"#compiled/jose/index.js";import Me from"#compiled/turndown/index.js";const Ne=y.union([y.literal(`error`),y.literal(`warning`)]);y.object({code:y.string(),message:y.string(),severity:Ne,sourcePath:y.string()}).strict();const Pe=y.object({errors:y.number().finite(),warnings:y.number().finite()}).strict();function Fe(e){return e}function T(e){return Fe({...e,severity:`error`})}function Ie(e){return Fe({...e,severity:`warning`})}function Le(e){return e.reduce((e,t)=>(t.severity===`error`?e.errors+=1:e.warnings+=1,e),{errors:0,warnings:0})}function Re(e){return e.some(e=>e.severity===`error`)}const ze=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],Be=[`package.json`,`vercel.json`],Ve=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],He=[`channels`,`connections`,`hooks`,`lib`,`sandbox`,`skills`,`tools`,`schedules`,`subagents`],Ue=[`agent.ts`,`agent.cts`,`agent.mts`,`agent.js`,`agent.cjs`,`agent.mjs`,`instructions.md`,`instructions.ts`,`instructions.cts`,`instructions.mts`,`instructions.js`,`instructions.cjs`,`instructions.mjs`,`system.md`,`system.ts`,`system.cts`,`system.mts`,`system.js`,`system.cjs`,`system.mjs`],We=[`hooks`,`lib`,`sandbox`,`skills`,`tools`,`subagents`],Ge=[`SKILL.md`],Ke=[`scripts`,`references`,`assets`],qe=new Set(Be);new Set(Ve),new Set(He),new Set(Ue),new Set(We),new Set(Ge),new Set(Ke);function E(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function Je(e,t){return t===`file`&&qe.has(e)}function Ye(e,t){if(t===`file`)return k(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:k(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:k(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function Xe(e,t){if(t===`file`)return k(e,`agent`)?`agent-config-module`:e===`instructions.md`?`instructions-markdown`:k(e,`instructions`)?`instructions-module`:e===`system.md`?`system-markdown`:k(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(e===`connections`)return`connections-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function Ze(e,t){if(t===`file`)return e===`SKILL.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function Qe(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(e.endsWith(`.md`))return`flat-skill-markdown`;if(O(e)!==null)return`flat-skill-module`}return`unknown`}function D(e){return e.replaceAll(pe,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function O(e){for(let t of ze)if(e.endsWith(t)&&e.length>t.length)return e.slice(0,-t.length);return null}function k(e,t){return O(e)===t}function A(e){let t=D(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}var $e=e(t(),1);function et(e,t){let r=c(e,t);if(n(r,[`build`,`compaction`,`description`,`metadata`,`model`,`modelContextWindowTokens`,`modelOptions`],t),r.model===void 0)throw Error(`${t} The "model" field is required.`);let a={model:r.model};r.description!==void 0&&(a.description=u(r.description,t));let o=i(r,`metadata`,t);return o!==void 0&&(a.metadata=o),r.compaction!==void 0&&(a.compaction=it(r.compaction,t)),r.build!==void 0&&(a.build=nt(r.build,t)),r.modelOptions!==void 0&&(a.modelOptions=rt(r.modelOptions,t)),r.modelContextWindowTokens!==void 0&&(a.modelContextWindowTokens=tt(r.modelContextWindowTokens,t)),a}function tt(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<=0)throw Error(t);return e}function nt(e,t){let r=c(e,t);n(r,[`externalDependencies`],t);let i={};if(r.externalDependencies!==void 0){if(!Array.isArray(r.externalDependencies))throw Error(t);i.externalDependencies=Object.freeze(r.externalDependencies.map(e=>u(e,t)))}return i}function rt(e,t){let r=c(e,t);n(r,[`providerOptions`],t);let i=r.providerOptions;return i===void 0?{}:{providerOptions:a(i,t)}}function it(e,t){let r=c(e,t);n(r,[`model`,`modelContextWindowTokens`,`thresholdPercent`],t);let i={};if(r.model!==void 0&&(i.model=r.model),r.modelContextWindowTokens!==void 0&&(i.modelContextWindowTokens=tt(r.modelContextWindowTokens,t)),r.thresholdPercent!==void 0){let e=r.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(t);i.thresholdPercent=e}return i}function at(e,t){let r=c(e,t);return n(r,[`markdown`],t),{markdown:u(r.markdown,t)}}function ot(e,t){let r=c(e,t);n(r,[`description`,`license`,`markdown`,`metadata`],t);let a={description:u(r.description,t),markdown:u(r.markdown,t)},o=r.license,s=i(r,`metadata`,t);return o!==void 0&&(a.license=u(o,t)),s!==void 0&&(a.metadata=s),a}function st(e,t){let r=c(e,t);n(r,[`cron`,`markdown`,`run`],t);let i=u(r.cron,t),a=r.markdown!==void 0,s=r.run!==void 0;if(a&&s)throw Error(`${t} Pass either "markdown" (fire-and-forget) or "run" (handler) — not both.`);if(!a&&!s)throw Error(`${t} Must provide either "markdown" (fire-and-forget) or "run" (handler).`);let l={cron:i};return a?l.markdown=u(r.markdown,t):l.run=o(r.run,t),l}function ct(e){return e}function lt(e){return e}function ut(e){return e}const dt=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;function ft(e){if(!$e.default.test(e))return{hasFrontmatter:!1,frontmatter:{},markdown:e};let t;try{t=(0,$e.default)(e)}catch(t){throw gt(e)&&!_t(e)?Error(`Markdown frontmatter is missing a closing delimiter.`):t}if(!d(t.data))throw Error(`Markdown frontmatter must parse to an object.`);return{hasFrontmatter:!0,frontmatter:t.data,markdown:vt(t.content)}}function pt(e){return ut(at({markdown:e},`Expected authored instructions markdown to match the public Ash shape.`))}function mt(e){let t=ft(e);if(!t.hasFrontmatter)throw Error(`Schedule markdown must start with YAML frontmatter declaring "cron".`);if(`run`in t.frontmatter)throw Error('Markdown-form schedules do not support the "run" frontmatter key. Use a TypeScript schedule (`<name>.ts`) to author a handler.');return ct(st({...t.frontmatter,markdown:t.markdown},`Expected authored schedule markdown to match the public Ash shape.`))}function ht(e,t={}){let n=ft(e),r=t.slug;if(r===void 0&&!n.hasFrontmatter)throw Error(`Skill markdown must start with YAML frontmatter.`);let i=xt(n.frontmatter),a=St(i.description,`description`),o=r===void 0?Ct(i.description,`description`):a??t.description??Tt(n.markdown,r),s={...i,description:o,markdown:n.markdown};return yt(s,i),lt(ot(s,`Expected authored skill markdown to match the public Ash shape.`))}function gt(e){return e.startsWith(`---
2
2
  `)||e.startsWith(`---\r
3
3
  `)}function _t(e){return dt.test(e)}function vt(e){return e.replace(/^\r?\n/u,``)}function yt(e,t){let n=St(t.license,`license`);n!==void 0&&(e.license=n);let r=wt(t.metadata,`metadata`);r!==void 0&&(e.metadata=r)}const bt=[`name`];function xt(e){let t={...e};for(let e of bt)delete t[e];return t}function St(e,t){if(e!=null){if(typeof e!=`string`)throw Error(`Expected "${t}" frontmatter to be a string.`);return e}}function Ct(e,t){let n=St(e,t);if(n===void 0)throw Error(`Missing required "${t}" frontmatter.`);return n}function wt(e,t){if(e==null)return;if(!d(e))throw Error(`Expected "${t}" frontmatter to be an object.`);let n=Object.entries(e).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected "${t}.${e}" frontmatter to be a string.`);return[e,n]});return Object.fromEntries(n)}function Tt(e,t){let n=e.split(/\r?\n/u).map(e=>e.trim()).find(e=>e!==``&&!e.startsWith("```"));return n===void 0?`Instructions for the ${t} skill.`:n.replace(/^[#>*\-\s]+/u,``).trim()||`Instructions for the ${t} skill.`}function Et(e){let t=S(e.appRoot),n=S(e.agentRoot),r={agentId:e.agentId??Dt(t,n,e.packageName),agentRoot:n,appRoot:t,channels:[...e.channels??[]],connections:[...e.connections??[]],diagnosticsSummary:Le(e.diagnostics??[]),hooks:[...e.hooks??[]],lib:[...e.lib??[]],kind:`ash-agent-discovery-manifest`,sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],version:12,subagents:[...e.subagents??[]]};return e.configModule!==void 0&&(r.configModule=e.configModule),e.instructions!==void 0&&(r.instructions=e.instructions),r}function Dt(e,t,n){let r=D(fe(e,t));return r===``||r===`.`||r===`agent`?n??ue(e):ue(t)}function j(e){return D(e)}function M(e){let t=D(e.logicalPath),n={sourceKind:`module`,logicalPath:t,sourceId:e.sourceId??j(t)};return e.exportName!==void 0&&(n.exportName=e.exportName),n}function Ot(e){return{...M(e),connectionName:e.connectionName}}function kt(e){let t=D(e.logicalPath);return{entryPath:e.entryPath,logicalPath:t,manifest:e.manifest,rootPath:e.rootPath,sourceId:e.sourceId??j(t),subagentId:e.subagentId}}function At(e){let t={description:e.description,sourceKind:`skill-package`,logicalPath:D(e.logicalPath),markdown:e.markdown,name:e.name,rootPath:e.rootPath,skillFilePath:e.skillFilePath,skillId:e.skillId,sourceId:e.sourceId};return e.assetsPath!==void 0&&(t.assetsPath=e.assetsPath),e.license!==void 0&&(t.license=e.license),e.metadata!==void 0&&(t.metadata={...e.metadata}),e.referencesPath!==void 0&&(t.referencesPath=e.referencesPath),e.scriptsPath!==void 0&&(t.scriptsPath=e.scriptsPath),t}async function jt(e){let t=D(e.logicalPath);return{definition:e.lower(await e.source.readTextFile(e.sourcePath),{name:A(t)}),sourceKind:`markdown`,logicalPath:t,sourceId:j(t)}}function Mt(e,t){let n={moduleFileNames:[]};for(let r of e)if(r.isFile()){if(t.markdownFileName!==void 0&&r.name===t.markdownFileName){n.markdownFileName=r.name;continue}t.moduleBaseName!==void 0&&O(r.name)===t.moduleBaseName&&n.moduleFileNames.push(r.name)}return n.moduleFileNames.sort((e,t)=>e.localeCompare(t)),n}function Nt(e,t){let n=new Map;for(let r of e){if(!r.isFile())continue;let e=t.allowMarkdown?Pt(r.name):null,i=t.allowModules?O(r.name):null,a=e??i;if(a===null)continue;let o=n.get(a);if(o===void 0&&(o={moduleFileNames:[],slotName:a},n.set(a,o)),e!==null){o.markdownFileName=r.name;continue}i!==null&&o.moduleFileNames.push(r.name)}return[...n.values()].map(e=>(e.moduleFileNames.sort((e,t)=>e.localeCompare(t)),e)).sort((e,t)=>e.slotName.localeCompare(t.slotName))}function Pt(e){return!e.endsWith(`.md`)||e.length<=3?null:e.slice(0,-3)}async function N(e){let t=x(e.rootPath,e.directoryName),n=e.rootEntries.find(t=>t.name===e.directoryName);if(n===void 0)return{diagnostics:[],sources:[]};if(!n.isDirectory())return{diagnostics:[T({code:e.invalidDirectoryCode,message:e.invalidDirectoryMessage,sourcePath:t})],sources:[]};let r=[],i=[];return await Ft({allowMarkdown:e.allowMarkdown===!0,diagnostics:r,markdownLowerer:e.allowMarkdown===!0?e.markdownLowerer:void 0,projectSource:e.source,recursive:e.recursive,relativeDirectory:e.directoryName,rootDirectoryPath:t,sources:i,subdirectoryRelative:``,unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment}),{diagnostics:r,sources:i}}async function Ft(e){let t=e.subdirectoryRelative===``?e.rootDirectoryPath:x(e.rootDirectoryPath,e.subdirectoryRelative),n=await P(e.projectSource,t);e.recursive&&await It(e,n,t),(e.unsupportedFileCode!==void 0||e.unsupportedEntryCode!==void 0)&&Lt(e,n,t),await Rt(e,n,t)}async function It(e,t,n){for(let r of t){if(!r.isDirectory())continue;let t=x(n,r.name);if(e.validateSegment!==void 0){let n=e.validateSegment(r.name,t);if(n!==null){e.diagnostics.push(n);continue}}await Ft({allowMarkdown:e.allowMarkdown,diagnostics:e.diagnostics,markdownLowerer:e.markdownLowerer,projectSource:e.projectSource,recursive:e.recursive,relativeDirectory:e.relativeDirectory,rootDirectoryPath:e.rootDirectoryPath,sources:e.sources,subdirectoryRelative:e.subdirectoryRelative===``?r.name:x(e.subdirectoryRelative,r.name),unsupportedEntryCode:e.unsupportedEntryCode,unsupportedEntryMessage:e.unsupportedEntryMessage,unsupportedFileCode:e.unsupportedFileCode,unsupportedFileMessage:e.unsupportedFileMessage,validateSegment:e.validateSegment})}}function Lt(e,t,n){for(let r of t){let t=E(r),i=x(n,r.name);if(t===`directory`)continue;if(t===`other`){e.unsupportedEntryCode!==void 0&&e.diagnostics.push(T({code:e.unsupportedEntryCode,message:e.unsupportedEntryMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a regular file or directory within "${e.relativeDirectory}/".`,sourcePath:i}));continue}if(e.unsupportedFileCode===void 0)continue;let a=O(r.name)!==null,o=e.allowMarkdown&&r.name.endsWith(`.md`);a||o||e.diagnostics.push(T({code:e.unsupportedFileCode,message:e.unsupportedFileMessage?.(i,e.relativeDirectory)??`Expected "${i}" to be a supported authored source within "${e.relativeDirectory}/".`,sourcePath:i}))}}async function Rt(e,t,n){for(let r of Nt(t,{allowMarkdown:e.allowMarkdown,allowModules:!0})){let t=e.subdirectoryRelative===``?r.slotName:x(e.subdirectoryRelative,r.slotName),i=D(x(e.relativeDirectory,t));if(e.validateSegment!==void 0){let t=r.markdownFileName??r.moduleFileNames[0]??r.slotName,i=e.validateSegment(r.slotName,x(n,t));if(i!==null){e.diagnostics.push(i);continue}}if(r.markdownFileName!==void 0&&r.moduleFileNames.length>0){e.diagnostics.push($t(n,i,[r.markdownFileName,...r.moduleFileNames]));continue}if(r.moduleFileNames.length>1){e.diagnostics.push(en(n,i,r.moduleFileNames));continue}if(r.markdownFileName!==void 0){let t=e.subdirectoryRelative===``?r.markdownFileName:x(e.subdirectoryRelative,r.markdownFileName),n=D(x(e.relativeDirectory,t));if(e.markdownLowerer===void 0)continue;let i=await jt({logicalPath:n,lower:e.markdownLowerer,source:e.projectSource,sourcePath:x(e.rootDirectoryPath,t)});e.sources.push(i);continue}let[a]=r.moduleFileNames;if(a===void 0)continue;let o=e.subdirectoryRelative===``?a:x(e.subdirectoryRelative,a);e.sources.push(M({logicalPath:D(x(e.relativeDirectory,o))}))}}const zt=`discover/module-slot-collision`,Bt=`discover/tools-directory-invalid`,Vt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Ht=/^[a-z][a-z0-9-]{0,63}$/,Ut=/^(\.?[a-z][a-z0-9-]{0,63}|\[[a-zA-Z][a-zA-Z0-9_]{0,63}\])$/,Wt=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;async function P(e,t){let n=[...await e.readDirectory(t)];return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function Gt(e){let t=await Kt({markdownFileName:`instructions.md`,moduleBaseName:`instructions`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`instructions`,source:e.source});if(t.diagnostics.length>0||t.source!==void 0)return{diagnostics:t.diagnostics,instructions:t.source};let n=await Kt({markdownFileName:`system.md`,moduleBaseName:`system`,rootEntries:e.rootEntries,rootPath:e.rootPath,slotLabel:`system`,source:e.source});if(n.source!==void 0){let t=n.source.sourceKind===`markdown`?`system.md`:n.source.logicalPath;return{diagnostics:[Ie({code:`discover/deprecated-system-slot`,message:`The "${t}" slot is deprecated. Rename it to "${t.replace(/^system/,`instructions`)}" — the runtime still loads the legacy slot for now, but support will be removed in a future release.`,sourcePath:x(e.rootPath,t)}),...n.diagnostics],instructions:n.source}}return n.diagnostics.length>0?{diagnostics:n.diagnostics}:{diagnostics:[T({code:`discover/required-instructions-missing`,message:`Expected one authored instructions prompt source at "instructions.md", "instructions.ts", "instructions.cts", "instructions.mts", "instructions.js", "instructions.cjs", or "instructions.mjs".`,sourcePath:e.rootPath})]}}async function Kt(e){let t=Mt(e.rootEntries,{markdownFileName:e.markdownFileName,moduleBaseName:e.moduleBaseName});if(t.markdownFileName!==void 0&&t.moduleFileNames.length>0)return{diagnostics:[$t(e.rootPath,e.slotLabel,[t.markdownFileName,...t.moduleFileNames])]};if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotLabel,t.moduleFileNames)]};if(t.markdownFileName!==void 0)return{diagnostics:[],source:await jt({logicalPath:e.markdownFileName,lower:pt,source:e.source,sourcePath:x(e.rootPath,t.markdownFileName)})};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:[]}:{diagnostics:[],source:M({logicalPath:n})}}function qt(e){let t=Mt(e.rootEntries,{moduleBaseName:e.slotName});if(t.moduleFileNames.length>1)return{diagnostics:[en(e.rootPath,e.slotName,t.moduleFileNames)]};let[n]=t.moduleFileNames;return n===void 0?e.missingDiagnostic===void 0?{diagnostics:[]}:{diagnostics:[T({code:e.missingDiagnostic.code,message:e.missingDiagnostic.message,sourcePath:e.rootPath})]}:{diagnostics:[],module:M({logicalPath:n})}}function Jt(e,t){return Vt.test(e)?null:T({code:`discover/tool-name-invalid`,message:`Tool filename "${e}" is not a legal tool name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Yt(e,t){return Ht.test(e)?null:T({code:`discover/connection-name-invalid`,message:`Connection filename "${e}" is not a legal connection name. Expected lowercase ASCII letters, digits, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Xt(e,t){return Ut.test(e)?null:T({code:`discover/channel-name-invalid`,message:`Channel path segment "${e}" is not a legal channel name. Expected lowercase kebab-case (\`my-channel\`), optionally with a leading dot (\`.well-known\`), or a path parameter form (\`[sessionId]\`).`,sourcePath:t})}function Zt(e,t){return Wt.test(e)?null:T({code:`discover/hook-name-invalid`,message:`Hook path segment "${e}" is not a legal hook name. Expected ASCII letters, digits, underscores, and dashes only, starting with a letter, up to 64 characters.`,sourcePath:t})}function Qt(e){return e.rootEntries.flatMap(t=>!t.isDirectory()||e.classifyEntry(t.name,E(t))!==`unknown`?[]:[Ie({code:`discover/unsupported-directory`,message:e.createUnsupportedDirectoryMessage(t.name),sourcePath:x(e.rootPath,t.name)})])}function $t(e,t,n){return T({code:`discover/slot-collision`,message:`Found conflicting authored sources for "${t}": ${tn(n)}.`,sourcePath:e})}function en(e,t,n){return T({code:zt,message:`Found multiple authored module sources for "${t}": ${tn(n)}.`,sourcePath:e})}function tn(e){return e.map(e=>`"${e}"`).join(`, `)}async function nn(e){let t=`connections`,n=x(e.rootPath,t),r=e.rootEntries.find(e=>e.name===t);if(r===void 0)return{connections:[],diagnostics:[]};if(!r.isDirectory())return{connections:[],diagnostics:[T({code:`discover/connections-directory-invalid`,message:`Expected "${n}" to be a directory of authored connections.`,sourcePath:n})]};let i=await P(e.source,n),a=[],o=[],s=new Set;for(let e of Nt(i,{allowMarkdown:!1,allowModules:!0})){let r=D(x(t,e.slotName));if(e.moduleFileNames.length>1){s.add(e.slotName),o.push(en(n,r,e.moduleFileNames));continue}let[i]=e.moduleFileNames;if(i===void 0)continue;s.add(e.slotName);let c=Yt(e.slotName,x(n,i));if(c!==null){o.push(c);continue}a.push(Ot({connectionName:e.slotName,logicalPath:x(t,i)}))}for(let r of i){if(!r.isDirectory())continue;let i=r.name,c=x(n,i);if(s.has(i)){o.push(T({code:`discover/connection-file-folder-collision`,message:`Connection "${i}" is defined twice. Found both file-form "connections/${i}.ts" and folder-form "connections/${i}/". Use one form, not both.`,sourcePath:c}));let e=a.findIndex(e=>e.connectionName===i);e!==-1&&a.splice(e,1);continue}let l=Yt(i,c);if(l!==null){o.push(l);continue}let u=rn(await P(e.source,c));if(u.length>1){o.push(T({code:zt,message:`Found multiple connection definition modules inside "${D(x(t,i))}": `+u.map(e=>`"${e}"`).join(`, `),sourcePath:c}));continue}let[d]=u;if(d===void 0){o.push(T({code:`discover/connection-folder-empty`,message:`Connection folder "connections/${i}/" contains no "connection.ts" definition. Add "connections/${i}/connection.ts" or use the file form "connections/${i}.ts".`,sourcePath:c}));continue}a.push(Ot({connectionName:i,logicalPath:x(t,i,d)}))}return{connections:a,diagnostics:o}}function rn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===`connection`&&n.push(...e.moduleFileNames);return n}const an=`discover/lib-entry-unsupported`;async function on(e){let t=await N({directoryName:`lib`,invalidDirectoryCode:`discover/lib-directory-invalid`,invalidDirectoryMessage:`Expected "${e.agentRoot}/lib" to be a directory of authored helper modules.`,recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedEntryCode:an,unsupportedEntryMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`,unsupportedFileCode:an,unsupportedFileMessage:e=>`Expected "${e}" to be a supported authored module within "lib/".`});return{diagnostics:t.diagnostics,lib:t.sources}}function F(){return{kind:`disk`,async readDirectory(e){return await _e(e,{withFileTypes:!0})},async readTextFile(e){return await ge(e,`utf8`)},async stat(e){try{let t=await ye(e);return t.isDirectory()?`directory`:t.isFile()?`file`:`other`}catch{return`missing`}}}}const I=`sandbox`,sn=`workspace`,cn=`sandbox`;async function ln(e){let t=[],n=e.rootEntries.find(e=>e.name===I);if(n===void 0)return un({diagnostics:t,rootEntries:e.rootEntries,rootPath:e.rootPath});let r=x(e.rootPath,I);if(!n.isDirectory())return t.push(T({code:`discover/sandbox-directory-invalid`,message:`Expected "${r}" to be the sandbox folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let i=await P(e.source,r),a=dn(i),o=i.find(e=>e.name===sn&&e.isDirectory());if(a.length>1)return t.push(T({code:zt,message:`Found multiple sandbox definition modules inside "${D(I)}": `+a.map(e=>`"${e}"`).join(`, `),sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let[s]=a,c=s!==void 0,l=o!==void 0;if(!c&&!l)return t.push(T({code:`discover/sandbox-folder-empty`,message:`Sandbox folder "sandbox/" contains neither a "sandbox.<ext>" definition nor a "workspace/" subdirectory. Add one or the other, or remove the folder.`,sourcePath:r})),{diagnostics:t,sandbox:null,sandboxWorkspace:null};let u=null;c&&(u=M({logicalPath:x(I,s)}));let d=null;if(l){let n=x(r,sn),i=D(x(I,sn)),a=await pn(e.source,n);a===null?d={logicalPath:i,rootEntries:await fn(e.source,n),sourceId:j(i),sourcePath:n}:t.push(a)}return{diagnostics:t,sandbox:u,sandboxWorkspace:d}}function un(e){let t=Mt(e.rootEntries,{moduleBaseName:cn});if(t.moduleFileNames.length>1)return e.diagnostics.push(T({code:zt,message:`Found multiple top-level sandbox definition modules: `+t.moduleFileNames.map(e=>`"${e}"`).join(`, `),sourcePath:e.rootPath})),{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null};let[n]=t.moduleFileNames;return n===void 0?{diagnostics:e.diagnostics,sandbox:null,sandboxWorkspace:null}:{diagnostics:e.diagnostics,sandbox:M({logicalPath:n}),sandboxWorkspace:null}}function dn(e){let t=e.filter(e=>e.isFile()),n=[];for(let e of Nt(t,{allowMarkdown:!1,allowModules:!0}))e.slotName===cn&&n.push(...e.moduleFileNames);return n}async function fn(e,t){let n=await P(e,t),r=[];for(let e of n){if(e.isDirectory()){r.push(`${e.name}/`);continue}e.isFile()&&r.push(e.name)}return r}async function pn(e,t){return(await P(e,t)).find(e=>e.name===`skills`)===void 0?null:T({code:`discover/sandbox-workspace-skills-reserved`,message:`"sandbox/workspace/skills/" is reserved for the framework skill discovery. Move skill files under "agent/skills/" instead, or rename the subtree.`,sourcePath:x(t,`skills`)})}const mn=`discover/skill-frontmatter-invalid`;async function hn(e){let t=e.source??F(),n=S(e.agentRoot),r=S(e.skillsDirectoryPath??x(n,`skills`)),i=D(e.skillsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],skills:[]};if(a!==`directory`)return{diagnostics:[T({code:`discover/skills-directory-invalid`,message:`Expected "${r}" to be a directory of authored skills.`,sourcePath:r})],skills:[]};let o=[],s=new Set,c=new Map,l=await P(t,r);for(let e of l){let n=await gn({entryName:e.name,entryType:E(e),skillsDirectoryPath:r,skillsLogicalPath:i,source:t});if(o.push(...n.diagnostics),n.skill===null||n.skillId===null||s.has(n.skillId))continue;let a=c.get(n.skillId);if(a!==void 0){o.push(T({code:`discover/skill-collision`,message:`Found conflicting authored skill sources for "${n.skillId}": "${a.logicalPath}" and "${n.logicalPath}".`,sourcePath:x(r,n.skillId)})),s.add(n.skillId),c.delete(n.skillId);continue}c.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:o,skills:[...c.values()].map(e=>e.skill)}}async function gn(e){let t=x(e.skillsDirectoryPath,e.entryName);switch(Qe(e.entryName,e.entryType)){case`skill-package-directory`:return _n({logicalSkillsPath:e.skillsLogicalPath,skillId:e.entryName,skillRootPath:t,source:e.source});case`flat-skill-markdown`:return vn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName,skillFilePath:t,source:e.source});case`flat-skill-module`:return yn({logicalSkillsPath:e.skillsLogicalPath,skillFileName:e.entryName});default:return{diagnostics:[T({code:`discover/skill-entry-not-directory`,message:`Expected "${t}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:t})],logicalPath:D(x(e.skillsLogicalPath,e.entryName)),skill:null,skillId:null}}}async function _n(e){let t=x(e.skillRootPath,`SKILL.md`),n=D(x(e.logicalSkillsPath,e.skillId,`SKILL.md`));if(await e.source.stat(t)!==`file`)return{diagnostics:[T({code:`discover/skill-markdown-missing`,message:`Expected "${t}" to exist for the "${e.skillId}" skill.`,sourcePath:e.skillRootPath})],logicalPath:n,skill:null,skillId:null};let r;try{r=ht(await e.source.readTextFile(t))}catch(e){return{diagnostics:[T({code:mn,message:xn(t,e),sourcePath:t})],logicalPath:n,skill:null,skillId:null}}let i=await bn(e.source,e.skillRootPath),a={description:r.description,logicalPath:n,markdown:r.markdown,name:e.skillId,rootPath:e.skillRootPath,skillFilePath:t,skillId:e.skillId,sourceId:j(n)};return i.assetsPath!==void 0&&(a.assetsPath=i.assetsPath),r.license!==void 0&&(a.license=r.license),r.metadata!==void 0&&(a.metadata=r.metadata),i.referencesPath!==void 0&&(a.referencesPath=i.referencesPath),i.scriptsPath!==void 0&&(a.scriptsPath=i.scriptsPath),{diagnostics:[],logicalPath:n,skill:At(a),skillId:e.skillId}}async function vn(e){let t=Sn(e.skillFileName),n=D(x(e.logicalSkillsPath,e.skillFileName)),r;try{r=ht(await e.source.readTextFile(e.skillFilePath),{slug:t})}catch(t){return{diagnostics:[T({code:mn,message:xn(e.skillFilePath,t),sourcePath:e.skillFilePath})],logicalPath:n,skill:null,skillId:null}}return{diagnostics:[],logicalPath:n,skill:{definition:r,sourceKind:`markdown`,logicalPath:n,sourceId:j(n)},skillId:t}}async function yn(e){let t=O(e.skillFileName),n=D(x(e.logicalSkillsPath,e.skillFileName));return t===null?{diagnostics:[],logicalPath:n,skill:null,skillId:null}:{diagnostics:[],logicalPath:n,skill:M({logicalPath:n}),skillId:t}}async function bn(e,t){let n=await e.readDirectory(t),r={};for(let e of n)if(e.isDirectory())switch(Ze(e.name,E(e))){case`skill-assets-directory`:r.assetsPath=x(t,e.name);break;case`skill-references-directory`:r.referencesPath=x(t,e.name);break;case`skill-scripts-directory`:r.scriptsPath=x(t,e.name);break;default:break}return r}function xn(e,t){return`Invalid authored skill frontmatter in "${e}": ${p(t)}`}function Sn(e){return e.endsWith(`.md`)?e.slice(0,-3):e}async function Cn(e){let t=e.source??F(),n=S(e.agentRoot),r=S(e.subagentsDirectoryPath??x(n,`subagents`)),i=D(e.subagentsLogicalPath??fe(n,r)),a=await t.stat(r);if(a===`missing`)return{diagnostics:[],subagents:[]};if(a!==`directory`)return{diagnostics:[T({code:`discover/subagents-directory-invalid`,message:`Expected "${r}" to be a directory of authored subagents.`,sourcePath:r})],subagents:[]};let o=await P(t,r),s=[],c=[];for(let n of o){if(!n.isDirectory())continue;let a=await wn({appRoot:e.appRoot,source:t,subagentId:n.name,subagentLogicalPath:x(i,n.name),subagentRoot:x(r,n.name)});s.push(...a.diagnostics),c.push(a.subagent)}return{diagnostics:s,subagents:c}}async function wn(e){let t=[],n=await P(e.source,e.subagentRoot);t.push(...Qt({classifyEntry:Xe,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the local subagent root.`},rootEntries:n,rootPath:e.subagentRoot}));let r=await Gt({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...r.diagnostics);let i=qt({missingDiagnostic:{code:`discover/required-subagent-config-module-missing`,message:`Expected one authored subagent config module at "agent.ts", "agent.cts", "agent.mts", "agent.js", "agent.cjs", or "agent.mjs".`},rootEntries:n,rootPath:e.subagentRoot,slotName:`agent`});t.push(...i.diagnostics);let a=await nn({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...a.diagnostics);let o=await ln({rootEntries:n,rootPath:e.subagentRoot,source:e.source});t.push(...o.diagnostics);let s=await N({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${x(e.subagentRoot,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Jt});t.push(...s.diagnostics);let c=await N({directoryName:`hooks`,invalidDirectoryCode:Dn,invalidDirectoryMessage:`Expected "${x(e.subagentRoot,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:n,rootPath:e.subagentRoot,source:e.source,validateSegment:Zt});t.push(...c.diagnostics);let l=await on({agentRoot:e.subagentRoot,rootEntries:n,source:e.source});t.push(...l.diagnostics),t.push(...Tn(e.subagentRoot,n));let u=await hn({agentRoot:e.subagentRoot,source:e.source});t.push(...u.diagnostics);let d=await Cn({agentRoot:e.subagentRoot,appRoot:e.appRoot,source:e.source});t.push(...d.diagnostics);let f={agentRoot:e.subagentRoot,appRoot:e.appRoot,connections:a.connections,diagnostics:t,hooks:c.sources,lib:l.lib,instructions:r.instructions,sandbox:o.sandbox,sandboxWorkspaces:o.sandboxWorkspace===null?[]:[o.sandboxWorkspace],skills:u.skills,tools:s.sources,subagents:d.subagents};i.module!==void 0&&(f.configModule=i.module);let p=Et(f);return{diagnostics:t,subagent:kt({entryPath:e.subagentRoot,logicalPath:e.subagentLogicalPath,manifest:p,rootPath:e.subagentRoot,subagentId:e.subagentId})}}function Tn(e,t){return t.flatMap(t=>Xe(t.name,E(t))===`invalid-schedules-directory`?[T({code:`discover/local-subagent-schedules-invalid`,message:`Local subagent packages cannot define schedules at "${x(e,t.name)}".`,sourcePath:x(e,t.name)})]:[])}async function En(e){let t=await N({allowMarkdown:!0,directoryName:`schedules`,invalidDirectoryCode:`discover/schedules-directory-invalid`,invalidDirectoryMessage:`Expected "${x(e.agentRoot,`schedules`)}" to be a directory of authored schedules.`,markdownLowerer:e=>mt(e),recursive:!0,rootEntries:e.rootEntries,rootPath:e.agentRoot,source:e.source,unsupportedFileCode:`discover/schedule-file-unsupported`,unsupportedFileMessage:e=>`Expected "${e}" to be a TypeScript or markdown schedule file within "schedules/".`});return{diagnostics:t.diagnostics,schedules:t.sources}}const Dn=`discover/hooks-directory-invalid`;async function On(e){let t=e.source??F(),n=S(e.appRoot),r=S(e.agentRoot),i=[],a=await kn(t,n),o=await P(t,r);i.push(...Qt({classifyEntry:Ye,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:o,rootPath:r}));let s=await Gt({rootEntries:o,rootPath:r,source:t});i.push(...s.diagnostics);let c=qt({rootEntries:o,rootPath:r,slotName:`agent`});i.push(...c.diagnostics);let l=await N({directoryName:`channels`,invalidDirectoryCode:`discover/channels-directory-invalid`,invalidDirectoryMessage:`Expected "${x(r,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Xt});i.push(...l.diagnostics);let u=await on({agentRoot:r,rootEntries:o,source:t});i.push(...u.diagnostics);let d=await En({agentRoot:r,rootEntries:o,source:t});i.push(...d.diagnostics);let f=await nn({rootEntries:o,rootPath:r,source:t});i.push(...f.diagnostics);let p=await ln({rootEntries:o,rootPath:r,source:t});i.push(...p.diagnostics);let m=await N({directoryName:`tools`,invalidDirectoryCode:Bt,invalidDirectoryMessage:`Expected "${x(r,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Jt});i.push(...m.diagnostics);let h=await N({directoryName:`hooks`,invalidDirectoryCode:Dn,invalidDirectoryMessage:`Expected "${x(r,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:o,rootPath:r,source:t,validateSegment:Zt});i.push(...h.diagnostics);let g=await hn({agentRoot:r,source:t});i.push(...g.diagnostics);let _=await Cn({agentRoot:r,appRoot:n,source:t});i.push(..._.diagnostics);let v={agentRoot:r,appRoot:n,channels:l.sources,connections:f.connections,packageName:a,diagnostics:i,hooks:h.sources,lib:u.lib,instructions:s.instructions,sandbox:p.sandbox,sandboxWorkspaces:p.sandboxWorkspace===null?[]:[p.sandboxWorkspace],schedules:d.schedules,skills:g.skills,tools:m.sources,subagents:_.subagents};return c.module!==void 0&&(v.configModule=c.module),{diagnostics:i,manifest:Et(v)}}async function kn(e,t){try{let n=x(t,`package.json`),r=JSON.parse(await e.readTextFile(n)).name;if(typeof r!=`string`||r.length===0)return;let i=r.lastIndexOf(`/`);return i===-1?r:r.slice(i+1)}catch{return}}var An=class extends Error{diagnostic;constructor(e){super(e.message),this.name=`DiscoveryProjectResolutionError`,this.diagnostic=e}};async function jn(e=process.cwd(),t={}){let n=t.source??F(),r=await Mn(n,e),i=r;for(;;){let e=await Nn(n,i);if(e!==null)return e;let t=await Pn(n,i);if(t!==null)return t;if(await Fn(n,i))return{agentRoot:i,appRoot:i,layout:`flat`};let r=b(i);if(r===i)break;i=r}throw new An(T({code:`discover/project-not-found`,message:`Could not resolve an Ash agent root from "${r}".`,sourcePath:r}))}async function Mn(e,t){let n=S(t);return await e.stat(n)===`directory`?n:b(n)}async function Nn(e,t){if(ue(t)!==`agent`)return null;let n=b(t);return await In(e,n)?{agentRoot:t,appRoot:n,layout:`nested`}:null}async function Pn(e,t){if(!await In(e,t))return null;let n=x(t,`agent`);return await Rn(e,n)?{agentRoot:n,appRoot:t,layout:`nested`}:null}async function Fn(e,t){let n=await Ln(e,t);return Array.from(n.entries()).some(([e,t])=>{let n=Ye(e,t);return n!==`unknown`&&n!==`lib-directory`})}async function In(e,t){let n=await Ln(e,t);return Array.from(n.entries()).some(([e,t])=>Je(e,t))}async function Ln(e,t){if(await e.stat(t)!==`directory`)return new Map;let n=await e.readDirectory(t);return new Map(n.map(e=>[e.name,E(e)]))}async function Rn(e,t){return await e.stat(t)===`directory`}const zn=`ash-agent-compiled-manifest`,L=`__root__`,Bn=y.object({exportName:y.string().optional(),sourceKind:y.literal(`module`),logicalPath:y.string(),sourceId:y.string()}).strict(),Vn=y.union([y.literal(`GET`),y.literal(`POST`),y.literal(`PUT`),y.literal(`DELETE`),y.literal(`PATCH`)]),Hn=y.object({kind:y.literal(`channel`),name:y.string(),logicalPath:y.string(),method:Vn,urlPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),exportName:y.string().optional(),adapterKind:y.string().optional()}).strict(),Un=y.object({kind:y.literal(`disabled`),name:y.string(),logicalPath:y.string()}).strict(),Wn=y.union([Hn,Un]),Gn=y.object({contextWindowTokens:y.number().int().positive().optional(),id:y.string(),source:Bn.optional(),providerOptions:ce.optional()}).strict(),Kn=y.object({externalDependencies:y.array(y.string()).optional()}).strict(),qn=y.object({model:Gn.optional(),thresholdPercent:y.number().finite().min(0).max(1).optional()}).strict(),Jn=y.object({build:Kn.optional(),compaction:qn.optional(),description:y.string().optional(),metadata:y.record(y.string(),y.string()),model:Gn,name:y.string(),source:Bn.optional()}).strict(),Yn=y.object({name:y.string(),logicalPath:y.string(),markdown:y.string(),sourceId:y.string(),sourceKind:y.union([y.literal(`markdown`),y.literal(`module`)])}).strict(),Xn={name:y.string(),description:y.string(),license:y.string().optional(),markdown:y.string(),metadata:y.record(y.string(),y.string()).optional(),sourceId:y.string(),logicalPath:y.string()},Zn=y.discriminatedUnion(`sourceKind`,[y.object({...Xn,sourceKind:y.literal(`markdown`)}).strict(),y.object({...Xn,sourceKind:y.literal(`module`),exportName:y.string().optional()}).strict(),y.object({...Xn,sourceKind:y.literal(`skill-package`),skillId:y.string(),skillFilePath:y.string(),rootPath:y.string(),assetsPath:y.string().optional(),referencesPath:y.string().optional(),scriptsPath:y.string().optional()}).strict()]),Qn=y.object({cron:y.string(),hasRun:y.boolean(),name:y.string(),logicalPath:y.string(),markdown:y.string().optional(),sourceId:y.string(),sourceKind:y.union([y.literal(`markdown`),y.literal(`module`)])}).strict(),$n=y.object({description:y.string().optional(),exportName:y.string().optional(),logicalPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),er=y.object({logicalPath:y.string(),rootEntries:y.array(y.string()).readonly(),sourceId:y.string(),sourcePath:y.string()}).strict(),tr=y.object({logicalPath:y.string(),rootEntries:y.array(y.string()).readonly()}).strict(),nr=y.object({connectionName:y.string(),description:y.string(),exportName:y.string().optional(),logicalPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),url:y.string(),vercelConnect:y.object({connector:y.string()}).strict().optional()}).strict(),rr=y.object({description:y.string(),exportName:y.string().optional(),inputSchema:ce.nullable(),logicalPath:y.string(),name:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),ir=y.object({exportName:y.string().optional(),logicalPath:y.string(),slug:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`)}).strict(),ar=y.object({agentRoot:y.string(),appRoot:y.string(),channels:y.array(Wn),config:Jn,connections:y.array(nr),diagnosticsSummary:Pe,disabledFrameworkTools:y.array(y.string()).readonly(),hooks:y.array(ir),sandbox:$n.nullable(),sandboxWorkspaces:y.array(er),schedules:y.array(Qn),skills:y.array(Zn).readonly(),instructions:Yn.optional(),tools:y.array(rr),workspaceResourceRoot:tr}).strict(),or=y.object({agent:ar,description:y.string(),entryPath:y.string(),logicalPath:y.string(),name:y.string(),nodeId:y.string(),rootPath:y.string(),sourceId:y.string(),sourceKind:y.literal(`module`),exportName:y.string().optional()}).strict(),sr=y.object({childNodeId:y.string(),parentNodeId:y.string()}).strict(),cr=y.object({agentRoot:y.string(),appRoot:y.string(),channels:y.array(Wn),config:Jn,connections:y.array(nr),diagnosticsSummary:Pe,disabledFrameworkTools:y.array(y.string()).readonly(),hooks:y.array(ir),kind:y.literal(zn),sandbox:$n.nullable(),sandboxWorkspaces:y.array(er),schedules:y.array(Qn),skills:y.array(Zn).readonly(),subagentEdges:y.array(sr),subagents:y.array(or),instructions:Yn.optional(),tools:y.array(rr),version:y.literal(22),workspaceResourceRoot:tr}).strict();function lr(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:pr(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,metadata:{...e.config.metadata},model:pr(e.config.model),name:e.config.name,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],hooks:[...e.hooks??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:ur({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function ur(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function dr(e,t){return e===`__root__`?t:`${e}::${t}`}function fr(e){return{...lr(e),kind:zn,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:22}}function pr(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}const mr=/^\/?[A-Za-z]:[\\/]/,hr=/^\\\\[^\\]/,gr=/(\b(?:from|import)\s*(?:\(\s*)?)(["'])([A-Za-z]:[\\/][^"'\n\r]*)\2/g;function _r(e){return mr.test(e)||hr.test(e)}function vr(e){let t=e.replaceAll(`\\`,`/`);return t.startsWith(`//`)?new URL(`file:${t}`).href:(/^\/[A-Za-z]:\//.test(t)&&(t=t.slice(1)),new URL(`file:///${t}`).href)}function yr(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?{path:e,suffix:``}:{path:e.slice(0,r),suffix:e.slice(r)}}function br(e){if(e.startsWith(`file://`))return e;let{path:t,suffix:n}=yr(e);return _r(t)?`${vr(t)}${n}`:e.replaceAll(`\\`,`/`)}function xr(e){return JSON.stringify(br(e))}function Sr(e){return e.replace(gr,(e,t,n,r)=>`${t}${n}${br(r)}${n}`)}const Cr=y.object({modules:y.record(y.string(),y.object({}).passthrough())}).strict(),wr=y.object({nodes:y.record(y.string(),Cr)}).strict();function Tr(e){let t=jr(e.moduleMapPath),n=e.importSpecifierStyle??`relative`,r=0,i=[Er({agentRoot:e.manifest.agentRoot,importSpecifierStyle:n,manifest:e.manifest,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:L}),...[...e.manifest.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>Er({agentRoot:e.agent.agentRoot,importSpecifierStyle:n,manifest:e.agent,moduleMapDirectory:t,nextBindingName(){return`module_${r++}`},nodeId:e.nodeId}))],a=i.flatMap(e=>e.modules.map(e=>`import * as ${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`));return[`// Generated by Ash. Do not edit by hand.`,``,...a,...a.length>0?[``]:[],`export const moduleMap = ${kr(i)};`,``,`export default moduleMap;`,``].join(`
4
- `)}function Er(e){return{modules:Dr(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:Or({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Mr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function Dr(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function Or(e){if(e.importSpecifierStyle===`absolute`)return br(Pr(e.targetPath));let t=Nr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function kr(e){return Ar([{key:`nodes`,value:Ar(e.map(e=>({key:e.nodeId,value:Ar([{key:`modules`,value:Ar(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Ar(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
4
+ `)}function Er(e){return{modules:Dr(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:Or({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:Mr(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function Dr(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.schedules)n.sourceKind!==`module`||!n.hasRun||t.set(n.sourceId,{sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function Or(e){if(e.importSpecifierStyle===`absolute`)return br(Pr(e.targetPath));let t=Nr(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function kr(e){return Ar([{key:`nodes`,value:Ar(e.map(e=>({key:e.nodeId,value:Ar([{key:`modules`,value:Ar(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function Ar(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
5
5
  `,`\n${r}`)}`).join(`,
6
6
  `),`${n}})`].join(`
7
7
  `)}function jr(e){let t=R(e);return t.segments.length===0?t.root.length===0?`.`:t.root:Fr(t.root,t.segments.slice(0,-1))}function Mr(e,t){let n=R(e),r=R(t);return r.root.length>0?Fr(r.root,r.segments):Fr(n.root,[...n.segments,...r.segments])}function Nr(e,t){let n=R(e),r=R(t);if(n.root!==r.root)return Pr(t);let i=0;for(;i<n.segments.length&&i<r.segments.length&&n.segments[i]===r.segments[i];)i+=1;let a=[...Array.from({length:n.segments.length-i},()=>`..`),...r.segments.slice(i)];return a.length===0?`.`:a.join(`/`)}function Pr(e){let t=R(e);return Fr(t.root,t.segments)}function R(e){let t=e.replaceAll(`\\`,`/`),n=``,r=t,i=t.match(/^[A-Za-z]:/);i===null?t.startsWith(`/`)&&(n=`/`,r=t.slice(1)):(n=i[0],r=t.slice(n.length),r.startsWith(`/`)&&(n=`${n}/`,r=r.slice(1)));let a=[];for(let e of r.split(`/`))if(!(e.length===0||e===`.`)){if(e===`..`){if(a.length>0&&a[a.length-1]!==`..`){a.pop();continue}n.length===0&&a.push(e);continue}a.push(e)}return{root:n,segments:a}}function Fr(e,t){return e===`/`?t.length===0?`/`:`/${t.join(`/`)}`:e.endsWith(`/`)?t.length===0?e:`${e}${t.join(`/`)}`:e.length>0?t.length===0?e:`${e}/${t.join(`/`)}`:t.length===0?`.`:t.join(`/`)}const Ir=`ash-model-catalog-cache`,Lr=y.object({provider:y.string().min(1),providerModelId:y.string().min(1),contextWindowTokens:y.number().int().nonnegative().optional(),maxOutputTokens:y.number().int().nonnegative().optional()}).passthrough(),Rr=y.object({slug:y.string().min(1),providers:y.array(Lr).min(1)}).passthrough(),zr=y.object({models:y.array(Rr),providerAliases:y.record(y.string(),y.string())}).passthrough();y.object({contextWindowTokens:y.number().int().positive(),maxOutputTokens:y.number().int().positive().optional()}).strict();const Br=y.object({fetchedAt:y.string(),kind:y.literal(Ir),models:y.array(Rr),providerAliases:y.record(y.string(),y.string()),version:y.literal(2)}).strict(),Vr=new Map([[`anthropic/claude-opus-4.7`,{contextWindowTokens:2e5,maxOutputTokens:32e3}],[`openai/gpt-5.4`,{contextWindowTokens:4e5,maxOutputTokens:128e3}],[`openai/gpt-5.4-mini`,{contextWindowTokens:4e5,maxOutputTokens:128e3}]]);function Hr(e){return x(e,`.ash`,`cache`,`model-catalog.json`)}function Ur(e){let t=null,n=null,r=null,i=async()=>(t??=Gr(e),await t),a=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=Wr(e).then(e=>(t=Promise.resolve(e),e));try{return await r}catch(e){throw n=e,e}},o=async()=>{let e=await i();if(e!==null&&Jr(e))return e;try{return await a()}catch{return e===null?null:e}};return{async getModelLimits(e){let t=Yr(e),n=await o();if(n!==null){let e=Kr(n.models,t);if(e)for(let t of e.providers){let e=qr(t);if(e!==null)return e}}return Vr.get(t)??null},async getByProviderModelId(e,t){let n=await o();if(n===null)return null;let r=e.split(`.`)[0],i=n.providerAliases[r]??r,a=Yr(t);for(let e of n.models)for(let t of e.providers)if(t.provider===i&&Yr(t.providerModelId)===a){let n=qr(t);if(n!==null)return{slug:e.slug,limits:n}}return null}}}async function Wr(e){let t=await fetch(`https://ai-gateway.vercel.sh/v1/models/catalog`);if(!t.ok)throw Error(`AI Gateway model catalog request failed with HTTP ${t.status} ${t.statusText}.`);let n=zr.safeParse(await t.json());if(!n.success)throw Error(`AI Gateway model catalog response did not match the expected schema.`);let r={fetchedAt:new Date().toISOString(),kind:Ir,models:n.data.models,providerAliases:n.data.providerAliases,version:2};try{let t=Hr(e);await C(x(e,`.ash`,`cache`),{recursive:!0}),await w(t,`${JSON.stringify(r,null,2)}\n`,`utf8`)}catch{}return r}async function Gr(e){try{let t=await ge(Hr(e),`utf8`),n=Br.safeParse(JSON.parse(t));return n.success?n.data:null}catch(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&e.code,null}}function Kr(e,t){return e.find(e=>e.slug===t)}function qr(e){return e.contextWindowTokens===void 0||e.contextWindowTokens<=0?null:{contextWindowTokens:e.contextWindowTokens,...e.maxOutputTokens!==void 0&&e.maxOutputTokens>0&&{maxOutputTokens:e.maxOutputTokens}}}function Jr(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=864e5:!1}function Yr(e){return e.endsWith(`-thinking`)?e.slice(0,-9):e}async function z(e){let t=r(await l(x(e.agentRoot,e.source.logicalPath)),e.source);try{return await s(t)}catch(t){throw Error(`Failed to execute the ${e.kind} export "${e.source.exportName??`default`}" from "${e.source.logicalPath}": ${p(t)}`)}}var Xr=class extends Error{agentId;constructor(e){super(`Agent "${e}" does not have an agent.ts config module. The "model" field is required.`),this.name=`MissingAgentConfigModuleError`,this.agentId=e}};async function Zr(e,t){if(e.configModule===void 0)throw new Xr(e.agentId);let n=et(await z({agentRoot:e.agentRoot,kind:`agent config`,source:e.configModule}),`Expected the agent config export "${e.configModule.exportName??`default`}" from "${e.configModule.logicalPath}" to match the public Ash shape.`),r=await Qr({modelCatalog:t.modelCatalog,purpose:`the primary compaction trigger model`,requireContextWindowTokens:!0,contextWindowTokens:n.modelContextWindowTokens,providerOptions:n.modelOptions?.providerOptions,source:e.configModule,value:n.model}),i={},a={compaction:i,metadata:n.metadata??{},model:r,name:e.agentId};return n.description!==void 0&&(a.description=n.description),n.build!==void 0&&(a.build={externalDependencies:n.build.externalDependencies===void 0?void 0:[...n.build.externalDependencies]}),a.source={exportName:e.configModule.exportName,sourceKind:`module`,logicalPath:e.configModule.logicalPath,sourceId:e.configModule.sourceId},n.compaction?.model!==void 0&&(i.model=await Qr({modelCatalog:t.modelCatalog,purpose:`the compaction summary model`,requireContextWindowTokens:!0,contextWindowTokens:n.compaction.modelContextWindowTokens,providerOptions:n.modelOptions?.providerOptions,source:e.configModule,value:n.compaction.model})),n.compaction?.thresholdPercent!==void 0&&(i.thresholdPercent=n.compaction.thresholdPercent),a}async function Qr(e){if(typeof e.value==`string`)return await $r({id:le(e.value),providerOptions:e.providerOptions===void 0?void 0:ee(e.providerOptions)},e);let t=e.source;if(t===void 0)throw Error(`Expected ${e.purpose} to provide a valid AI SDK language model reference.`);let n=e.value,r=n.specificationVersion;if(r!==`v2`&&r!==`v3`&&r!==`v4`||typeof n.provider!=`string`||typeof n.modelId!=`string`||typeof n.doGenerate!=`function`||typeof n.doStream!=`function`)throw Error(`Expected the authored agent config export "${t.exportName??`default`}" from "${t.logicalPath}" to provide a valid AI SDK language model.`);let i={id:le(n),source:{exportName:t.exportName,sourceKind:`module`,logicalPath:t.logicalPath,sourceId:t.sourceId},providerOptions:e.providerOptions===void 0?void 0:ee(e.providerOptions)};if(e.contextWindowTokens===void 0){let t=await e.modelCatalog.getByProviderModelId(n.provider,n.modelId);if(t)return{...i,id:t.slug,contextWindowTokens:t.limits.contextWindowTokens}}return await $r(i,e)}async function $r(e,t){if(t.contextWindowTokens!==void 0)return{...e,contextWindowTokens:t.contextWindowTokens};let n;try{n=await t.modelCatalog.getModelLimits(e.id)}catch(n){if(!t.requireContextWindowTokens)return e;throw Error(`Failed to load AI Gateway model metadata for ${t.purpose} "${e.id}". ${p(n)}`)}if(n===null){if(!t.requireContextWindowTokens)return e;throw Error(`Cannot compile agent compaction because ${t.purpose} "${e.id}" does not have known AI Gateway context window metadata.`)}return{...e,contextWindowTokens:n.contextWindowTokens}}function ei(e){return typeof e==`object`&&!!e&&e.__kind===`ash:channel`}function ti(e,t){if(!ei(e))throw Error(`${t} Use \`defineChannel({ routes, ... })\` (or a wrapper like \`slackChannel\` / \`ashChannel\`) — bare \`{ fetch, receive? }\` channel objects are no longer supported.`);return e}function ni(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-channel`}async function ri(e,t){let n=await z({agentRoot:e,kind:`channel`,source:t}),r=A(t.logicalPath).replace(/^channels\//,``);if(ni(n))return{kind:`disabled`,name:r,logicalPath:t.logicalPath};let i=ti(n,`Expected the channel export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return i.routes.map(e=>({kind:`channel`,name:r,logicalPath:t.logicalPath,method:e.method.toUpperCase(),urlPath:e.path,sourceId:t.sourceId,sourceKind:`module`,exportName:t.exportName,adapterKind:ii(i.adapter)}))}function ii(e){if(typeof e!=`object`||!e)return;let t=e.kind;return typeof t==`string`&&t.length>0?t:void 0}function ai(e,t=`auth`){if(typeof e!=`object`||!e)return`The "${t}" field must be an object with a "getToken" method.`;let n=e;if(typeof n.getToken!=`function`)return`The "${t}.getToken" field must be a function returning Promise<{ token }>.`;let r=n.startAuthorization!==void 0,i=n.completeAuthorization!==void 0;if(!r&&!i&&n.principalType!==void 0&&n.principalType!==`app`&&n.principalType!==`user`)return`The "${t}.principalType" field must be "app" or "user".`;if(r!==i)return`The "${t}" field must provide either both "startAuthorization" and "completeAuthorization" (interactive OAuth) or neither (getToken-only). Got only "${r?`startAuthorization`:`completeAuthorization`}".`;if(r&&typeof n.startAuthorization!=`function`)return`The "${t}.startAuthorization" field must be a function when provided.`;if(i&&typeof n.completeAuthorization!=`function`)return`The "${t}.completeAuthorization" field must be a function when provided.`;if(r&&n.principalType!==`user`)return`Interactive authorization (startAuthorization + completeAuthorization) is restricted to "principalType": "user" in v1. See D10 of research/connections/connection-principal-model.md for the rationale.`}function oi(e,t,n=`auth`){let r=ai(e,n);if(r!==void 0)throw Error(`${t} ${r}`);let i=e,a=si(i.vercelConnect);if(i.startAuthorization!==void 0&&i.completeAuthorization!==void 0){let e={completeAuthorization:i.completeAuthorization,getToken:i.getToken,principalType:`user`,startAuthorization:i.startAuthorization};return a===void 0?e:{...e,vercelConnect:a}}let o={getToken:i.getToken,principalType:i.principalType??`app`};return a===void 0?o:{...o,vercelConnect:a}}function si(e){if(typeof e!=`object`||!e)return;let t=e.connector;if(!(typeof t!=`string`||t.length===0))return{connector:t}}const ci=[`approval`,`auth`,`description`,`headers`,`tools`,`url`],li=[`completeAuthorization`,`getToken`,`principalType`,`startAuthorization`,`vercelConnect`];function ui(e,t){let r=c(e,t);n(r,ci,t),di(r,t),fi(r,t);let i=pi(r,t),a=mi(r,t),o=hi(r,t);if(i!==void 0&&a!==void 0&&typeof a!=`function`&&Object.keys(a).some(e=>e.toLowerCase()===`authorization`))throw Error(`${t} "headers" must not include an "Authorization" key when "auth" is also provided.`);let s={description:r.description,url:r.url};if(i!==void 0&&(s.auth=i),a!==void 0&&(s.headers=a),o!==void 0&&(s.tools=o),r.approval!==void 0){if(typeof r.approval!=`function`)throw Error(`${t} The "approval" field must be a function when provided.`);s.approval=r.approval}return s}function di(e,t){if(typeof e.url!=`string`||!URL.canParse(e.url))throw Error(`${t} The "url" field must be a valid URL.`);let n=new URL(e.url);if(n.protocol!==`https:`&&n.protocol!==`http:`)throw Error(`${t} The "url" field must use the http or https protocol, got "${n.protocol}".`)}function fi(e,t){if(typeof e.description!=`string`||e.description.length===0)throw Error(`${t} The "description" field must be a non-empty string.`)}function pi(e,t){if(e.auth===void 0)return;let r=c(e.auth,`${t} The "auth" field must be an object with a "getToken" method.`);return n(r,li,`${t} The "auth" field`),oi(r,t)}function mi(e,t){if(e.headers===void 0)return;if(typeof e.headers==`function`)return e.headers;if(typeof e.headers!=`object`||e.headers===null||Array.isArray(e.headers))throw Error(`${t} The "headers" field must be a plain object or a function.`);let n=e.headers;for(let[e,r]of Object.entries(n)){let n=typeof r;if(n!==`string`&&n!==`function`&&n!==`object`||n===`object`&&(r===null||typeof r.then!=`function`))throw Error(`${t} The "headers.${e}" value must be a string, Promise, or function.`)}return n}function hi(e,t){if(e.tools===void 0)return;if(typeof e.tools!=`object`||e.tools===null||Array.isArray(e.tools))throw Error(`${t} The "tools" field must specify either "allow" or "block".`);let n=e.tools,r=`allow`in n,i=`block`in n;if(r&&i)throw Error(`${t} The "tools" field must specify either "allow" or "block", not both.`);if(!r&&!i)throw Error(`${t} The "tools" field must specify either "allow" or "block".`);return r?(gi(n.allow,`${t} The "tools.allow"`),{allow:n.allow}):(gi(n.block,`${t} The "tools.block"`),{block:n.block})}function gi(e,t){if(!Array.isArray(e))throw Error(`${t} field must be an array of strings.`);for(let n=0;n<e.length;n++)if(typeof e[n]!=`string`)throw Error(`${t}[${n}] must be a string.`)}async function _i(e,t){let n=ui(await z({agentRoot:e,kind:`connection`,source:t}),`Expected the connection export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={connectionName:t.connectionName,description:n.description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`,url:n.url},i=vi(n.auth);return i!==void 0&&(r.vercelConnect=i),r}function vi(e){if(typeof e!=`object`||!e)return;let t=e.vercelConnect;if(typeof t!=`object`||!t)return;let n=t.connector;if(!(typeof n!=`string`||n.length===0))return{connector:n}}function yi(e){return{exportName:e.exportName,logicalPath:e.logicalPath,slug:A(e.logicalPath).replace(/^hooks\//,``),sourceId:e.sourceId,sourceKind:`module`}}function bi(e,t){let r=c(e,t);n(r,[`backend`,`bootstrap`,`description`,`onSession`],t);let i={};if(r.backend!==void 0&&(i.backend=xi(r.backend,t)),r.description!==void 0){if(typeof r.description!=`string`)throw Error(`${t} The "description" field must be a string when set.`);i.description=r.description}return r.bootstrap!==void 0&&(i.bootstrap=o(r.bootstrap,t)),r.onSession!==void 0&&(i.onSession=o(r.onSession,t)),i}function xi(e,t){let n=c(e,`${t} The "backend" field must be a SandboxBackend value (use vercelBackend(), localBackend(), or your own factory).`);if(typeof n.name!=`string`||n.name.length===0)throw Error(`${t} The "backend" value must expose a non-empty string "name" identifier.`);if(typeof n.create!=`function`)throw Error(`${t} The "backend" value must expose a "create" function.`);if(n.prewarm!==void 0&&typeof n.prewarm!=`function`)throw Error(`${t} The "backend.prewarm" property must be a function when set.`);return n}async function Si(e,t){return{description:bi(await z({agentRoot:e,kind:`sandbox`,source:t}),`Expected the sandbox export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`).description,exportName:t.exportName,logicalPath:t.logicalPath,sourceId:t.sourceId,sourceKind:`module`}}async function Ci(e,t){let n=t.sourceKind===`markdown`?at(t.definition,`Expected the compiled instructions definition at "${t.logicalPath}" to match the public Ash shape.`):at(await z({agentRoot:e,kind:`instructions`,source:t}),`Expected the instructions export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{name:A(t.logicalPath),logicalPath:t.logicalPath,markdown:n.markdown,sourceId:t.sourceId,sourceKind:t.sourceKind}}async function wi(e,t){let n=t.sourceKind===`markdown`?st(t.definition,`Expected the compiled schedule definition at "${t.logicalPath}" to match the public Ash shape.`):st(await z({agentRoot:e,kind:`schedule`,source:t}),`Expected the schedule export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r={cron:n.cron,hasRun:n.run!==void 0,logicalPath:t.logicalPath,name:Ti(t.logicalPath),sourceId:t.sourceId,sourceKind:t.sourceKind};return n.markdown===void 0?r:{...r,markdown:n.markdown.trim()}}function Ti(e){return A(e).replace(/^schedules\//,``)}async function Ei(e,t){if(t.sourceKind===`skill-package`)return Di(t);let n=t.sourceKind===`markdown`?ot(t.definition,`Expected the compiled skill definition at "${t.logicalPath}" to match the public Ash shape.`):ot(await z({agentRoot:e,kind:`skill`,source:t}),`Expected the skill export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`);return{description:n.description,license:n.license,logicalPath:t.logicalPath,markdown:n.markdown,metadata:n.metadata===void 0?void 0:{...n.metadata},name:A(t.logicalPath).replace(/^skills\//,``),sourceId:t.sourceId,sourceKind:t.sourceKind}}function Di(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:e.logicalPath,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillId:e.skillId,skillFilePath:e.skillFilePath,sourceId:e.sourceId,sourceKind:`skill-package`}}async function Oi(e){let t=[],n=[];for(let r of e.subagents){let i=await ki({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:e.parentNodeId,source:r});t.push(i.node,...i.descendants.nodes),n.push({childNodeId:i.node.nodeId,parentNodeId:e.parentNodeId},...i.descendants.edges)}return{edges:n,nodes:t}}async function ki(e){let t=dr(e.parentNodeId,e.source.sourceId),n=e.source.subagentId,r=await e.compileAgentNodeManifest({...e.source.manifest,appRoot:e.appRoot},e.context),i=r.config.description;if(!i)throw Error(`Local subagent "${e.source.logicalPath}" is missing a "description" field on its agent config. Add \`description\` to \`defineAgent({ ... })\` so the parent agent can decide when to delegate to this subagent.`);return{descendants:await Oi({appRoot:e.appRoot,compileAgentNodeManifest:e.compileAgentNodeManifest,context:e.context,parentNodeId:t,subagents:e.source.manifest.subagents}),node:{agent:r,description:i,entryPath:e.source.entryPath,logicalPath:e.source.logicalPath,name:n,nodeId:t,rootPath:e.source.rootPath,sourceId:e.source.sourceId,sourceKind:`module`}}}function Ai(e){return typeof e==`object`&&!!e&&e.kind===`ash:disabled-tool`}function ji(e){return e&&typeof e==`object`&&`~standard`in e?e[`~standard`].jsonSchema.input({target:`draft-07`}):JSON.parse(JSON.stringify(e))}function Mi(e,t){if(Ai(e))return{kind:`disabled`};let r=c(e,t);n(r,[`description`,`execute`,`inputSchema`,`needsApproval`,`onCompact`,`retentionPolicy`],t);let i=r.inputSchema===void 0?null:ji(r.inputSchema),a={description:u(r.description,t),execute:o(r.execute,t),inputSchema:i};if(r.onCompact!==void 0&&o(r.onCompact,t),r.needsApproval!==void 0&&o(r.needsApproval,t),r.retentionPolicy!==void 0){let e=r.retentionPolicy;if(e!==`auto`&&e!==`keep`&&typeof e!=`function`)throw Error(`${t} Expected \`retentionPolicy\` to be "auto", "keep", or a function.`)}return{kind:`tool`,definition:a}}async function Ni(e,t){let n=Mi(await z({agentRoot:e,kind:`tool`,source:t}),`Expected the tool export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r=A(t.logicalPath).replace(/^tools\//,``).replaceAll(`/`,`-`);return n.kind===`disabled`?{kind:`disabled`,name:r}:{kind:`tool`,definition:{description:n.definition.description,exportName:t.exportName,inputSchema:n.definition.inputSchema??null,logicalPath:t.logicalPath,name:r,sourceId:t.sourceId,sourceKind:`module`}}}async function Pi(e){let t={modelCatalog:Ur(e.appRoot)},[n,r]=await Promise.all([Fi(e,t),Oi({appRoot:e.appRoot,compileAgentNodeManifest:Fi,context:t,parentNodeId:L,subagents:e.subagents})]);return fr({...n,subagentEdges:r.edges,subagents:r.nodes})}async function Fi(e,t){let n=await Promise.all(e.tools.map(t=>Ni(e.agentRoot,t))),r=[],i=[];for(let e of n)e.kind===`tool`?r.push(e.definition):i.push(e.name);let a=(await Promise.all(e.channels.map(t=>ri(e.agentRoot,t)))).flat();return lr({agentRoot:e.agentRoot,appRoot:e.appRoot,channels:a,config:await Zr(e,t),connections:await Promise.all(e.connections.map(t=>_i(e.agentRoot,t))),diagnosticsSummary:e.diagnosticsSummary,disabledFrameworkTools:i,hooks:e.hooks.map(e=>yi(e)),sandbox:e.sandbox===null?null:await Si(e.agentRoot,e.sandbox),sandboxWorkspaces:e.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:await Promise.all(e.schedules.map(t=>wi(e.agentRoot,t))),skills:await Promise.all(e.skills.map(t=>Ei(e.agentRoot,t))),instructions:e.instructions===void 0?void 0:await Ci(e.agentRoot,e.instructions),tools:r})}const Ii=`workspace-resources`;async function Li(e){let t=x(e.compileDirectoryPath,Ii);await ve(t,{force:!0,recursive:!0});let n=await zi({nodeId:L,resourcesRoot:t,manifest:e.manifest}),r=await Promise.all(e.manifest.subagents.map(async e=>({...e,agent:await zi({nodeId:e.nodeId,resourcesRoot:t,manifest:e.agent})})));return{...n,kind:e.manifest.kind,subagentEdges:e.manifest.subagentEdges,subagents:r,version:e.manifest.version}}function Ri(e,t){return{logicalPath:D(x(Ii,t)),rootEntries:ur({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}}async function zi(e){for(let t of e.manifest.sandboxWorkspaces)if(t.rootEntries.some(e=>e===`skills/`||e===`skills`))throw Error(`Sandbox workspace "${t.logicalPath}" cannot define "skills" because Ash manages that workspace entry.`);let t=x(e.resourcesRoot,e.nodeId);await C(t,{recursive:!0});for(let n of e.manifest.sandboxWorkspaces)await he(n.sourcePath,t,{recursive:!0});for(let n of e.manifest.skills)await Bi({nodeRoot:t,skill:n});return{...e.manifest,workspaceResourceRoot:Ri(e.manifest,e.nodeId)}}async function Bi(e){let t=x(e.nodeRoot,`skills`,e.skill.name);if(e.skill.sourceKind===`skill-package`){await he(e.skill.rootPath,t,{recursive:!0});return}let n=x(t,`SKILL.md`);await C(b(n),{recursive:!0}),await w(n,e.skill.markdown)}function Vi(e){let t=S(e),n=x(t,`.ash`,`discovery`),r=x(t,`.ash`,`compile`);return{appRoot:t,compiledManifestPath:x(r,`compiled-agent-manifest.json`),compileDirectoryPath:r,compileMetadataPath:x(r,`compile-metadata.json`),diagnosticsPath:x(n,`diagnostics.json`),discoveryManifestPath:x(n,`agent-discovery-manifest.json`),discoveryDirectoryPath:n,moduleMapPath:x(r,`module-map.mjs`)}}function Hi(e){return{diagnostics:[...e],kind:`ash-discovery-diagnostics`,summary:Le(e),version:1}}function Ui(e){let t=_(),n=Gi(e.discoveryManifestJson),r=Gi(e.diagnosticsArtifactJson),i=Gi(e.moduleMapSource);return{compile:{moduleMap:{path:qi(e.appRoot,e.paths.moduleMapPath),sha256:i}},discovery:{diagnostics:{path:qi(e.appRoot,e.paths.diagnosticsPath),sha256:r},manifest:{path:qi(e.appRoot,e.paths.discoveryManifestPath),sha256:n},sourceGraphHash:Gi(`${n}:${r}:${i}`),summary:e.diagnosticsSummary},generator:{name:t.name,version:t.version},kind:`ash-compile-metadata`,status:e.diagnosticsSummary.errors>0?`failed`:`ready`,version:5}}async function Wi(e){let t=Vi(e.appRoot),n=Hi(e.diagnostics),r=await Li({compileDirectoryPath:t.compileDirectoryPath,manifest:await Pi(e.manifest)}),i=Ki(r),a=Ki(e.manifest),o=Ki(n),s=Tr({manifest:r,moduleMapPath:t.moduleMapPath}),c=Ui({appRoot:e.appRoot,diagnosticsArtifactJson:o,diagnosticsSummary:n.summary,discoveryManifestJson:a,moduleMapSource:s,paths:t}),l=Ki(c);return await C(t.discoveryDirectoryPath,{recursive:!0}),await C(t.compileDirectoryPath,{recursive:!0}),await Promise.all([w(t.compiledManifestPath,i),w(t.diagnosticsPath,o),w(t.discoveryManifestPath,a),w(t.moduleMapPath,s),w(t.compileMetadataPath,l)]),{compiledManifest:r,diagnosticsArtifact:n,metadata:c,moduleMapSource:s,paths:t}}function Gi(e){return be(`sha256`).update(e).digest(`hex`)}function Ki(e){return`${JSON.stringify(e,null,2)}\n`}function qi(e,t){return D(fe(S(e),t))}var Ji=class extends Error{result;constructor(e){super(Zi({diagnostics:e.diagnostics,diagnosticsPath:e.paths.diagnosticsPath})),this.name=`CompileAgentError`,this.result=e}};async function Yi(e={}){let t=e.source??F(),n=await jn(e.startPath,{source:t}),r=await On({...n,source:t}),i=await Wi({appRoot:n.appRoot,diagnostics:r.diagnostics,manifest:r.manifest}),a={diagnostics:r.diagnostics,manifest:i.compiledManifest,metadata:i.metadata,paths:i.paths,project:n};if(Re(r.diagnostics))throw new Ji(a);return Xi(r.diagnostics),a}function Xi(e){let t=e.filter(e=>e.severity===`warning`);if(t.length!==0)for(let e of t)console.warn(`Warning [${e.code}]: ${e.message}\n source: ${e.sourcePath}`)}function Zi(e){let t=Le(e.diagnostics),n=[`Discovery failed with ${t.errors} error(s) and ${t.warnings} warning(s).`];if(e.diagnosticsPath!==void 0&&n.push(`Diagnostics artifact: ${e.diagnosticsPath}`),e.diagnostics.length===0)return n.join(`
@@ -1,4 +1,4 @@
1
- import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-CvbqpwTh.js";import{t as m}from"./authored-module-loader-XcFLnl49.js";import{t as h}from"./errors-DsO9xmQL.js";import{i as g,t as _}from"./package-DmsQgn4v.js";import{join as v,posix as y}from"node:path";import{mkdir as ne,readFile as re,readdir as ie,realpath as b,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:g(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,o=a();for(let e of t){if(e.kind===`disabled`){if(!o.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...o].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let s=l().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),c=new Set,u=[];for(let e of[...s,...r]){let t=k(e);c.has(t)||(c.add(t),u.push(e))}return u}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(g(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
1
+ import{E as e,S as t,T as n,_ as r,a as i,c as a,d as o,g as s,h as c,l,m as u,p as ee,s as te,u as d,x as f,y as p}from"./paths-AVYgVLR3.js";import{t as m}from"./authored-module-loader-XcFLnl49.js";import{t as h}from"./errors-DsO9xmQL.js";import{i as g,t as _}from"./package-DmsQgn4v.js";import{join as v,posix as y}from"node:path";import{mkdir as ne,readFile as re,readdir as ie,realpath as b,writeFile as x}from"node:fs/promises";import{createHash as S}from"node:crypto";import{existsSync as C}from"node:fs";function w(e){return e.dev?{appRoot:e.appRoot,dev:e.dev,moduleMapLoaderPath:g(`src/internal/authored-module-map-loader.ts`)}:{appRoot:e.appRoot,dev:e.dev}}const T=`#ash-channel/`;function E(e){let t=e.compileResult.manifest.channels,n=new Set,r=[],i=new Set,o=a();for(let e of t){if(e.kind===`disabled`){if(!o.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...o].sort().join(`, `)}.`);i.add(e.name);continue}n.add(e.name),r.push({method:e.method,route:e.urlPath})}let s=l().filter(e=>!n.has(e.name)&&!i.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),c=new Set,u=[];for(let e of[...s,...r]){let t=k(e);c.has(t)||(c.add(t),u.push(e))}return u}function D(e,t){for(let n of t.registrations)A(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function O(e,t){return N(t.previous,t.next)?!1:(j(e),D(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function k(e){return`${e.method.toUpperCase()} ${e.route}`}function A(e,t){let r=k(t),i=`${T}${r}`,a=n(g(`src/internal/nitro/routes/channel-dispatch.ts`));e.options.handlers.push({handler:i,method:t.method,route:t.route}),e.options.virtual[i]=[`import { dispatchChannelRequest } from ${a};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(r)}, config);`].join(`
2
2
  `)}function j(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&M(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(T)&&delete e.options.virtual[t]}function M(e){return e.handler.startsWith(T)}function N(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route)return!1}return!0}const P=`ash.schedule.`;var F=class extends Error{scheduleId;sourceId;taskName;constructor(e,t={}){super(e),this.name=`ScheduleRegistrationError`,t.scheduleId!==void 0&&(this.scheduleId=t.scheduleId),t.sourceId!==void 0&&(this.sourceId=t.sourceId),t.taskName!==void 0&&(this.taskName=t.taskName)}};function I(e){let t=e.map(e=>({cron:e.cron,description:`Run Ash schedule "${e.name}" from "${e.logicalPath}".`,logicalPath:e.logicalPath,scheduleId:e.name,sourceId:e.sourceId,taskName:R(e.sourceId)})).sort((e,t)=>e.sourceId.localeCompare(t.sourceId));return L(t),t}function L(e){let t=new Map;for(let n of e){let e=t.get(n.scheduleId);if(e===void 0){t.set(n.scheduleId,n);continue}throw new F(`Duplicate authored schedule id "${n.scheduleId}" found in "${e.logicalPath}" and "${n.logicalPath}".`,{scheduleId:n.scheduleId,sourceId:n.sourceId,taskName:n.taskName})}}function R(e){return`${P}${Buffer.from(e,`utf8`).toString(`base64url`)}`}const z=`#ash-schedule-task/`;function B(e,t){if(t.registrations.length!==0){e.options.experimental.tasks=!0;for(let n of t.registrations)U(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registration:n})}}function V(e,t){let n=!G(t.previous,t.next);return H(e),B(e,{artifactsConfig:t.artifactsConfig,dispatchModulePath:t.dispatchModulePath,registrations:t.next}),n}function H(e){for(let t of Object.keys(e.options.tasks))t.startsWith(`ash.schedule.`)&&delete e.options.tasks[t];for(let t of Object.keys(e.options.virtual))t.startsWith(z)&&delete e.options.virtual[t];for(let[t,n]of Object.entries(e.options.scheduledTasks)){let r=W(n).filter(e=>!e.startsWith(P));if(r.length===0){delete e.options.scheduledTasks[t];continue}if(r.length===1){let[n]=r;n!==void 0&&(e.options.scheduledTasks[t]=n);continue}e.options.scheduledTasks[t]=r}}function U(e,t){let r=`${z}${t.registration.taskName}`,i=n(t.dispatchModulePath);e.options.tasks[t.registration.taskName]={description:t.registration.description,handler:r},e.options.virtual[r]=[`import { dispatchScheduleTask } from ${i};`,`const config = ${JSON.stringify(t.artifactsConfig)};`,`export default {`,` meta: { description: ${JSON.stringify(t.registration.description)} },`,` async run(event) {`,` return { result: await dispatchScheduleTask(event.name, config) };`,` },`,`};`].join(`
3
3
  `),ae(e,t.registration.cron,t.registration.taskName)}function ae(e,t,n){let r=e.options.scheduledTasks[t];if(r===void 0){e.options.scheduledTasks[t]=n;return}if(typeof r==`string`){e.options.scheduledTasks[t]=[r,n];return}r.includes(n)||r.push(n)}function W(e){return typeof e==`string`?[e]:[...e]}function G(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.cron!==i.cron||r.description!==i.description||r.logicalPath!==i.logicalPath||r.scheduleId!==i.scheduleId||r.sourceId!==i.sourceId||r.taskName!==i.taskName)return!1}return!0}async function K(e){return[...e.manifest.schedules].map(e=>{let t={cron:e.cron,hasRun:e.hasRun,logicalPath:e.logicalPath,name:e.name,sourceId:e.sourceId,sourceKind:e.sourceKind};return e.markdown===void 0?t:{...t,markdown:e.markdown}})}async function q(e){return await K({manifest:await o({compiledArtifactsSource:e.compiledArtifactsSource})})}async function J(e){let t=v(e.outDir,`compiled-artifacts-bootstrap.mjs`),n=v(e.outDir,`compiled-artifacts-instrumentation.mjs`),r=se(e.compileResult.manifest.agentRoot);await ne(e.outDir,{recursive:!0}),await x(t,await le({compileResult:e.compileResult,installModulePath:g(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:t,metadata:e.compileResult.metadata})),r!==void 0&&await x(n,ue({agentName:e.compileResult.manifest.config.name,instrumentationPath:r,registerConfigPath:g(`src/harness/instrumentation-config.ts`)}));let i={bootstrapPath:t};return r!==void 0&&(i.instrumentationPluginPath=n,i.instrumentationSourcePath=r),i}const oe=[`.ts`,`.mts`,`.js`,`.mjs`];function se(e){for(let t of oe){let n=v(e,`instrumentation${t}`);if(C(n))return n}}function ce(e){return e.replace(/^export const moduleMap = /m,`const moduleMap = `).replace(/\nexport default moduleMap;\n?$/,`
4
4
  `)}async function le(e){let r=ce(t({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath})).trim();return[`// Generated by Ash. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${n(e.installModulePath)};`,``,r,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``,`export async function __ashInstallCompiledArtifactsStep() {`,` "use step";`,` return null;`,`}`,``].join(`
@@ -1,2 +1,2 @@
1
- import{D as e,b as t,t as n,v as r,y as i}from"../../chunks/paths-CvbqpwTh.js";import{d as a,f as o,h as s}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as c,renderCliBanner as l,renderCliSection as u}from"../ui/output.js";async function d(e){let t=await f(e);return{application:n(t?.project.appRoot??e),compiledState:t,messaging:{createSessionRoutePath:o,continueSessionRoutePattern:a,streamRoutePattern:s}}}async function f(n){try{return await i({startPath:n})}catch(n){if(n instanceof r)return n.result;if(n instanceof e||n instanceof t)return null;throw n}}function p(e,t){return`${e} ${t}${e===1?``:`s`}`}function m(e,t){return`${`${e} error${e===1?``:`s`}`}, ${`${t} warning${t===1?``:`s`}`}`}function h(e){switch(e){case`ready`:return`success`;case`failed`:return`danger`;default:return`warning`}}async function g(e,t){let n=await d(t),r=n.compiledState,i=n.application,a=c(),o=[{label:`App Root`,value:i.appRoot}],s=[{label:`Workflow Build`,value:i.workflowBuildDir},{label:`Output`,value:i.outputDir}],f=[];r===null?o.push({label:`Compile`,tone:`warning`,value:`unavailable`}):(o.push({label:`Agent Root`,value:r.project.agentRoot},{label:`Layout`,value:r.project.layout},{label:`Compile`,tone:h(r.metadata.status),value:r.metadata.status},{label:`Diagnostics`,tone:r.metadata.discovery.summary.errors>0?`danger`:r.metadata.discovery.summary.warnings>0?`warning`:`success`,value:m(r.metadata.discovery.summary.errors,r.metadata.discovery.summary.warnings)},{label:`Instructions`,value:r.manifest.instructions?.logicalPath??`none`},{label:`Skills`,value:p(r.manifest.skills.length,`skill`)}),s.unshift({label:`Compiled Manifest`,value:r.paths.compiledManifestPath},{label:`Discovery Manifest`,value:r.paths.discoveryManifestPath},{label:`Diagnostics`,value:r.paths.diagnosticsPath},{label:`Module Map`,value:r.paths.moduleMapPath},{label:`Metadata`,value:r.paths.compileMetadataPath}),f.push(r.manifest.instructions===void 0?{label:`Instructions`,value:`No instructions prompt discovered.`}:{label:`Instructions`,value:r.manifest.instructions.logicalPath})),e.log([l(a,{subtitle:`Resolved application paths and the active message contract.`,title:`Ash Info`}),``,u(a,{rows:o,title:`Application`}),``,u(a,{rows:s,title:`Artifacts`}),...r===null?[]:[``,u(a,{rows:f,title:`Instructions`})],``,u(a,{rows:[{label:`Workflow ID`,value:i.workflowId},{label:`Source Dir`,value:i.workflowSourceDir},{label:`Create`,tone:`info`,value:`POST ${n.messaging.createSessionRoutePath}`},{label:`Continue`,tone:`info`,value:`POST ${n.messaging.continueSessionRoutePattern}`},{label:`Stream`,tone:`info`,value:`GET ${n.messaging.streamRoutePattern}`}],title:`Messaging`})].join(`
1
+ import{D as e,b as t,t as n,v as r,y as i}from"../../chunks/paths-AVYgVLR3.js";import{d as a,f as o,h as s}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as c,renderCliBanner as l,renderCliSection as u}from"../ui/output.js";async function d(e){let t=await f(e);return{application:n(t?.project.appRoot??e),compiledState:t,messaging:{createSessionRoutePath:o,continueSessionRoutePattern:a,streamRoutePattern:s}}}async function f(n){try{return await i({startPath:n})}catch(n){if(n instanceof r)return n.result;if(n instanceof e||n instanceof t)return null;throw n}}function p(e,t){return`${e} ${t}${e===1?``:`s`}`}function m(e,t){return`${`${e} error${e===1?``:`s`}`}, ${`${t} warning${t===1?``:`s`}`}`}function h(e){switch(e){case`ready`:return`success`;case`failed`:return`danger`;default:return`warning`}}async function g(e,t){let n=await d(t),r=n.compiledState,i=n.application,a=c(),o=[{label:`App Root`,value:i.appRoot}],s=[{label:`Workflow Build`,value:i.workflowBuildDir},{label:`Output`,value:i.outputDir}],f=[];r===null?o.push({label:`Compile`,tone:`warning`,value:`unavailable`}):(o.push({label:`Agent Root`,value:r.project.agentRoot},{label:`Layout`,value:r.project.layout},{label:`Compile`,tone:h(r.metadata.status),value:r.metadata.status},{label:`Diagnostics`,tone:r.metadata.discovery.summary.errors>0?`danger`:r.metadata.discovery.summary.warnings>0?`warning`:`success`,value:m(r.metadata.discovery.summary.errors,r.metadata.discovery.summary.warnings)},{label:`Instructions`,value:r.manifest.instructions?.logicalPath??`none`},{label:`Skills`,value:p(r.manifest.skills.length,`skill`)}),s.unshift({label:`Compiled Manifest`,value:r.paths.compiledManifestPath},{label:`Discovery Manifest`,value:r.paths.discoveryManifestPath},{label:`Diagnostics`,value:r.paths.diagnosticsPath},{label:`Module Map`,value:r.paths.moduleMapPath},{label:`Metadata`,value:r.paths.compileMetadataPath}),f.push(r.manifest.instructions===void 0?{label:`Instructions`,value:`No instructions prompt discovered.`}:{label:`Instructions`,value:r.manifest.instructions.logicalPath})),e.log([l(a,{subtitle:`Resolved application paths and the active message contract.`,title:`Ash Info`}),``,u(a,{rows:o,title:`Application`}),``,u(a,{rows:s,title:`Artifacts`}),...r===null?[]:[``,u(a,{rows:f,title:`Instructions`})],``,u(a,{rows:[{label:`Workflow ID`,value:i.workflowId},{label:`Source Dir`,value:i.workflowSourceDir},{label:`Create`,tone:`info`,value:`POST ${n.messaging.createSessionRoutePath}`},{label:`Continue`,tone:`info`,value:`POST ${n.messaging.continueSessionRoutePattern}`},{label:`Stream`,tone:`info`,value:`GET ${n.messaging.streamRoutePattern}`}],title:`Messaging`})].join(`
2
2
  `))}export{g as printApplicationInfo};
@@ -1,3 +1,3 @@
1
- import{t as e}from"../../chunks/errors-DsO9xmQL.js";import{c as t,d as n,f as r,h as i,l as a}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as o,renderCliBanner as s,renderCliSection as c,renderCliSpeakerLine as l,renderCliTaggedLine as u}from"../ui/output.js";import{n as d,r as f,t as p}from"../../chunks/input-requests-BsBi7_5K.js";import{parseDevReplInput as m}from"./input.js";import{a as h,i as g,n as _,o as v,r as y,s as b,t as x}from"../../chunks/client-BeZ_W7vl.js";import{createDevelopmentTerminal as S}from"./terminal.js";import{createInterface as C,emitKeypressEvents as ee}from"node:readline";function te(e){return[...e].reverse().find(a)}function ne(e){let t=new URL(e);return t.hash=``,t.search=``,t.pathname.endsWith(`/`)||(t.pathname=`${t.pathname}/`),t}function w(e){return new URL(e.routePath.replace(/^\/+/,``),ne(e.serverUrl))}function T(e){let t=e.resource.trim();try{return new URL(t)}catch{return w({routePath:t,serverUrl:e.serverUrl})}}const E=[`vercel.com/sso-api`,`<title>Authentication Required</title>`,`Vercel Authentication`];function D(e){if(e.length===0)return!1;for(let t of E)if(e.includes(t))return!0;return!1}function O(e){return e instanceof b||typeof e==`object`&&e&&`body`in e&&typeof e.body==`string`?D(e.body):!1}function k(e){return[`Vercel Deployment Protection blocked the request to ${e.serverUrl}.`,``,"To access the deployment from `ash dev`, do one of:"," • Run `vercel link` in this project so the CLI can mint an OIDC",` token for the deployment automatically.`,` • Set VERCEL_AUTOMATION_BYPASS_SECRET to a Protection Bypass for`,` Automation token (Project Settings → Deployment Protection).`,` • Disable Deployment Protection on the target deployment.`,``,`Docs: https://vercel.com/docs/deployment-protection`].join(`
1
+ import{t as e}from"../../chunks/errors-DsO9xmQL.js";import{c as t,d as n,f as r,h as i,l as a}from"../../chunks/types-MZUhN0Zy.js";import{createCliTheme as o,renderCliBanner as s,renderCliSection as c,renderCliSpeakerLine as l,renderCliTaggedLine as u}from"../ui/output.js";import{n as d,r as f,t as p}from"../../chunks/input-requests-BsBi7_5K.js";import{parseDevReplInput as m}from"./input.js";import{a as h,i as g,n as _,o as v,r as y,s as b,t as x}from"../../chunks/client-CKsU8Li3.js";import{createDevelopmentTerminal as S}from"./terminal.js";import{createInterface as C,emitKeypressEvents as ee}from"node:readline";function te(e){return[...e].reverse().find(a)}function ne(e){let t=new URL(e);return t.hash=``,t.search=``,t.pathname.endsWith(`/`)||(t.pathname=`${t.pathname}/`),t}function w(e){return new URL(e.routePath.replace(/^\/+/,``),ne(e.serverUrl))}function T(e){let t=e.resource.trim();try{return new URL(t)}catch{return w({routePath:t,serverUrl:e.serverUrl})}}const E=[`vercel.com/sso-api`,`<title>Authentication Required</title>`,`Vercel Authentication`];function D(e){if(e.length===0)return!1;for(let t of E)if(e.includes(t))return!0;return!1}function O(e){return e instanceof b||typeof e==`object`&&e&&`body`in e&&typeof e.body==`string`?D(e.body):!1}function k(e){return[`Vercel Deployment Protection blocked the request to ${e.serverUrl}.`,``,"To access the deployment from `ash dev`, do one of:"," • Run `vercel link` in this project so the CLI can mint an OIDC",` token for the deployment automatically.`,` • Set VERCEL_AUTOMATION_BYPASS_SECRET to a Protection Bypass for`,` Automation token (Project Settings → Deployment Protection).`,` • Disable Deployment Protection on the target deployment.`,``,`Docs: https://vercel.com/docs/deployment-protection`].join(`
2
2
  `)}var A=h();async function j(){try{let e=(await(0,A.getVercelOidcToken)()).trim();if(e.length>0)return e}catch{}return process.env.VERCEL_OIDC_TOKEN?.trim()||``}const M=new Set([`localhost`,`127.0.0.1`,`0.0.0.0`,`::1`,`[::1]`]);function N(e){try{return M.has(new URL(e).hostname)}catch{return!1}}async function P(e){let t={},n=process.env.VERCEL_AUTOMATION_BYPASS_SECRET?.trim();if(n&&(t[_]=n),!e.isLocal){let e=await j();e.length>0&&(t[y]=e)}return t}var F=class{#e;#t;constructor(e){let t=N(e.serverUrl);this.#e=new x({headers:()=>P({isLocal:t}),host:e.serverUrl,...t?{}:{auth:{bearer:j}}}),this.#t=this.#e.session()}async clear(){this.#t=this.#e.session()}async close(){}getSession(){return this.#t.state}async sendMessage(e){return await this.send({message:e.message,onEvent:e.onEvent,onResponseStart:e.onResponseStart})}async send(e){let t=await this.#t.send({inputResponses:e.inputResponses,message:e.message});e.onResponseStart?.({sessionId:t.sessionId});let n=[];for await(let r of t)n.push(r),e.onEvent?.(r);return{events:n,sessionId:t.sessionId,session:this.#t.state}}};function I(e){return new F(e)}function L(e){let t=[{label:`Server`,tone:`info`,value:e.serverUrl},{label:`Create`,tone:`info`,value:`POST ${r}`},{label:`Continue`,tone:`info`,value:`POST ${n}`},{label:`Stream`,tone:`info`,value:`GET ${i}`}];return t.push({label:`Session`,value:`Follow-up messages reuse the active continuation token.`}),t}function R(){return[{label:`/help`,value:`Print the connection contract and available commands.`},{label:`/new`,value:`Clear the current durable session cursor.`},{label:`/exit`,value:`Exit the REPL.`}]}function z(e,t){return[s(e,{subtitle:`Interactive development REPL for the active Ash server.`,title:`Ash Dev`}),``,c(e,{rows:L(t),title:`Connection`}),``,c(e,{rows:R(),title:`Commands`})].join(`
3
3
  `)}function re(e){let t=e.trim();return t.length>0?t:null}function B(e){return e.options?.sourceKind===`subagent`?`subagent`:e.fallback}function V(e){return e.options?.sourceKind===`subagent`?`subagent`:e.fallback}function H(e){return e.options?.sourceLabel===void 0?e.message:`${e.options.sourceLabel}${e.separator??` `}${e.message}`}function U(e,t,n){switch(t.type){case`message.appended`:return{finalized:!1,kind:`message`,line:l(e,{message:t.data.messageSoFar,speaker:n?.sourceLabel??`agent`,tone:V({fallback:`accent`,options:n})})};case`message.completed`:if(t.data.message===null)return;if(t.data.finishReason===`tool-calls`){let r=re(t.data.message);return r===null?void 0:{finalized:!0,kind:`message`,line:u(e,{message:H({message:r,options:n,separator:`: `}),tag:B({fallback:`step`,options:n}),tone:V({fallback:`accent`,options:n})})}}return{finalized:!0,kind:`message`,line:l(e,{message:t.data.message,speaker:n?.sourceLabel??`agent`,tone:V({fallback:`accent`,options:n})})};case`reasoning.appended`:return{finalized:!1,kind:`reasoning`,line:u(e,{message:H({message:t.data.reasoningSoFar,options:n,separator:`: `}),tag:B({fallback:`reasoning`,options:n}),tone:V({fallback:`info`,options:n})})};case`reasoning.completed`:return{finalized:!0,kind:`reasoning`,line:u(e,{message:H({message:t.data.reasoning,options:n,separator:`: `}),tag:B({fallback:`reasoning`,options:n}),tone:V({fallback:`info`,options:n})})};default:return}}function W(e,t,n){let r=U(e,t,n);if(r!==void 0)return r.line;switch(t.type){case`message.received`:return;case`actions.requested`:return u(e,{message:H({message:`${t.type} (${t.data.actions.length} action${t.data.actions.length===1?``:`s`})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`muted`,options:n})});case`input.requested`:return u(e,{message:H({message:`${t.type} (${t.data.requests.length} request${t.data.requests.length===1?``:`s`})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`info`,options:n})});case`action.result`:return u(e,{message:H({message:`${t.type} (${Z(t.data.result)})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`muted`,options:n})});case`session.waiting`:case`session.completed`:return;case`connection.authorization_required`:return u(e,{message:H({message:`${t.type} (${t.data.connectionName}: ${t.data.description}${ae(t.data.authorization)})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`warning`,options:n})});case`compaction.requested`:return u(e,{message:H({message:`compacting conversation history`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`muted`,options:n})});case`compaction.completed`:return u(e,{message:H({message:`conversation history compacted`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`muted`,options:n})});case`step.failed`:case`turn.failed`:case`session.failed`:return;case`subagent.called`:return u(e,{message:H({message:`${t.type} (${t.data.name} -> ${t.data.childSessionId})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`info`,options:n})});case`subagent.started`:return u(e,{message:H({message:`${t.type} (${t.data.subagentName})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`info`,options:n})});case`subagent.event`:return u(e,{message:H({message:`${t.type} (${t.data.subagentName}: ${oe(t.data.event)})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`muted`,options:n})});case`subagent.completed`:return u(e,{message:H({message:`${t.type} (${t.data.subagentName})`,options:n}),tag:B({fallback:`event`,options:n}),tone:V({fallback:`info`,options:n})});default:return}}function G(e){switch(e.type){case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:return`content`;default:return`meta`}}function K(){return{activeLiveContentKind:null,lastPrintedBlockKind:null}}function q(e){let t=e.state;return t.activeLiveContentKind!==null&&(e.terminal.commitLive(),t={activeLiveContentKind:null,lastPrintedBlockKind:`content`}),t.lastPrintedBlockKind!==null&&t.lastPrintedBlockKind!==e.kind&&e.terminal.print(``),e.terminal.print(e.line),{activeLiveContentKind:null,lastPrintedBlockKind:e.kind}}function J(e){let t=U(e.theme,e.event,e.options);if(t!==void 0){let n=e.state;return n.activeLiveContentKind!==null&&n.activeLiveContentKind!==t.kind&&(e.terminal.commitLive(),n={activeLiveContentKind:null,lastPrintedBlockKind:`content`}),n.lastPrintedBlockKind!==null&&n.lastPrintedBlockKind!==`content`&&e.terminal.print(``),e.terminal.updateLive(t.line),t.finalized?(e.terminal.commitLive(),{activeLiveContentKind:null,lastPrintedBlockKind:`content`}):{activeLiveContentKind:t.kind,lastPrintedBlockKind:`content`}}let n=W(e.theme,e.event,e.options);return n===void 0?e.state:q({kind:G(e.event),line:n,state:e.state,terminal:e.terminal})}function Y(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}function X(e){return e.length===0}var ie=class{#e=new Map;#t;#n;#r;#i;constructor(e){this.#t=e.displayStateRef,this.#n=e.serverUrl,this.#r=e.terminal,this.#i=e.theme}subscribe(e){if(this.#e.has(e.sessionId))return;let t=new AbortController,n=this.#a({controller:t,sessionId:e.sessionId,subagentName:e.subagentName}).finally(()=>{this.#e.delete(e.sessionId)});this.#e.set(e.sessionId,{controller:t,done:n,label:e.subagentName})}async waitForIdle(){for(;this.#e.size>0;)await Promise.all([...this.#e.values()].map(e=>e.done))}async close(){let e=[...this.#e.values()];for(let t of e)t.controller.abort();await Promise.allSettled(e.map(e=>e.done))}async#a(n){let r=T({resource:t(n.sessionId),serverUrl:this.#n});try{for await(let e of v({host:this.#n,maxReconnectAttempts:3,resolveHeaders:async()=>await g({resourceUrl:r}),sessionId:n.sessionId,signal:n.controller.signal,startIndex:0}))if(this.#t.current=J({event:e,options:{sourceKind:`subagent`,sourceLabel:n.subagentName},state:this.#t.current,terminal:this.#r,theme:this.#i}),e.type===`subagent.called`&&this.subscribe({sessionId:e.data.childSessionId,subagentName:e.data.name}),a(e))return}catch(t){if(Y(t))return;let r=e(t);this.#t.current=q({kind:`meta`,line:u(this.#i,{message:`${n.subagentName} stream failed: ${r}`,tag:`subagent`,tone:`danger`}),state:this.#t.current,terminal:this.#r})}finally{n.controller.abort()}}};function Z(e){switch(e.kind){case`load-skill-result`:return e.kind;case`subagent-result`:return`${e.kind}:${e.subagentName}`;case`tool-result`:return`${e.kind}:${e.toolName}`}}function ae(e){if(e===void 0)return``;let t=[];return e.url!==void 0&&t.push(e.url),e.userCode!==void 0&&t.push(`code ${e.userCode}`),e.instructions!==void 0&&t.push(e.instructions),t.length===0?``:` — ${t.join(`, `)}`}function oe(e){switch(e.type){case`actions.requested`:{let t=e.data.actions,n=t.map(e=>e.kind===`tool-call`?e.toolName:e.kind).join(`,`);return`${e.type} (${t.length} action${t.length===1?``:`s`}${n.length>0?`: ${n}`:``})`}case`action.result`:return`${e.type} (${Z(e.data.result)})`;case`input.requested`:return`${e.type} (${e.data.requests.length} request${e.data.requests.length===1?``:`s`})`;default:return e.type}}function se(e,t){return t.continuationToken?u(e,{message:`resuming session ${t.continuationToken}`,tag:`session`,tone:`info`}):u(e,{message:`starting a new session`,tag:`session`,tone:`info`})}function ce(e,t){return t.turn.inputResponses!==void 0&&t.turn.message===void 0?u(e,{message:`responding to pending input request${t.turn.inputResponses.length===1?``:`s`}`,tag:`session`,tone:`info`}):se(e,t.session)}function le(e,t){let n=te(t),r=d(t);switch(n?.type){case`session.waiting`:return[u(e,{message:r.length>0?`waiting for input approval/answer or the next message`:`waiting for the next message`,tag:`session`,tone:`success`})];case`session.completed`:return[u(e,{message:`session completed; the next input starts a new session`,tag:`session`,tone:`success`})];case`session.failed`:{let t=n.data.details&&typeof n.data.details.name==`string`?n.data.details.name:void 0;return[u(e,{message:t?`session failed (${t}): ${n.data.message}`:`session failed: ${n.data.message}`,tag:`session`,tone:`danger`}),u(e,{message:`cleared; the next input starts a new session`,tag:`session`,tone:`warning`})]}default:return[]}}async function Q(e,t,n={}){return await new Promise(r=>{let i=e.input,a=()=>{e.off(`close`,o),e.off(`line`,s),i.off(`keypress`,c)},o=()=>{a(),r(void 0)},s=e=>{a(),r(e)},c=(t,i)=>{n.allowEscape!==!0||i.name!==`escape`||(a(),e.write(null,{ctrl:!0,name:`u`}),r(p))};e.setPrompt(t),e.once(`close`,o),e.once(`line`,s),n.allowEscape&&(ee(i,e),i.on(`keypress`,c)),e.prompt()})}async function $(e){let n=e.turn,r={current:K()},i=new ie({displayStateRef:r,serverUrl:e.serverUrl,terminal:e.terminal,theme:e.theme}),a=async t=>{e.terminal.startPrompt(e.rl,t);let n=await Q(e.rl,t,{allowEscape:!0});return e.terminal.stopPrompt(),n};try{for(;;){let o=e.client.getSession();r.current=q({kind:`meta`,line:ce(e.theme,{session:o,turn:n}),state:r.current,terminal:e.terminal});let s=await e.client.send({inputResponses:n.inputResponses,message:n.message,onEvent(t){r.current=J({event:t,state:r.current,terminal:e.terminal,theme:e.theme}),t.type===`subagent.called`&&i.subscribe({sessionId:t.data.childSessionId,subagentName:t.data.name})},onResponseStart(n){n.sessionId&&o.sessionId!==n.sessionId&&(r.current=q({kind:`meta`,line:u(e.theme,{message:n.sessionId,tag:`session`,tone:`accent`}),state:r.current,terminal:e.terminal}),r.current=q({kind:`meta`,line:u(e.theme,{message:T({resource:t(n.sessionId),serverUrl:e.serverUrl}).toString(),tag:`stream`,tone:`info`}),state:r.current,terminal:e.terminal}))}}),c=d(s.events);if(X(c)){await i.waitForIdle();for(let t of le(e.theme,s.events))r.current=q({kind:`meta`,line:t,state:r.current,terminal:e.terminal});return`continue`}let l=await f({ask:a,print(t){r.current=q({kind:`meta`,line:t,state:r.current,terminal:e.terminal})},requests:c,theme:e.theme});if(l.kind===`aborted`)return`exit`;if(l.kind===`deferred`)return r.current=q({kind:`meta`,line:u(e.theme,{message:`left pending input requests unresolved; send a new message to ignore them`,tag:`session`,tone:`warning`}),state:r.current,terminal:e.terminal}),`continue`;n={inputResponses:l.inputResponses}}}finally{await i.close()}}async function ue(t){let n=S(),r=o({color:!0}),i=C({input:process.stdin,output:n.output,terminal:!0});i.on(`SIGINT`,()=>{i.close()});let a=I({serverUrl:t.serverUrl});try{for(n.print(z(r,t)),n.print(``);;){n.print(``),n.startPrompt(i,`you> `);let o=await Q(i,`you> `);if(n.stopPrompt(),o===void 0)return;let s=m(o);switch(s.kind!==`empty`&&s.kind!==`exit`&&n.print(``),s.kind){case`empty`:continue;case`help`:n.print(z(r,t)),n.print(``);continue;case`exit`:return;case`new`:await a.clear(),n.print(u(r,{message:`cleared; the next input starts a new session`,tag:`session`,tone:`warning`})),n.print(``);continue;case`message`:try{if(await $({client:a,rl:i,serverUrl:t.serverUrl,terminal:n,theme:r,turn:{message:s.message}})===`exit`)return}catch(i){O(i)?n.printError(u(r,{message:k({serverUrl:t.serverUrl}),tag:`auth`,tone:`warning`})):n.printError(u(r,{message:e(i),tag:`error`,tone:`danger`}))}n.print(``)}}}finally{await a.close(),i.close(),n.dispose()}}export{K as createTurnDisplayState,U as formatContentEvent,W as formatEvent,J as renderTurnEvent,ue as runDevelopmentRepl,X as shouldDrainSubagentStreamsOnBoundary};