@entrydesk/cli 1.30.0 → 1.32.0-beta

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 (52) hide show
  1. package/README.md +19 -0
  2. package/dist/agents-6VHSTGVU.js +43 -0
  3. package/dist/{billing-MGDBCV6I.js → billing-WA7WGH7U.js} +1 -1
  4. package/dist/{budget-YYGSDB4J.js → budget-PC4EAZLV.js} +1 -1
  5. package/dist/chunk-5QJUAR4K.js +120 -0
  6. package/dist/chunk-77D346VR.js +2 -0
  7. package/dist/chunk-JMYSCKCF.js +2 -0
  8. package/dist/config-ED6PZQ7J.js +4 -0
  9. package/dist/{config-help-RTQDCM2A.js → config-help-CTZHKILN.js} +1 -1
  10. package/dist/{connectors-EEPEIQ76.js → connectors-O4K2ZFDM.js} +8 -8
  11. package/dist/help-KDHCFJNF.js +4 -0
  12. package/dist/index.js +1 -1
  13. package/dist/login-LX3ISJEI.js +2 -0
  14. package/dist/logout-YNCDJ5ST.js +2 -0
  15. package/dist/{marketplace-5QZCY7QH.js → marketplace-FHSTOAWV.js} +8 -8
  16. package/dist/mcp-2G4B3BVK.js +4 -0
  17. package/dist/{meeting-5RUQYMWF.js → meeting-UBBSEEHT.js} +5 -5
  18. package/dist/models-PGGTDNI4.js +3 -0
  19. package/dist/{notifications-ZCJVVQIC.js → notifications-DHPLCJFY.js} +3 -3
  20. package/dist/{profile-RIAXCLXG.js → profile-K4V2Y63H.js} +1 -1
  21. package/dist/{recordings-FMD3YL7B.js → recordings-OXG66QN2.js} +3 -3
  22. package/dist/{schedules-JFVHBBM3.js → schedules-R4U37II4.js} +9 -9
  23. package/dist/{skills-L4AGJVTQ.js → skills-JVSRQSKA.js} +3 -3
  24. package/dist/status-S37SXIYD.js +2 -0
  25. package/dist/task-H2COR6Z4.js +180 -0
  26. package/dist/{tasks-7SK2EZZS.js → tasks-7NS4UOBP.js} +9 -9
  27. package/dist/tool-VLJFDXQ4.js +35 -0
  28. package/dist/update-5GLLNVRU.js +4 -0
  29. package/dist/{usage-6PXKAMOY.js → usage-PAL5KJ5C.js} +5 -5
  30. package/dist/version-ROABNJFL.js +2 -0
  31. package/dist/workflow-XERZYR3S.js +62 -0
  32. package/dist/{workspaces-EQSJKVVV.js → workspaces-PLJMIDJR.js} +3 -3
  33. package/package.json +6 -7
  34. package/dist/agents-JG6OXKYV.js +0 -43
  35. package/dist/chunk-LHRI5YM6.js +0 -2
  36. package/dist/chunk-NC63CPWW.js +0 -118
  37. package/dist/chunk-RJGB52EF.js +0 -4
  38. package/dist/chunk-ZIAOI7B2.js +0 -2
  39. package/dist/config-PBKYHI2B.js +0 -4
  40. package/dist/help-FBKSAMA7.js +0 -4
  41. package/dist/login-HL5KEHEN.js +0 -2
  42. package/dist/logout-QI7X4M4E.js +0 -2
  43. package/dist/mcp-5764U6QO.js +0 -4
  44. package/dist/models-PFIG6ACY.js +0 -3
  45. package/dist/status-DBKKDZAF.js +0 -2
  46. package/dist/task-PBX6HRS3.js +0 -194
  47. package/dist/token-5JSZTSX7.js +0 -2
  48. package/dist/token-util-U6DGFQDY.js +0 -2
  49. package/dist/tool-YOUXWQ76.js +0 -35
  50. package/dist/update-3SS5DWV3.js +0 -4
  51. package/dist/version-RYL2AKE2.js +0 -2
  52. package/dist/workflow-6MU3A6LB.js +0 -62
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ import{B as ke,C as lt,L as xe,P as zt,T as Lr,a as Bn,b as ve,c as Oe,e as Le,f as Ke,g as $r,h as Wn,i as Un,j as $s,k as jn,l as Je,m as Mr,n as Ms,o as Fr,s as se,t as Dr,u as zn,v as it,w as at,x as Or}from"./chunk-5QJUAR4K.js";import{a as sl,c as rl}from"./chunk-JMYSCKCF.js";var Zn=sl((bd,Os)=>{"use strict";function qn(t){return Array.isArray(t)?t:[t]}var nl=void 0,Br="",Gn=" ",Nr="\\",il=/^\s+$/,ol=/(?:[^\\]|^)\\$/,al=/^\\!/,ll=/^\\#/,cl=/\r?\n/g,ul=/^\.{0,2}\/|^\.{1,2}$/,hl=/\/$/,Ne="/",Xn="node-ignore";typeof Symbol<"u"&&(Xn=Symbol.for("node-ignore"));var Vn=Xn,Be=(t,e,s)=>(Object.defineProperty(t,e,{value:s}),s),dl=/([0-z])-([0-z])/g,Yn=()=>!1,pl=t=>t.replace(dl,(e,s,r)=>s.charCodeAt(0)<=r.charCodeAt(0)?e:Br),fl=t=>{let{length:e}=t;return t.slice(0,e-e%2)},gl=[[/^\uFEFF/,()=>Br],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,s)=>e+(s.indexOf("\\")===0?Gn:Br)],[/(\\+?)\s/g,(t,e)=>{let{length:s}=e;return e.slice(0,s-s%2)+Gn}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,s)=>e+6<s.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,s)=>{let r=s.replace(/\\\*/g,"[^\\/]*");return e+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Nr],[/\\\\/g,()=>Nr],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,s,r,n)=>e===Nr?`\\[${s}${fl(r)}${n}`:n==="]"&&r.length%2===0?`[${pl(s)}${r}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],ml=/(^|\\\/)?\\\*$/,Ze="regex",Fs="checkRegex",Hn="_",wl={[Ze](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Fs](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},yl=t=>gl.reduce((e,[s,r])=>e.replace(s,r.bind(t)),t),Ds=t=>typeof t=="string",bl=t=>t&&Ds(t)&&!il.test(t)&&!ol.test(t)&&t.indexOf("#")!==0,Sl=t=>t.split(cl).filter(Boolean),Wr=class{constructor(e,s,r,n,i,o){this.pattern=e,this.mark=s,this.negative=i,Be(this,"body",r),Be(this,"ignoreCase",n),Be(this,"regexPrefix",o)}get regex(){let e=Hn+Ze;return this[e]?this[e]:this._make(Ze,e)}get checkRegex(){let e=Hn+Fs;return this[e]?this[e]:this._make(Fs,e)}_make(e,s){let r=this.regexPrefix.replace(ml,wl[e]),n=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return Be(this,s,n)}},vl=({pattern:t,mark:e},s)=>{let r=!1,n=t;n.indexOf("!")===0&&(r=!0,n=n.substr(1)),n=n.replace(al,"!").replace(ll,"#");let i=yl(n);return new Wr(t,e,n,s,r,i)},Ur=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[Vn]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(Ds(e)&&(e={pattern:e}),bl(e.pattern)){let s=vl(e,this._ignoreCase);this._added=!0,this._rules.push(s)}}add(e){return this._added=!1,qn(Ds(e)?Sl(e):e).forEach(this._add,this),this._added}test(e,s,r){let n=!1,i=!1,o;this._rules.forEach(l=>{let{negative:c}=l;i===c&&n!==i||c&&!n&&!i&&!s||!l[r].test(e)||(n=!c,i=c,o=c?nl:l)});let a={ignored:n,unignored:i};return o&&(a.rule=o),a}},kl=(t,e)=>{throw new e(t)},re=(t,e,s)=>Ds(t)?t?re.isNotRelative(t)?s(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:s("path must not be empty",TypeError):s(`path must be a string, but got \`${e}\``,TypeError),Kn=t=>ul.test(t);re.isNotRelative=Kn;re.convert=t=>t;var jr=class{constructor({ignorecase:e=!0,ignoreCase:s=e,allowRelativePaths:r=!1}={}){Be(this,Vn,!0),this._rules=new Ur(s),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,s,r,n){let i=e&&re.convert(e);return re(i,e,this._strictPathCheck?kl:Yn),this._t(i,s,r,n)}checkIgnore(e){if(!hl.test(e))return this.test(e);let s=e.split(Ne).filter(Boolean);if(s.pop(),s.length){let r=this._t(s.join(Ne)+Ne,this._testCache,!0,s);if(r.ignored)return r}return this._rules.test(e,!1,Fs)}_t(e,s,r,n){if(e in s)return s[e];if(n||(n=e.split(Ne).filter(Boolean)),n.pop(),!n.length)return s[e]=this._rules.test(e,r,Ze);let i=this._t(n.join(Ne)+Ne,s,r,n);return s[e]=i.ignored?i:this._rules.test(e,r,Ze)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return qn(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},zr=t=>new jr(t),xl=t=>re(t&&re.convert(t),t,Yn),Jn=()=>{let t=s=>/^\\\\\?\\/.test(s)||/["<>|\u0000-\u001F]+/u.test(s)?s:s.replace(/\\/g,"/");re.convert=t;let e=/^[a-z]:\//i;re.isNotRelative=s=>e.test(s)||Kn(s)};typeof process<"u"&&process.platform==="win32"&&Jn();Os.exports=zr;zr.default=zr;Os.exports.isPathValid=xl;Be(Os.exports,Symbol.for("setupWindows"),Jn)});import{getToolName as hd}from"ai";import{render as dd}from"ink";import{v4 as pd}from"uuid";import{exec as Bu}from"child_process";import Wu from"os";import Cl from"fs/promises";var si=rl(Zn(),1);import Qe from"fs/promises";import Qn from"os";import It from"path";function $t(t){let e=t.startsWith("~/")||t.startsWith("~\\")?It.join(Qn.homedir(),t.slice(2)):t==="~"?Qn.homedir():t;return It.resolve(e)}function ti(t){return t.normalize("NFC").replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu," ")}async function Nt(t){let e=$t(t);try{return await Qe.access(e),e}catch(s){if((s&&typeof s=="object"&&"code"in s?String(s.code):void 0)!=="ENOENT")throw s;let n=It.dirname(e),i=It.basename(e),o;try{o=await Qe.readdir(n)}catch{throw s}let a=ti(i),l=o.filter(h=>ti(h)===a),[c]=l;if(l.length===1&&c)return It.join(n,c);if(l.length>1){let h=new Error(`Multiple files match "${i}" after whitespace normalization: ${l.join(", ")}. Use filesystem__list_directory and pass an exact name.`);throw h.code="EAMBIG",h}throw s}}var Gr=100*1024,ri=50*1024,ts=10*1024*1024,ni=10,Hr=100,ii=10,We=10*1024*1024,es=3e4,oi=3e5;function ne(t,e=Gr){return t.length>e?t.slice(0,e)+`
3
+ ... [truncated, ${t.length-e} more characters]`:t}var ei={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".pdf":"application/pdf"},Tl=new Set([".txt",".md",".json",".js",".ts",".jsx",".tsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".fish",".py",".rb",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".sql",".graphql",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc"]);async function Ls(t){let e=It.extname(t).toLowerCase();if(ei[e])return{type:"binary",mimeType:ei[e]};if(Tl.has(e))return{type:"text"};try{let s=await Qe.open(t,"r"),r=Buffer.alloc(8);if(await s.read(r,0,8,0),await s.close(),r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71)return{type:"binary",mimeType:"image/png"};if(r[0]===255&&r[1]===216&&r[2]===255)return{type:"binary",mimeType:"image/jpeg"};if(r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56)return{type:"binary",mimeType:"image/gif"};if(r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return{type:"binary",mimeType:"application/pdf"};if(r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70)return{type:"binary",mimeType:"image/webp"};for(let n of r)if(n===0)return{type:"binary"}}catch{}return{type:"text"}}async function Ns(t){let e=(0,si.default)();e.add([".git","node_modules",".DS_Store"]);let s=t,r=[];for(;s!==It.dirname(s);){let n=It.join(s,".gitignore");try{await Qe.access(n),r.unshift(n)}catch{}s=It.dirname(s)}for(let n of r)try{let i=await Qe.readFile(n,"utf-8");e.add(i)}catch{}return e}function Bs(t,e,s){return t.filter(r=>{let n=It.relative(e,r);return!s.ignores(n.split(It.sep).join("/"))})}function ai(t,e,s){let r=e.split(`
4
+ `),n=s.split(`
5
+ `),i=[`--- a/${It.basename(t)}`,`+++ b/${It.basename(t)}`],o=0,a=0;for(;o<r.length||a<n.length;){if(o<r.length&&a<n.length&&r[o]===n[a]){o++,a++;continue}let l=o,c=a,h=!1;for(let d=1;d<10&&!h;d++)for(let m=l;m<=l+d;m++){for(let g=c;g<=c+d;g++)if(m<r.length&&g<n.length&&r[m]===n[g]){let p=Math.max(0,l-3),y=Math.min(r.length,m+3),v=Math.max(0,c-3),S=Math.min(n.length,g+3);i.push(`@@ -${p+1},${y-p} +${v+1},${S-v} @@`);for(let b=p;b<l;b++)i.push(` ${r[b]}`);for(let b=l;b<m;b++)i.push(`-${r[b]}`);for(let b=c;b<g;b++)i.push(`+${n[b]}`);for(let b=m;b<Math.min(m+3,r.length);b++)b<y&&i.push(` ${r[b]}`);o=m,a=g,h=!0;break}if(h)break}if(!h){for(i.push(`@@ -${l+1},${r.length-l} +${c+1},${n.length-c} @@`);o<r.length;)i.push(`-${r[o]}`),o++;for(;a<n.length;)i.push(`+${n[a]}`),a++}}return i.join(`
6
+ `)}var li=async t=>{try{return await Cl.mkdir($t(t.path),{recursive:!0}),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to create directory"}}};import ci from"fs/promises";var ui=async t=>{try{let e=await Nt(t.path),s=await ci.readFile(e,"utf-8"),r=s,n=[];for(let[o,a]of t.edits.entries()){let l=r.split(a.old_text).length-1;l===0?n.push({index:o,old_text:a.old_text.length>100?a.old_text.slice(0,100)+"...":a.old_text,reason:"Text not found in file. Ensure the old_text matches exactly, including whitespace and indentation."}):l>1&&n.push({index:o,old_text:a.old_text.length>100?a.old_text.slice(0,100)+"...":a.old_text,reason:`Found ${l} occurrences. The old_text must be unique. Include more surrounding context to make it unique.`})}if(n.length>0)return{success:!1,error:"Edit validation failed",errors:n};for(let o of t.edits)r=r.replace(o.old_text,o.new_text);let i=ai(e,s,r);return t.dry_run?{success:!0,applied:0,dry_run:!0,diff:i}:(await ci.writeFile(e,r,"utf-8"),{success:!0,applied:t.edits.length,diff:i})}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to edit file"}}};import{exec as El}from"child_process";import{existsSync as Rl}from"fs";import Al from"os";import{promisify as Pl}from"util";var _l=Pl(El),hi=async t=>{try{let e=$t(t.cwd||Al.homedir());if(!Rl(e))return{success:!1,error:`Working directory does not exist: ${e}`};let s=Math.min(t.timeout??es,oi),{stdout:r,stderr:n}=await _l(t.command,{cwd:e,timeout:s,maxBuffer:ts,shell:process.platform==="win32"?"cmd.exe":"/bin/bash"});return{success:!0,stdout:ne(r),stderr:ne(n)}}catch(e){let s=e;return{success:!1,exitCode:s.code,killed:s.killed,signal:s.signal,stdout:ne(s.stdout||""),stderr:ne(s.stderr||""),error:s.message||"Command execution failed"}}};import Il from"fs/promises";var di=async t=>{try{let e=await Il.stat(await Nt(t.path));return{success:!0,info:{size:e.size,type:e.isDirectory()?"directory":e.isFile()?"file":e.isSymbolicLink()?"symlink":"unknown",created:e.birthtime.toISOString(),modified:e.mtime.toISOString(),accessed:e.atime.toISOString(),permissions:e.mode.toString(8)}}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to get file info"}}};import{execFile as Au}from"child_process";import Pu from"fs/promises";import ko from"path";import{promisify as _u}from"util";import{fileURLToPath as Fc}from"url";import{posix as Nc,win32 as en}from"path";import{fileURLToPath as Bc}from"url";import{lstatSync as Wc,readdir as Uc,readdirSync as jc,readlinkSync as zc,realpathSync as Gc}from"fs";import*as Hc from"fs";import{lstat as qc,readdir as Xc,readlink as Vc,realpath as Yc}from"fs/promises";import{EventEmitter as nn}from"events";import Ji from"stream";import{StringDecoder as Kc}from"string_decoder";var Di=(t,e,s)=>{let r=t instanceof RegExp?pi(t,s):t,n=e instanceof RegExp?pi(e,s):e,i=r!==null&&n!=null&&$l(r,n,s);return i&&{start:i[0],end:i[1],pre:s.slice(0,i[0]),body:s.slice(i[0]+r.length,i[1]),post:s.slice(i[1]+n.length)}},pi=(t,e)=>{let s=e.match(t);return s?s[0]:null},$l=(t,e,s)=>{let r,n,i,o,a,l=s.indexOf(t),c=s.indexOf(e,l+1),h=l;if(l>=0&&c>0){if(t===e)return[l,c];for(r=[],i=s.length;h>=0&&!a;){if(h===l)r.push(h),l=s.indexOf(t,h+1);else if(r.length===1){let d=r.pop();d!==void 0&&(a=[d,c])}else n=r.pop(),n!==void 0&&n<i&&(i=n,o=c),c=s.indexOf(e,h+1);h=l<c&&l>=0?l:c}r.length&&o!==void 0&&(a=[i,o])}return a},Oi="\0SLASH"+Math.random()+"\0",Li="\0OPEN"+Math.random()+"\0",sn="\0CLOSE"+Math.random()+"\0",Ni="\0COMMA"+Math.random()+"\0",Bi="\0PERIOD"+Math.random()+"\0",Ml=new RegExp(Oi,"g"),Fl=new RegExp(Li,"g"),Dl=new RegExp(sn,"g"),Ol=new RegExp(Ni,"g"),Ll=new RegExp(Bi,"g"),Nl=/\\\\/g,Bl=/\\{/g,Wl=/\\}/g,Ul=/\\,/g,jl=/\\./g,zl=1e5;function qr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function Gl(t){return t.replace(Nl,Oi).replace(Bl,Li).replace(Wl,sn).replace(Ul,Ni).replace(jl,Bi)}function Hl(t){return t.replace(Ml,"\\").replace(Fl,"{").replace(Dl,"}").replace(Ol,",").replace(Ll,".")}function Wi(t){if(!t)return[""];let e=[],s=Di("{","}",t);if(!s)return t.split(",");let{pre:r,body:n,post:i}=s,o=r.split(",");o[o.length-1]+="{"+n+"}";let a=Wi(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function ql(t,e={}){if(!t)return[];let{max:s=zl}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),ls(Gl(t),s,!0).map(Hl)}function Xl(t){return"{"+t+"}"}function Vl(t){return/^-?0\d/.test(t)}function Yl(t,e){return t<=e}function Kl(t,e){return t>=e}function ls(t,e,s){let r=[],n=Di("{","}",t);if(!n)return[t];let i=n.pre,o=n.post.length?ls(n.post,e,!1):[""];if(/\$$/.test(n.pre))for(let a=0;a<o.length&&a<e;a++){let l=i+"{"+n.body+"}"+o[a];r.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),c=a||l,h=n.body.indexOf(",")>=0;if(!c&&!h)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+sn+n.post,ls(t,e,!0)):[t];let d;if(c)d=n.body.split(/\.\./);else if(d=Wi(n.body),d.length===1&&d[0]!==void 0&&(d=ls(d[0],e,!1).map(Xl),d.length===1))return o.map(g=>n.pre+d[0]+g);let m;if(c&&d[0]!==void 0&&d[1]!==void 0){let g=qr(d[0]),p=qr(d[1]),y=Math.max(d[0].length,d[1].length),v=d.length===3&&d[2]!==void 0?Math.abs(qr(d[2])):1,S=Yl;p<g&&(v*=-1,S=Kl);let b=d.some(Vl);m=[];for(let R=g;S(R,p);R+=v){let _;if(l)_=String.fromCharCode(R),_==="\\"&&(_="");else if(_=String(R),b){let A=y-_.length;if(A>0){let G=new Array(A+1).join("0");R<0?_="-"+G+_.slice(1):_=G+_}}m.push(_)}}else{m=[];for(let g=0;g<d.length;g++)m.push.apply(m,ls(d[g],e,!1))}for(let g=0;g<m.length;g++)for(let p=0;p<o.length&&r.length<e;p++){let y=i+m[g]+o[p];(!s||c||y)&&r.push(y)}}return r}var Ks=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},Jl={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ss=t=>t.replace(/[[\]\\-]/g,"\\$&"),Zl=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),fi=t=>t.join(""),Ql=(t,e)=>{let s=e;if(t.charAt(s)!=="[")throw new Error("not in a brace expression");let r=[],n=[],i=s+1,o=!1,a=!1,l=!1,c=!1,h=s,d="";t:for(;i<t.length;){let p=t.charAt(i);if((p==="!"||p==="^")&&i===s+1){c=!0,i++;continue}if(p==="]"&&o&&!l){h=i+1;break}if(o=!0,p==="\\"&&!l){l=!0,i++;continue}if(p==="["&&!l){for(let[y,[v,S,b]]of Object.entries(Jl))if(t.startsWith(y,i)){if(d)return["$.",!1,t.length-s,!0];i+=y.length,b?n.push(v):r.push(v),a=a||S;continue t}}if(l=!1,d){p>d?r.push(ss(d)+"-"+ss(p)):p===d&&r.push(ss(p)),d="",i++;continue}if(t.startsWith("-]",i+1)){r.push(ss(p+"-")),i+=2;continue}if(t.startsWith("-",i+1)){d=p,i+=2;continue}r.push(ss(p)),i++}if(h<i)return["",!1,0,!1];if(!r.length&&!n.length)return["$.",!1,t.length-s,!0];if(n.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let p=r[0].length===2?r[0].slice(-1):r[0];return[Zl(p),!1,h-s,!1]}let m="["+(c?"^":"")+fi(r)+"]",g="["+(c?"":"^")+fi(n)+"]";return[r.length&&n.length?"("+m+"|"+g+")":r.length?m:g,a,h-s,!0]},ze=(t,{windowsPathsNoEscape:e=!1,magicalBraces:s=!0}={})=>s?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),tc=new Set(["!","?","+","*","@"]),gi=t=>tc.has(t),ec="(?!(?:^|/)\\.\\.?(?:$|/))",Ws="(?!\\.)",sc=new Set(["[","."]),rc=new Set(["..","."]),nc=new Set("().*{}+?[]^$\\!"),ic=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),rn="[^/]",mi=rn+"*?",wi=rn+"+?",Ui=class Ft{type;#t;#s;#i=!1;#n=[];#o;#S;#w;#u=!1;#a;#d;#h=!1;constructor(e,s,r={}){this.type=e,e&&(this.#s=!0),this.#o=s,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?r:this.#t.#a,this.#w=this.#t===this?[]:this.#t.#w,e==="!"&&!this.#t.#u&&this.#w.push(this),this.#S=this.#o?this.#o.#n.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let e of this.#n)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#n.map(e=>String(e)).join("|")+")":this.#d=this.#n.map(e=>String(e)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#w.pop();){if(e.type!=="!")continue;let s=e,r=s.#o;for(;r;){for(let n=s.#S+1;!r.type&&n<r.#n.length;n++)for(let i of e.#n){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(r.#n[n])}s=r,r=s.#o}}return this}push(...e){for(let s of e)if(s!==""){if(typeof s!="string"&&!(s instanceof Ft&&s.#o===this))throw new Error("invalid part: "+s);this.#n.push(s)}}toJSON(){let e=this.type===null?this.#n.slice().map(s=>typeof s=="string"?s:s.toJSON()):[this.type,...this.#n.map(s=>s.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#S===0)return!0;let e=this.#o;for(let s=0;s<this.#S;s++){let r=e.#n[s];if(!(r instanceof Ft&&r.type==="!"))return!1}return!0}isEnd(){if(this.#t===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#n.length:0;return this.#S===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let s=new Ft(this.type,e);for(let r of this.#n)s.copyIn(r);return s}static#r(e,s,r,n){let i=!1,o=!1,a=-1,l=!1;if(s.type===null){let g=r,p="";for(;g<e.length;){let y=e.charAt(g++);if(i||y==="\\"){i=!i,p+=y;continue}if(o){g===a+1?(y==="^"||y==="!")&&(l=!0):y==="]"&&!(g===a+2&&l)&&(o=!1),p+=y;continue}else if(y==="["){o=!0,a=g,l=!1,p+=y;continue}if(!n.noext&&gi(y)&&e.charAt(g)==="("){s.push(p),p="";let v=new Ft(y,s);g=Ft.#r(e,v,g,n),s.push(v);continue}p+=y}return s.push(p),g}let c=r+1,h=new Ft(null,s),d=[],m="";for(;c<e.length;){let g=e.charAt(c++);if(i||g==="\\"){i=!i,m+=g;continue}if(o){c===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(c===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=c,l=!1,m+=g;continue}if(gi(g)&&e.charAt(c)==="("){h.push(m),m="";let p=new Ft(g,h);h.push(p),c=Ft.#r(e,p,c,n);continue}if(g==="|"){h.push(m),m="",d.push(h),h=new Ft(null,s);continue}if(g===")")return m===""&&s.#n.length===0&&(s.#h=!0),h.push(m),m="",s.push(...d,h),c;m+=g}return s.type=null,s.#s=void 0,s.#n=[e.substring(r-1)],c}static fromGlob(e,s={}){let r=new Ft(null,void 0,s);return Ft.#r(e,r,0,s),r}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let e=this.toString(),[s,r,n,i]=this.toRegExpSource();if(!(n||this.#s||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let o=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${s}$`,o),{_src:s,_glob:e})}get options(){return this.#a}toRegExpSource(e){let s=e??!!this.#a.dot;if(this.#t===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#n.some(m=>typeof m!="string"),c=this.#n.map(m=>{let[g,p,y,v]=typeof m=="string"?Ft.#v(m,this.#s,l):m.toRegExpSource(e);return this.#s=this.#s||y,this.#i=this.#i||v,g}).join(""),h="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&rc.has(this.#n[0]))){let m=sc,g=s&&m.has(c.charAt(0))||c.startsWith("\\.")&&m.has(c.charAt(2))||c.startsWith("\\.\\.")&&m.has(c.charAt(4)),p=!s&&!e&&m.has(c.charAt(0));h=g?ec:p?Ws:""}let d="";return this.isEnd()&&this.#t.#u&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[h+c+d,ze(c),this.#s=!!this.#s,this.#i]}let r=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#p(s);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#s=void 0,[l,ze(this.toString()),!1,!1]}let o=!r||e||s||!Ws?"":this.#p(!0);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!s?Ws:"")+wi;else{let l=this.type==="!"?"))"+(this.isStart()&&!s&&!e?Ws:"")+mi+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=n+i+l}return[a,ze(i),this.#s=!!this.#s,this.#i]}#p(e){return this.#n.map(s=>{if(typeof s=="string")throw new Error("string type in extglob ast??");let[r,n,i,o]=s.toRegExpSource(e);return this.#i=this.#i||o,r}).filter(s=>!(this.isStart()&&this.isEnd())||!!s).join("|")}static#v(e,s,r=!1){let n=!1,i="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(n){n=!1,i+=(nc.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,i+=r&&/^[*]+$/.test(e)?wi:mi,s=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?i+="\\\\":n=!0;continue}if(c==="["){let[h,d,m,g]=Ql(e,l);if(m){i+=h,o=o||d,l+=m-1,s=s||g;continue}}if(c==="?"){i+=rn,s=!0;continue}i+=ic(c)}return[i,ze(e),!!s,o]}},ji=(t,{windowsPathsNoEscape:e=!1,magicalBraces:s=!1}={})=>s?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),Ct=(t,e,s={})=>(Ks(e),!s.nocomment&&e.charAt(0)==="#"?!1:new fe(e,s).match(t)),oc=/^\*+([^+@!?\*\[\(]*)$/,ac=t=>e=>!e.startsWith(".")&&e.endsWith(t),lc=t=>e=>e.endsWith(t),cc=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),uc=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),hc=/^\*+\.\*+$/,dc=t=>!t.startsWith(".")&&t.includes("."),pc=t=>t!=="."&&t!==".."&&t.includes("."),fc=/^\.\*+$/,gc=t=>t!=="."&&t!==".."&&t.startsWith("."),mc=/^\*+$/,wc=t=>t.length!==0&&!t.startsWith("."),yc=t=>t.length!==0&&t!=="."&&t!=="..",bc=/^\?+([^+@!?\*\[\(]*)?$/,Sc=([t,e=""])=>{let s=zi([t]);return e?(e=e.toLowerCase(),r=>s(r)&&r.toLowerCase().endsWith(e)):s},vc=([t,e=""])=>{let s=Gi([t]);return e?(e=e.toLowerCase(),r=>s(r)&&r.toLowerCase().endsWith(e)):s},kc=([t,e=""])=>{let s=Gi([t]);return e?r=>s(r)&&r.endsWith(e):s},xc=([t,e=""])=>{let s=zi([t]);return e?r=>s(r)&&r.endsWith(e):s},zi=([t])=>{let e=t.length;return s=>s.length===e&&!s.startsWith(".")},Gi=([t])=>{let e=t.length;return s=>s.length===e&&s!=="."&&s!==".."},Hi=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",yi={win32:{sep:"\\"},posix:{sep:"/"}},Tc=Hi==="win32"?yi.win32.sep:yi.posix.sep;Ct.sep=Tc;var Tt=Symbol("globstar **");Ct.GLOBSTAR=Tt;var Cc="[^/]",Ec=Cc+"*?",Rc="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Ac="(?:(?!(?:\\/|^)\\.).)*?",Pc=(t,e={})=>s=>Ct(s,t,e);Ct.filter=Pc;var Bt=(t,e={})=>Object.assign({},t,e),_c=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ct;let e=Ct;return Object.assign((s,r,n={})=>e(s,r,Bt(t,n)),{Minimatch:class extends e.Minimatch{constructor(s,r={}){super(s,Bt(t,r))}static defaults(s){return e.defaults(Bt(t,s)).Minimatch}},AST:class extends e.AST{constructor(s,r,n={}){super(s,r,Bt(t,n))}static fromGlob(s,r={}){return e.AST.fromGlob(s,Bt(t,r))}},unescape:(s,r={})=>e.unescape(s,Bt(t,r)),escape:(s,r={})=>e.escape(s,Bt(t,r)),filter:(s,r={})=>e.filter(s,Bt(t,r)),defaults:s=>e.defaults(Bt(t,s)),makeRe:(s,r={})=>e.makeRe(s,Bt(t,r)),braceExpand:(s,r={})=>e.braceExpand(s,Bt(t,r)),match:(s,r,n={})=>e.match(s,r,Bt(t,n)),sep:e.sep,GLOBSTAR:Tt})};Ct.defaults=_c;var qi=(t,e={})=>(Ks(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:ql(t,{max:e.braceExpandMax}));Ct.braceExpand=qi;var Ic=(t,e={})=>new fe(t,e).makeRe();Ct.makeRe=Ic;var $c=(t,e,s={})=>{let r=new fe(e,s);return t=t.filter(n=>r.match(n)),r.options.nonull&&!t.length&&t.push(e),t};Ct.match=$c;var bi=/[?*]|[+@!]\(.*?\)|\[|\]/,Mc=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),fe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){Ks(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Hi,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(n=>this.slashSplit(n));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let r=this.globParts.map((n,i,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=n[0]===""&&n[1]===""&&(n[2]==="?"||!bi.test(n[2]))&&!bi.test(n[3]),l=/^[a-z]:/i.test(n[0]);if(a)return[...n.slice(0,4),...n.slice(4).map(c=>this.parse(c))];if(l)return[n[0],...n.slice(1).map(c=>this.parse(c))]}return n.map(a=>this.parse(a))});if(this.debug(this.pattern,r),this.set=r.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n<this.set.length;n++){let i=this.set[n];i[0]===""&&i[1]===""&&this.globParts[n][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let s=0;s<t.length;s++)for(let r=0;r<t[s].length;r++)t[s][r]==="**"&&(t[s][r]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let r=s;for(;e[r+1]==="**";)r++;r!==s&&e.splice(s,r-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,r)=>{let n=s[s.length-1];return r==="**"&&n==="**"?s:r===".."&&n&&n!==".."&&n!=="."&&n!=="**"?(s.pop(),s):(s.push(r),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let r=1;r<t.length-1;r++){let n=t[r];r===1&&n===""&&t[0]===""||(n==="."||n==="")&&(e=!0,t.splice(r,1),r--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let s=0;for(;(s=t.indexOf("..",s+1))!==-1;){let r=t[s-1];r&&r!=="."&&r!==".."&&r!=="**"&&(e=!0,t.splice(s-1,2),s-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let s of t){let r=-1;for(;(r=s.indexOf("**",r+1))!==-1;){let i=r;for(;s[i+1]==="**";)i++;i>r&&s.splice(r+1,i-r);let o=s[r+1],a=s[r+2],l=s[r+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(r,1);let c=s.slice(0);c[r]="**",t.push(c),r--}if(!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let o=s[i];i===1&&o===""&&s[0]===""||(o==="."||o==="")&&(e=!0,s.splice(i,1),i--)}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(e=!0,s.pop())}let n=0;for(;(n=s.indexOf("..",n+1))!==-1;){let i=s[n-1];if(i&&i!=="."&&i!==".."&&i!=="**"){e=!0;let o=n===1&&s[n+1]==="**"?["."]:[];s.splice(n-1,2,...o),s.length===0&&s.push(""),n-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let s=e+1;s<t.length;s++){let r=this.partsMatch(t[e],t[s],!this.preserveMultipleSlashes);if(r){t[e]=[],t[s]=r;break}}return t.filter(e=>e.length)}partsMatch(t,e,s=!1){let r=0,n=0,i=[],o="";for(;r<t.length&&n<e.length;)if(t[r]===e[n])i.push(o==="b"?e[n]:t[r]),r++,n++;else if(s&&t[r]==="**"&&e[n]===t[r+1])i.push(t[r]),r++;else if(s&&e[n]==="**"&&t[r]===e[n+1])i.push(e[n]),n++;else if(t[r]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(o==="b")return!1;o="a",i.push(t[r]),r++,n++}else if(e[n]==="*"&&t[r]&&(this.options.dot||!t[r].startsWith("."))&&t[r]!=="**"){if(o==="a")return!1;o="b",i.push(e[n]),r++,n++}else return!1;return t.length===e.length&&i}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,s=0;for(let r=0;r<t.length&&t.charAt(r)==="!";r++)e=!e,s++;s&&(this.pattern=t.slice(s)),this.negate=e}matchOne(t,e,s=!1){let r=this.options;if(this.isWindows){let p=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),y=!p&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),v=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!v&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),b=y?3:p?0:void 0,R=S?3:v?0:void 0;if(typeof b=="number"&&typeof R=="number"){let[_,A]=[t[b],e[R]];_.toLowerCase()===A.toLowerCase()&&(e[R]=_,R>b?e=e.slice(R):b>R&&(t=t.slice(b)))}}let{optimizationLevel:n=1}=this.options;n>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var i=0,o=0,a=t.length,l=e.length;i<a&&o<l;i++,o++){this.debug("matchOne loop");var c=e[o],h=t[i];if(this.debug(e,c,h),c===!1)return!1;if(c===Tt){this.debug("GLOBSTAR",[e,c,h]);var d=i,m=o+1;if(m===l){for(this.debug("** at the end");i<a;i++)if(t[i]==="."||t[i]===".."||!r.dot&&t[i].charAt(0)===".")return!1;return!0}for(;d<a;){var g=t[d];if(this.debug(`
7
+ globstar while`,t,d,e,m,g),this.matchOne(t.slice(d),e.slice(m),s))return this.debug("globstar found match!",d,a,g),!0;if(g==="."||g===".."||!r.dot&&g.charAt(0)==="."){this.debug("dot detected!",t,d,e,m);break}this.debug("globstar swallow a segment, and continue"),d++}return!!(s&&(this.debug(`
8
+ >>> no match, partial?`,t,d,e,m),d===a))}let p;if(typeof c=="string"?(p=h===c,this.debug("string match",c,h,p)):(p=c.test(h),this.debug("pattern match",c,h,p)),!p)return!1}if(i===a&&o===l)return!0;if(i===a)return s;if(o===l)return i===a-1&&t[i]==="";throw new Error("wtf?")}braceExpand(){return qi(this.pattern,this.options)}parse(t){Ks(t);let e=this.options;if(t==="**")return Tt;if(t==="")return"";let s,r=null;(s=t.match(mc))?r=e.dot?yc:wc:(s=t.match(oc))?r=(e.nocase?e.dot?uc:cc:e.dot?lc:ac)(s[1]):(s=t.match(bc))?r=(e.nocase?e.dot?vc:Sc:e.dot?kc:xc)(s):(s=t.match(hc))?r=e.dot?pc:dc:(s=t.match(fc))&&(r=gc);let n=Ui.fromGlob(t,this.options).toMMPattern();return r&&typeof n=="object"&&Reflect.defineProperty(n,"test",{value:r}),n}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Ec:e.dot?Rc:Ac,r=new Set(e.nocase?["i"]:[]),n=t.map(a=>{let l=a.map(h=>{if(h instanceof RegExp)for(let d of h.flags.split(""))r.add(d);return typeof h=="string"?Mc(h):h===Tt?Tt:h._src});l.forEach((h,d)=>{let m=l[d+1],g=l[d-1];h!==Tt||g===Tt||(g===void 0?m!==void 0&&m!==Tt?l[d+1]="(?:\\/|"+s+"\\/)?"+m:l[d]=s:m===void 0?l[d-1]=g+"(?:\\/|\\/"+s+")?":m!==Tt&&(l[d-1]=g+"(?:\\/|\\/"+s+"\\/)"+m,l[d+1]=Tt))});let c=l.filter(h=>h!==Tt);if(this.partial&&c.length>=1){let h=[];for(let d=1;d<=c.length;d++)h.push(c.slice(0,d).join("/"));return"(?:"+h.join("|")+")"}return c.join("/")}).join("|"),[i,o]=t.length>1?["(?:",")"]:["",""];n="^"+i+n+o+"$",this.partial&&(n="^(?:\\/|"+i+n.slice(1,-1)+o+")$"),this.negate&&(n="^(?!"+n+").+$");try{this.regexp=new RegExp(n,[...r].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let r=this.slashSplit(t);this.debug(this.pattern,"split",r);let n=this.set;this.debug(this.pattern,"set",n);let i=r[r.length-1];if(!i)for(let o=r.length-2;!i&&o>=0;o--)i=r[o];for(let o=0;o<n.length;o++){let a=n[o],l=r;if(s.matchBase&&a.length===1&&(l=[i]),this.matchOne(l,a,e))return s.flipNegate?!0:!this.negate}return s.flipNegate?!1:this.negate}static defaults(t){return Ct.defaults(t).Minimatch}};Ct.AST=Ui;Ct.Minimatch=fe;Ct.escape=ji;Ct.unescape=ze;var Dc=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Xi=new Set,tn=typeof process=="object"&&process?process:{},Vi=(t,e,s,r)=>{typeof tn.emitWarning=="function"?tn.emitWarning(t,e,s,r):console.error(`[${s}] ${e}: ${t}`)},Js=globalThis.AbortController,Si=globalThis.AbortSignal;if(typeof Js>"u"){Si=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(s,r){this._onabort.push(r)}},Js=class{constructor(){e()}signal=new Si;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=!0;for(let r of this.signal._onabort)r(s);this.signal.onabort?.(s)}}};let t=tn.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Vi("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Oc=t=>!Xi.has(t),pe=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Yi=t=>pe(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?Vs:null:null,Vs=class extends Array{constructor(t){super(t),this.fill(0)}},Lc=class cs{heap;length;static#t=!1;static create(e){let s=Yi(e);if(!s)return[];cs.#t=!0;let r=new cs(e,s);return cs.#t=!1,r}constructor(e,s){if(!cs.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new s(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Qs=class Ki{#t;#s;#i;#n;#o;#S;#w;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#r;#p;#v;#b;#f;#A;#g;#T;#C;#m;#y;#k;#E;#e;#F;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#m,autopurgeTimers:e.#y,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#r,next:e.#p,prev:e.#v,get head(){return e.#b},get tail(){return e.#f},free:e.#A,isBackgroundFetch:s=>e.#c(s),backgroundFetch:(s,r,n,i)=>e.#j(s,r,n,i),moveToTail:s=>e.#O(s),indexes:s=>e.#_(s),rindexes:s=>e.#I(s),isStale:s=>e.#x(s)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#i}get onInsert(){return this.#n}get disposeAfter(){return this.#o}constructor(e){let{max:s=0,ttl:r,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:h,disposeAfter:d,noDisposeOnSet:m,noUpdateTTL:g,maxSize:p=0,maxEntrySize:y=0,sizeCalculation:v,fetchMethod:S,memoMethod:b,noDeleteOnFetchRejection:R,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:A,allowStaleOnFetchAbort:G,ignoreFetchAbort:L,perf:I}=e;if(I!==void 0&&typeof I?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=I??Dc,s!==0&&!pe(s))throw new TypeError("max option must be a nonnegative integer");let f=s?Yi(s):Array;if(!f)throw new Error("invalid max value: "+s);if(this.#t=s,this.#s=p,this.maxEntrySize=y||this.#s,this.sizeCalculation=v,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=b,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=S,this.#E=!!S,this.#h=new Map,this.#l=new Array(s).fill(void 0),this.#r=new Array(s).fill(void 0),this.#p=new f(s),this.#v=new f(s),this.#b=0,this.#f=0,this.#A=Lc.create(s),this.#a=0,this.#d=0,typeof c=="function"&&(this.#i=c),typeof h=="function"&&(this.#n=h),typeof d=="function"?(this.#o=d,this.#g=[]):(this.#o=void 0,this.#g=void 0),this.#k=!!this.#i,this.#F=!!this.#n,this.#e=!!this.#o,this.noDisposeOnSet=!!m,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!R,this.allowStaleOnFetchRejection=!!A,this.allowStaleOnFetchAbort=!!G,this.ignoreFetchAbort=!!L,this.maxEntrySize!==0){if(this.#s!==0&&!pe(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!pe(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=pe(n)||n===0?n:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!pe(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#$()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let N="LRU_CACHE_UNBOUNDED";Oc(N)&&(Xi.add(N),Vi("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,Ki))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#$(){let e=new Vs(this.#t),s=new Vs(this.#t);this.#m=e,this.#C=s;let r=this.ttlAutopurge?new Array(this.#t):void 0;this.#y=r,this.#N=(o,a,l=this.#u.now())=>{if(s[o]=a!==0?l:0,e[o]=a,r?.[o]&&(clearTimeout(r[o]),r[o]=void 0),a!==0&&r){let c=setTimeout(()=>{this.#x(o)&&this.#P(this.#l[o],"expire")},a+1);c.unref&&c.unref(),r[o]=c}},this.#R=o=>{s[o]=e[o]!==0?this.#u.now():0},this.#M=(o,a)=>{if(e[a]){let l=e[a],c=s[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=n||i();let h=o.now-c;o.remainingTTL=l-h}};let n=0,i=()=>{let o=this.#u.now();if(this.ttlResolution>0){n=o;let a=setTimeout(()=>n=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=s[a];if(!l||!c)return 1/0;let h=(n||i())-c;return l-h},this.#x=o=>{let a=s[o],l=e[o];return!!l&&!!a&&(n||i())-a>l}}#R=()=>{};#M=()=>{};#N=()=>{};#x=()=>!1;#G(){let e=new Vs(this.#t);this.#d=0,this.#T=e,this.#L=s=>{this.#d-=e[s],e[s]=0},this.#B=(s,r,n,i)=>{if(this.#c(r))return 0;if(!pe(n))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(n=i(r,s),!pe(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return n},this.#D=(s,r,n)=>{if(e[s]=r,this.#s){let i=this.#s-e[s];for(;this.#d>i;)this.#U(!0)}this.#d+=e[s],n&&(n.entrySize=r,n.totalCalculatedSize=this.#d)}}#L=e=>{};#D=(e,s,r)=>{};#B=(e,s,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#a)for(let s=this.#f;!(!this.#W(s)||((e||!this.#x(s))&&(yield s),s===this.#b));)s=this.#v[s]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let s=this.#b;!(!this.#W(s)||((e||!this.#x(s))&&(yield s),s===this.#f));)s=this.#p[s]}#W(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#_())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#r[e])&&(yield[this.#l[e],this.#r[e]])}*rentries(){for(let e of this.#I())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#r[e])&&(yield[this.#l[e],this.#r[e]])}*keys(){for(let e of this.#_()){let s=this.#l[e];s!==void 0&&!this.#c(this.#r[e])&&(yield s)}}*rkeys(){for(let e of this.#I()){let s=this.#l[e];s!==void 0&&!this.#c(this.#r[e])&&(yield s)}}*values(){for(let e of this.#_())this.#r[e]!==void 0&&!this.#c(this.#r[e])&&(yield this.#r[e])}*rvalues(){for(let e of this.#I())this.#r[e]!==void 0&&!this.#c(this.#r[e])&&(yield this.#r[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,s={}){for(let r of this.#_()){let n=this.#r[r],i=this.#c(n)?n.__staleWhileFetching:n;if(i!==void 0&&e(i,this.#l[r],this))return this.get(this.#l[r],s)}}forEach(e,s=this){for(let r of this.#_()){let n=this.#r[r],i=this.#c(n)?n.__staleWhileFetching:n;i!==void 0&&e.call(s,i,this.#l[r],this)}}rforEach(e,s=this){for(let r of this.#I()){let n=this.#r[r],i=this.#c(n)?n.__staleWhileFetching:n;i!==void 0&&e.call(s,i,this.#l[r],this)}}purgeStale(){let e=!1;for(let s of this.#I({allowStale:!0}))this.#x(s)&&(this.#P(this.#l[s],"expire"),e=!0);return e}info(e){let s=this.#h.get(e);if(s===void 0)return;let r=this.#r[s],n=this.#c(r)?r.__staleWhileFetching:r;if(n===void 0)return;let i={value:n};if(this.#m&&this.#C){let o=this.#m[s],a=this.#C[s];if(o&&a){let l=o-(this.#u.now()-a);i.ttl=l,i.start=Date.now()}}return this.#T&&(i.size=this.#T[s]),i}dump(){let e=[];for(let s of this.#_({allowStale:!0})){let r=this.#l[s],n=this.#r[s],i=this.#c(n)?n.__staleWhileFetching:n;if(i===void 0||r===void 0)continue;let o={value:i};if(this.#m&&this.#C){o.ttl=this.#m[s];let a=this.#u.now()-this.#C[s];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[s]),e.unshift([r,o])}return e}load(e){this.clear();for(let[s,r]of e){if(r.start){let n=Date.now()-r.start;r.start=this.#u.now()-n}this.set(s,r.value,r)}}set(e,s,r={}){if(s===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,h=this.#B(e,s,r.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#P(e,"set"),this;let d=this.#a===0?void 0:this.#h.get(e);if(d===void 0)d=this.#a===0?this.#f:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#l[d]=e,this.#r[d]=s,this.#h.set(e,d),this.#p[this.#f]=d,this.#v[d]=this.#f,this.#f=d,this.#a++,this.#D(d,h,l),l&&(l.set="add"),c=!1,this.#F&&this.#n?.(s,e,"add");else{this.#O(d);let m=this.#r[d];if(s!==m){if(this.#E&&this.#c(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=m;g!==void 0&&!o&&(this.#k&&this.#i?.(g,e,"set"),this.#e&&this.#g?.push([g,e,"set"]))}else o||(this.#k&&this.#i?.(m,e,"set"),this.#e&&this.#g?.push([m,e,"set"]));if(this.#L(d),this.#D(d,h,l),this.#r[d]=s,l){l.set="replace";let g=m&&this.#c(m)?m.__staleWhileFetching:m;g!==void 0&&(l.oldValue=g)}}else l&&(l.set="update");this.#F&&this.onInsert?.(s,e,s===m?"update":"replace")}if(n!==0&&!this.#m&&this.#$(),this.#m&&(c||this.#N(d,n,i),l&&this.#M(l,d)),!o&&this.#e&&this.#g){let m=this.#g,g;for(;g=m?.shift();)this.#o?.(...g)}return this}pop(){try{for(;this.#a;){let e=this.#r[this.#b];if(this.#U(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#e&&this.#g){let e=this.#g,s;for(;s=e?.shift();)this.#o?.(...s)}}}#U(e){let s=this.#b,r=this.#l[s],n=this.#r[s];return this.#E&&this.#c(n)?n.__abortController.abort(new Error("evicted")):(this.#k||this.#e)&&(this.#k&&this.#i?.(n,r,"evict"),this.#e&&this.#g?.push([n,r,"evict"])),this.#L(s),this.#y?.[s]&&(clearTimeout(this.#y[s]),this.#y[s]=void 0),e&&(this.#l[s]=void 0,this.#r[s]=void 0,this.#A.push(s)),this.#a===1?(this.#b=this.#f=0,this.#A.length=0):this.#b=this.#p[s],this.#h.delete(r),this.#a--,s}has(e,s={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=s,i=this.#h.get(e);if(i!==void 0){let o=this.#r[i];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#x(i))n&&(n.has="stale",this.#M(n,i));else return r&&this.#R(i),n&&(n.has="hit",this.#M(n,i)),!0}else n&&(n.has="miss");return!1}peek(e,s={}){let{allowStale:r=this.allowStale}=s,n=this.#h.get(e);if(n===void 0||!r&&this.#x(n))return;let i=this.#r[n];return this.#c(i)?i.__staleWhileFetching:i}#j(e,s,r,n){let i=s===void 0?void 0:this.#r[s];if(this.#c(i))return i;let o=new Js,{signal:a}=r;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:r,context:n},c=(y,v=!1)=>{let{aborted:S}=o.signal,b=r.ignoreFetchAbort&&y!==void 0,R=r.ignoreFetchAbort||!!(r.allowStaleOnFetchAbort&&y!==void 0);if(r.status&&(S&&!v?(r.status.fetchAborted=!0,r.status.fetchError=o.signal.reason,b&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),S&&!b&&!v)return d(o.signal.reason,R);let _=g,A=this.#r[s];return(A===g||b&&v&&A===void 0)&&(y===void 0?_.__staleWhileFetching!==void 0?this.#r[s]=_.__staleWhileFetching:this.#P(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,y,l.options))),y},h=y=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=y),d(y,!1)),d=(y,v)=>{let{aborted:S}=o.signal,b=S&&r.allowStaleOnFetchAbort,R=b||r.allowStaleOnFetchRejection,_=R||r.noDeleteOnFetchRejection,A=g;if(this.#r[s]===g&&(!_||!v&&A.__staleWhileFetching===void 0?this.#P(e,"fetch"):b||(this.#r[s]=A.__staleWhileFetching)),R)return r.status&&A.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),A.__staleWhileFetching;if(A.__returned===A)throw y},m=(y,v)=>{let S=this.#S?.(e,i,l);S&&S instanceof Promise&&S.then(b=>y(b===void 0?void 0:b),v),o.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(y(void 0),r.allowStaleOnFetchAbort&&(y=b=>c(b,!0)))})};r.status&&(r.status.fetchDispatched=!0);let g=new Promise(m).then(c,h),p=Object.assign(g,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return s===void 0?(this.set(e,p,{...l.options,status:void 0}),s=this.#h.get(e)):this.#r[s]=p,p}#c(e){if(!this.#E)return!1;let s=e;return!!s&&s instanceof Promise&&s.hasOwnProperty("__staleWhileFetching")&&s.__abortController instanceof Js}async fetch(e,s={}){let{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:y,forceRefresh:v=!1,status:S,signal:b}=s;if(!this.#E)return S&&(S.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:S});let R={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:p,ignoreFetchAbort:g,status:S,signal:b},_=this.#h.get(e);if(_===void 0){S&&(S.fetch="miss");let A=this.#j(e,_,R,y);return A.__returned=A}else{let A=this.#r[_];if(this.#c(A)){let f=r&&A.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",f&&(S.returnedStale=!0)),f?A.__staleWhileFetching:A.__returned=A}let G=this.#x(_);if(!v&&!G)return S&&(S.fetch="hit"),this.#O(_),n&&this.#R(_),S&&this.#M(S,_),A;let L=this.#j(e,_,R,y),I=L.__staleWhileFetching!==void 0&&r;return S&&(S.fetch=G?"stale":"refresh",I&&G&&(S.returnedStale=!0)),I?L.__staleWhileFetching:L.__returned=L}}async forceFetch(e,s={}){let r=await this.fetch(e,s);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,s={}){let r=this.#w;if(!r)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:i,...o}=s,a=this.get(e,o);if(!i&&a!==void 0)return a;let l=r(e,a,{options:o,context:n});return this.set(e,l,o),l}get(e,s={}){let{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=s,a=this.#h.get(e);if(a!==void 0){let l=this.#r[a],c=this.#c(l);return o&&this.#M(o,a),this.#x(a)?(o&&(o.get="stale"),c?(o&&r&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#P(e,"expire"),o&&r&&(o.returnedStale=!0),r?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#O(a),n&&this.#R(a),l))}else o&&(o.get="miss")}#z(e,s){this.#v[s]=e,this.#p[e]=s}#O(e){e!==this.#f&&(e===this.#b?this.#b=this.#p[e]:this.#z(this.#v[e],this.#p[e]),this.#z(this.#f,e),this.#f=e)}delete(e){return this.#P(e,"delete")}#P(e,s){let r=!1;if(this.#a!==0){let n=this.#h.get(e);if(n!==void 0)if(this.#y?.[n]&&(clearTimeout(this.#y?.[n]),this.#y[n]=void 0),r=!0,this.#a===1)this.#H(s);else{this.#L(n);let i=this.#r[n];if(this.#c(i)?i.__abortController.abort(new Error("deleted")):(this.#k||this.#e)&&(this.#k&&this.#i?.(i,e,s),this.#e&&this.#g?.push([i,e,s])),this.#h.delete(e),this.#l[n]=void 0,this.#r[n]=void 0,n===this.#f)this.#f=this.#v[n];else if(n===this.#b)this.#b=this.#p[n];else{let o=this.#v[n];this.#p[o]=this.#p[n];let a=this.#p[n];this.#v[a]=this.#v[n]}this.#a--,this.#A.push(n)}}if(this.#e&&this.#g?.length){let n=this.#g,i;for(;i=n?.shift();)this.#o?.(...i)}return r}clear(){return this.#H("delete")}#H(e){for(let s of this.#I({allowStale:!0})){let r=this.#r[s];if(this.#c(r))r.__abortController.abort(new Error("deleted"));else{let n=this.#l[s];this.#k&&this.#i?.(r,n,e),this.#e&&this.#g?.push([r,n,e])}}if(this.#h.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#m&&this.#C){this.#m.fill(0),this.#C.fill(0);for(let s of this.#y??[])s!==void 0&&clearTimeout(s);this.#y?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#b=0,this.#f=0,this.#A.length=0,this.#d=0,this.#a=0,this.#e&&this.#g){let s=this.#g,r;for(;r=s?.shift();)this.#o?.(...r)}}},vi=typeof process=="object"&&process?process:{stdout:null,stderr:null},Jc=t=>!!t&&typeof t=="object"&&(t instanceof Zs||t instanceof Ji||Zc(t)||Qc(t)),Zc=t=>!!t&&typeof t=="object"&&t instanceof nn&&typeof t.pipe=="function"&&t.pipe!==Ji.Writable.prototype.pipe,Qc=t=>!!t&&typeof t=="object"&&t instanceof nn&&typeof t.write=="function"&&typeof t.end=="function",ie=Symbol("EOF"),oe=Symbol("maybeEmitEnd"),de=Symbol("emittedEnd"),Us=Symbol("emittingEnd"),rs=Symbol("emittedError"),js=Symbol("closed"),ki=Symbol("read"),zs=Symbol("flush"),xi=Symbol("flushChunk"),Gt=Symbol("encoding"),Ue=Symbol("decoder"),gt=Symbol("flowing"),ns=Symbol("paused"),je=Symbol("resume"),mt=Symbol("buffer"),xt=Symbol("pipes"),wt=Symbol("bufferLength"),Xr=Symbol("bufferPush"),Gs=Symbol("bufferShift"),St=Symbol("objectMode"),ut=Symbol("destroyed"),Vr=Symbol("error"),Yr=Symbol("emitData"),Ti=Symbol("emitEnd"),Kr=Symbol("emitEnd2"),Vt=Symbol("async"),Jr=Symbol("abort"),Hs=Symbol("aborted"),is=Symbol("signal"),Te=Symbol("dataListeners"),Mt=Symbol("discarded"),os=t=>Promise.resolve().then(t),tu=t=>t(),eu=t=>t==="end"||t==="finish"||t==="prefinish",su=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,ru=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Zi=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[je](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},nu=class extends Zi{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}},iu=t=>!!t.objectMode,ou=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Zs=class extends nn{[gt]=!1;[ns]=!1;[xt]=[];[mt]=[];[St];[Gt];[Vt];[Ue];[ie]=!1;[de]=!1;[Us]=!1;[js]=!1;[rs]=null;[wt]=0;[ut]=!1;[is];[Hs]=!1;[Te]=0;[Mt]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");iu(e)?(this[St]=!0,this[Gt]=null):ou(e)?(this[Gt]=e.encoding,this[St]=!1):(this[St]=!1,this[Gt]=null),this[Vt]=!!e.async,this[Ue]=this[Gt]?new Kc(this[Gt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[mt]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[xt]});let{signal:s}=e;s&&(this[is]=s,s.aborted?this[Jr]():s.addEventListener("abort",()=>this[Jr]()))}get bufferLength(){return this[wt]}get encoding(){return this[Gt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[St]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Vt]}set async(t){this[Vt]=this[Vt]||!!t}[Jr](){this[Hs]=!0,this.emit("abort",this[is]?.reason),this.destroy(this[is]?.reason)}get aborted(){return this[Hs]}set aborted(t){}write(t,e,s){if(this[Hs])return!1;if(this[ie])throw new Error("write after end");if(this[ut])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let r=this[Vt]?os:tu;if(!this[St]&&!Buffer.isBuffer(t)){if(ru(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(su(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[St]?(this[gt]&&this[wt]!==0&&this[zs](!0),this[gt]?this.emit("data",t):this[Xr](t),this[wt]!==0&&this.emit("readable"),s&&r(s),this[gt]):t.length?(typeof t=="string"&&!(e===this[Gt]&&!this[Ue]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Gt]&&(t=this[Ue].write(t)),this[gt]&&this[wt]!==0&&this[zs](!0),this[gt]?this.emit("data",t):this[Xr](t),this[wt]!==0&&this.emit("readable"),s&&r(s),this[gt]):(this[wt]!==0&&this.emit("readable"),s&&r(s),this[gt])}read(t){if(this[ut])return null;if(this[Mt]=!1,this[wt]===0||t===0||t&&t>this[wt])return this[oe](),null;this[St]&&(t=null),this[mt].length>1&&!this[St]&&(this[mt]=[this[Gt]?this[mt].join(""):Buffer.concat(this[mt],this[wt])]);let e=this[ki](t||null,this[mt][0]);return this[oe](),e}[ki](t,e){if(this[St])this[Gs]();else{let s=e;t===s.length||t===null?this[Gs]():typeof s=="string"?(this[mt][0]=s.slice(t),e=s.slice(0,t),this[wt]-=t):(this[mt][0]=s.subarray(t),e=s.subarray(0,t),this[wt]-=t)}return this.emit("data",e),!this[mt].length&&!this[ie]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[ie]=!0,this.writable=!1,(this[gt]||!this[ns])&&this[oe](),this}[je](){this[ut]||(!this[Te]&&!this[xt].length&&(this[Mt]=!0),this[ns]=!1,this[gt]=!0,this.emit("resume"),this[mt].length?this[zs]():this[ie]?this[oe]():this.emit("drain"))}resume(){return this[je]()}pause(){this[gt]=!1,this[ns]=!0,this[Mt]=!1}get destroyed(){return this[ut]}get flowing(){return this[gt]}get paused(){return this[ns]}[Xr](t){this[St]?this[wt]+=1:this[wt]+=t.length,this[mt].push(t)}[Gs](){return this[St]?this[wt]-=1:this[wt]-=this[mt][0].length,this[mt].shift()}[zs](t=!1){do;while(this[xi](this[Gs]())&&this[mt].length);!t&&!this[mt].length&&!this[ie]&&this.emit("drain")}[xi](t){return this.emit("data",t),this[gt]}pipe(t,e){if(this[ut])return t;this[Mt]=!1;let s=this[de];return e=e||{},t===vi.stdout||t===vi.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[xt].push(e.proxyErrors?new nu(this,t,e):new Zi(this,t,e)),this[Vt]?os(()=>this[je]()):this[je]()),t}unpipe(t){let e=this[xt].find(s=>s.dest===t);e&&(this[xt].length===1?(this[gt]&&this[Te]===0&&(this[gt]=!1),this[xt]=[]):this[xt].splice(this[xt].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[Mt]=!1,this[Te]++,!this[xt].length&&!this[gt]&&this[je]();else if(t==="readable"&&this[wt]!==0)super.emit("readable");else if(eu(t)&&this[de])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[rs]){let r=e;this[Vt]?os(()=>r.call(this,this[rs])):r.call(this,this[rs])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Te]=this.listeners("data").length,this[Te]===0&&!this[Mt]&&!this[xt].length&&(this[gt]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Te]=0,!this[Mt]&&!this[xt].length&&(this[gt]=!1)),e}get emittedEnd(){return this[de]}[oe](){!this[Us]&&!this[de]&&!this[ut]&&this[mt].length===0&&this[ie]&&(this[Us]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[js]&&this.emit("close"),this[Us]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==ut&&this[ut])return!1;if(t==="data")return!this[St]&&!s?!1:this[Vt]?(os(()=>this[Yr](s)),!0):this[Yr](s);if(t==="end")return this[Ti]();if(t==="close"){if(this[js]=!0,!this[de]&&!this[ut])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[rs]=s,super.emit(Vr,s);let n=!this[is]||this.listeners("error").length?super.emit("error",s):!1;return this[oe](),n}else if(t==="resume"){let n=super.emit("resume");return this[oe](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let r=super.emit(t,...e);return this[oe](),r}[Yr](t){for(let s of this[xt])s.dest.write(t)===!1&&this.pause();let e=this[Mt]?!1:super.emit("data",t);return this[oe](),e}[Ti](){return this[de]?!1:(this[de]=!0,this.readable=!1,this[Vt]?(os(()=>this[Kr]()),!0):this[Kr]())}[Kr](){if(this[Ue]){let e=this[Ue].end();if(e){for(let s of this[xt])s.dest.write(e);this[Mt]||super.emit("data",e)}}for(let e of this[xt])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[St]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[St]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[St])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Gt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ut,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[Mt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let s=this.read();if(s!==null)return Promise.resolve({done:!1,value:s});if(this[ie])return e();let r,n,i=c=>{this.off("data",o),this.off("end",a),this.off(ut,l),e(),n(c)},o=c=>{this.off("error",i),this.off("end",a),this.off(ut,l),this.pause(),r({value:c,done:!!this[ie]})},a=()=>{this.off("error",i),this.off("data",o),this.off(ut,l),e(),r({done:!0,value:void 0})},l=()=>i(new Error("stream destroyed"));return new Promise((c,h)=>{n=h,r=c,this.once(ut,l),this.once("error",i),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[Mt]=!1;let t=!1,e=()=>(this.pause(),this.off(Vr,e),this.off(ut,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let r=this.read();return r===null?e():{done:!1,value:r}};return this.once("end",e),this.once(Vr,e),this.once(ut,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ut])return t?this.emit("error",t):this.emit(ut),this;this[ut]=!0,this[Mt]=!0,this[mt].length=0,this[wt]=0;let e=this;return typeof e.close=="function"&&!this[js]&&e.close(),t?this.emit("error",t):this.emit(ut),this}static get isStream(){return Jc}},au=Gc.native,us={lstatSync:Wc,readdir:Uc,readdirSync:jc,readlinkSync:zc,realpathSync:au,promises:{lstat:qc,readdir:Xc,readlink:Vc,realpath:Yc}},Qi=t=>!t||t===us||t===Hc?us:{...us,...t,promises:{...us.promises,...t.promises||{}}},to=/^\\\\\?\\([a-z]:)\\?$/i,lu=t=>t.replace(/\//g,"\\").replace(to,"$1\\"),cu=/[\\\/]/,Ut=0,eo=1,so=2,Yt=4,ro=6,no=8,Ce=10,io=12,Wt=15,as=~Wt,Zr=16,Ci=32,hs=64,Ht=128,qs=256,Ys=512,Ei=hs|Ht|Ys,uu=1023,Qr=t=>t.isFile()?no:t.isDirectory()?Yt:t.isSymbolicLink()?Ce:t.isCharacterDevice()?so:t.isBlockDevice()?ro:t.isSocket()?io:t.isFIFO()?eo:Ut,Ri=new Qs({max:2**12}),ds=t=>{let e=Ri.get(t);if(e)return e;let s=t.normalize("NFKD");return Ri.set(t,s),s},Ai=new Qs({max:2**12}),Xs=t=>{let e=Ai.get(t);if(e)return e;let s=ds(t.toLowerCase());return Ai.set(t,s),s},Pi=class extends Qs{constructor(){super({max:256})}},hu=class extends Qs{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},oo=Symbol("PathScurry setAsCwd"),At=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#i;get mode(){return this.#i}#n;get nlink(){return this.#n}#o;get uid(){return this.#o}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#r;get mtimeMs(){return this.#r}#p;get ctimeMs(){return this.#p}#v;get birthtimeMs(){return this.#v}#b;get atime(){return this.#b}#f;get mtime(){return this.#f}#A;get ctime(){return this.#A}#g;get birthtime(){return this.#g}#T;#C;#m;#y;#k;#E;#e;#F;#$;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=Ut,s,r,n,i,o){this.name=t,this.#T=n?Xs(t):ds(t),this.#e=e&uu,this.nocase=n,this.roots=r,this.root=s||this,this.#F=i,this.#m=o.fullpath,this.#k=o.relative,this.#E=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=Qi(o.fs)}depth(){return this.#C!==void 0?this.#C:this.parent?this.#C=this.parent.depth()+1:this.#C=0}childrenCache(){return this.#F}resolve(t){if(!t)return this;let e=this.getRootString(t),s=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#M(s):this.#M(s)}#M(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#F.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#F.set(this,e),this.#e&=~Zr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),r=this.nocase?Xs(t):ds(t);for(let a of s)if(a.#T===r)return a;let n=this.parent?this.sep:"",i=this.#m?this.#m+n+t:void 0,o=this.newChild(t,Ut,{...e,parent:this,fullpath:i});return this.canReaddir()||(o.#e|=Ht),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#k!==void 0)return this.#k;let t=this.name,e=this.parent;if(!e)return this.#k=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#E!==void 0)return this.#E;let t=this.name,e=this.parent;if(!e)return this.#E=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#m!==void 0)return this.#m;let t=this.name,e=this.parent;if(!e)return this.#m=this.name;let s=e.fullpath()+(e.parent?this.sep:"")+t;return this.#m=s}fullpathPosix(){if(this.#y!==void 0)return this.#y;if(this.sep==="/")return this.#y=this.fullpath();if(!this.parent){let r=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(r)?this.#y=`//?/${r}`:this.#y=r}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#y=s}isUnknown(){return(this.#e&Wt)===Ut}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&Wt)===no}isDirectory(){return(this.#e&Wt)===Yt}isCharacterDevice(){return(this.#e&Wt)===so}isBlockDevice(){return(this.#e&Wt)===ro}isFIFO(){return(this.#e&Wt)===eo}isSocket(){return(this.#e&Wt)===io}isSymbolicLink(){return(this.#e&Ce)===Ce}lstatCached(){return this.#e&Ci?this:void 0}readlinkCached(){return this.#$}realpathCached(){return this.#R}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#$)return!0;if(!this.parent)return!1;let t=this.#e&Wt;return!(t!==Ut&&t!==Ce||this.#e&qs||this.#e&Ht)}calledReaddir(){return!!(this.#e&Zr)}isENOENT(){return!!(this.#e&Ht)}isNamed(t){return this.nocase?this.#T===Xs(t):this.#T===ds(t)}async readlink(){let t=this.#$;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#$=s}catch(e){this.#I(e.code);return}}readlinkSync(){let t=this.#$;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#$=s}catch(e){this.#I(e.code);return}}#N(t){this.#e|=Zr;for(let e=t.provisional;e<t.length;e++){let s=t[e];s&&s.#x()}}#x(){this.#e&Ht||(this.#e=(this.#e|Ht)&as,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#x()}#L(){this.#e|=Ys,this.#D()}#D(){if(this.#e&hs)return;let t=this.#e;(t&Wt)===Yt&&(t&=as),this.#e=t|hs,this.#G()}#B(t=""){t==="ENOTDIR"||t==="EPERM"?this.#D():t==="ENOENT"?this.#x():this.children().provisional=0}#_(t=""){t==="ENOTDIR"?this.parent.#D():t==="ENOENT"&&this.#x()}#I(t=""){let e=this.#e;e|=qs,t==="ENOENT"&&(e|=Ht),(t==="EINVAL"||t==="UNKNOWN")&&(e&=as),this.#e=e,t==="ENOTDIR"&&this.parent&&this.parent.#D()}#W(t,e){return this.#j(t,e)||this.#U(t,e)}#U(t,e){let s=Qr(t),r=this.newChild(t.name,s,{parent:this}),n=r.#e&Wt;return n!==Yt&&n!==Ce&&n!==Ut&&(r.#e|=hs),e.unshift(r),e.provisional++,r}#j(t,e){for(let s=e.provisional;s<e.length;s++){let r=e[s];if((this.nocase?Xs(t.name):ds(t.name))===r.#T)return this.#c(t,r,s,e)}}#c(t,e,s,r){let n=e.name;return e.#e=e.#e&as|Qr(t),n!==t.name&&(e.name=t.name),s!==r.provisional&&(s===r.length-1?r.pop():r.splice(s,1),r.unshift(e)),r.provisional++,e}async lstat(){if((this.#e&Ht)===0)try{return this.#z(await this.#t.promises.lstat(this.fullpath())),this}catch(t){this.#_(t.code)}}lstatSync(){if((this.#e&Ht)===0)try{return this.#z(this.#t.lstatSync(this.fullpath())),this}catch(t){this.#_(t.code)}}#z(t){let{atime:e,atimeMs:s,birthtime:r,birthtimeMs:n,blksize:i,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:h,ino:d,mode:m,mtime:g,mtimeMs:p,nlink:y,rdev:v,size:S,uid:b}=t;this.#b=e,this.#l=s,this.#g=r,this.#v=n,this.#u=i,this.#h=o,this.#A=a,this.#p=l,this.#s=c,this.#S=h,this.#a=d,this.#i=m,this.#f=g,this.#r=p,this.#n=y,this.#w=v,this.#d=S,this.#o=b;let R=Qr(t);this.#e=this.#e&as|R|Ci,R!==Ut&&R!==Yt&&R!==Ce&&(this.#e|=hs)}#O=[];#P=!1;#H(t){this.#P=!1;let e=this.#O.slice();this.#O.length=0,e.forEach(s=>s(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let n=s.slice(0,s.provisional);e?t(null,n):queueMicrotask(()=>t(null,n));return}if(this.#O.push(t),this.#P)return;this.#P=!0;let r=this.fullpath();this.#t.readdir(r,{withFileTypes:!0},(n,i)=>{if(n)this.#B(n.code),s.provisional=0;else{for(let o of i)this.#W(o,s);this.#N(s)}this.#H(s.slice(0,s.provisional))})}#q;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#q)await this.#q;else{let s=()=>{};this.#q=new Promise(r=>s=r);try{for(let r of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#W(r,t);this.#N(t)}catch(r){this.#B(r.code),t.provisional=0}this.#q=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#W(s,t);this.#N(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ei)return!1;let t=Wt&this.#e;return t===Ut||t===Yt||t===Ce}shouldWalk(t,e){return(this.#e&Yt)===Yt&&!(this.#e&Ei)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#R)return this.#R;if(!((Ys|qs|Ht)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#R=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#R)return this.#R;if(!((Ys|qs|Ht)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#R=this.resolve(t)}catch{this.#L()}}[oo](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],r=this;for(;r&&r.parent;)e.add(r),r.#k=s.join(this.sep),r.#E=s.join("/"),r=r.parent,s.push("..");for(r=t;r&&r.parent&&!e.has(r);)r.#k=void 0,r.#E=void 0,r=r.parent}},ao=class lo extends At{sep="\\";splitSep=cu;constructor(e,s=Ut,r,n,i,o,a){super(e,s,r,n,i,o,a)}newChild(e,s=Ut,r={}){return new lo(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return en.parse(e).root}getRoot(e){if(e=lu(e.toUpperCase()),e===this.root.name)return this.root;for(let[s,r]of Object.entries(this.roots))if(this.sameRoot(e,s))return this.roots[e]=r;return this.roots[e]=new on(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(to,"$1\\"),e===s}},co=class uo extends At{splitSep="/";sep="/";constructor(e,s=Ut,r,n,i,o,a){super(e,s,r,n,i,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,s=Ut,r={}){return new uo(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}},ho=class{root;rootPath;roots;cwd;#t;#s;#i;nocase;#n;constructor(t=process.cwd(),e,s,{nocase:r,childrenCacheSize:n=16*1024,fs:i=us}={}){this.#n=Qi(i),(t instanceof URL||t.startsWith("file://"))&&(t=Bc(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new Pi,this.#s=new Pi,this.#i=new hu(n);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),r===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=r,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,h=e.sep,d=this.rootPath,m=!1;for(let g of a){let p=c--;l=l.child(g,{relative:new Array(p).fill("..").join(h),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(m?"":h)+g}),m=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#i}resolve(...t){let e="";for(let n=t.length-1;n>=0;n--){let i=t[n];if(!(!i||i===".")&&(e=e?`${i}/${e}`:i,this.isAbsolute(i)))break}let s=this.#t.get(e);if(s!==void 0)return s;let r=this.cwd.resolve(e).fullpath();return this.#t.set(e,r),r}resolvePosix(...t){let e="";for(let n=t.length-1;n>=0;n--){let i=t[n];if(!(!i||i===".")&&(e=e?`${i}/${e}`:i,this.isAbsolute(i)))break}let s=this.#s.get(e);if(s!==void 0)return s;let r=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,r),r}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let r=await t.readdir();return s?r:r.map(n=>n.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(r=>r.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:r=!1,filter:n,walkFilter:i}=e,o=[];(!n||n(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(h,d)=>{a.add(h),h.readdirCB((m,g)=>{if(m)return d(m);let p=g.length;if(!p)return d();let y=()=>{--p===0&&d()};for(let v of g)(!n||n(v))&&o.push(s?v:v.fullpath()),r&&v.isSymbolicLink()?v.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,i)?l(S,y):y()):v.shouldWalk(a,i)?l(v,y):y()},!0)},c=t;return new Promise((h,d)=>{l(c,m=>{if(m)return d(m);h(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:r=!1,filter:n,walkFilter:i}=e,o=[];(!n||n(t))&&o.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let h of c){(!n||n(h))&&o.push(s?h:h.fullpath());let d=h;if(h.isSymbolicLink()){if(!(r&&(d=h.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,i)&&a.add(d)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:r=!1,filter:n,walkFilter:i}=e;(!n||n(t))&&(yield s?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!n||n(c))&&(yield s?c:c.fullpath());let h=c;if(c.isSymbolicLink()){if(!(r&&(h=c.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(o,i)&&o.add(h)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:r=!1,filter:n,walkFilter:i}=e,o=new Zs({objectMode:!0});(!n||n(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],c=0,h=()=>{let d=!1;for(;!d;){let m=l.shift();if(!m){c===0&&o.end();return}c++,a.add(m);let g=(y,v,S=!1)=>{if(y)return o.emit("error",y);if(r&&!S){let b=[];for(let R of v)R.isSymbolicLink()&&b.push(R.realpath().then(_=>_?.isUnknown()?_.lstat():_));if(b.length){Promise.all(b).then(()=>g(null,v,!0));return}}for(let b of v)b&&(!n||n(b))&&(o.write(s?b:b.fullpath())||(d=!0));c--;for(let b of v){let R=b.realpathCached()||b;R.shouldWalk(a,i)&&l.push(R)}d&&!o.flowing?o.once("drain",h):p||h()},p=!0;m.readdirCB(g,!0),p=!1}};return h(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof At||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:r=!1,filter:n,walkFilter:i}=e,o=new Zs({objectMode:!0}),a=new Set;(!n||n(t))&&o.write(s?t:t.fullpath());let l=[t],c=0,h=()=>{let d=!1;for(;!d;){let m=l.shift();if(!m){c===0&&o.end();return}c++,a.add(m);let g=m.readdirSync();for(let p of g)(!n||n(p))&&(o.write(s?p:p.fullpath())||(d=!0));c--;for(let p of g){let y=p;if(p.isSymbolicLink()){if(!(r&&(y=p.realpathSync())))continue;y.isUnknown()&&y.lstatSync()}y.shouldWalk(a,i)&&l.push(y)}}d&&!o.flowing&&o.once("drain",h)};return h(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[oo](e)}},on=class extends ho{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,en,"\\",{...e,nocase:s}),this.nocase=s;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase}parseRootPath(t){return en.parse(t).root.toUpperCase()}newRoot(t){return new ao(this.rootPath,Yt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},an=class extends ho{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,Nc,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new co(this.rootPath,Yt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},po=class extends an{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},Xd=process.platform==="win32"?ao:co,du=process.platform==="win32"?on:process.platform==="darwin"?po:an,pu=t=>t.length>=1,fu=t=>t.length>=1,gu=Symbol.for("nodejs.util.inspect.custom"),fo=class go{#t;#s;#i;length;#n;#o;#S;#w;#u;#a;#d=!0;constructor(e,s,r,n){if(!pu(e))throw new TypeError("empty pattern list");if(!fu(s))throw new TypeError("empty glob list");if(s.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#t=e,this.#s=s,this.#i=r,this.#n=n,this.#i===0){if(this.isUNC()){let[i,o,a,l,...c]=this.#t,[h,d,m,g,...p]=this.#s;c[0]===""&&(c.shift(),p.shift());let y=[i,o,a,l,""].join("/"),v=[h,d,m,g,""].join("/");this.#t=[y,...c],this.#s=[v,...p],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[i,...o]=this.#t,[a,...l]=this.#s;o[0]===""&&(o.shift(),l.shift());let c=i+"/",h=a+"/";this.#t=[c,...o],this.#s=[h,...l],this.length=this.#t.length}}}[gu](){return"Pattern <"+this.#s.slice(this.#i).join("/")+">"}pattern(){return this.#t[this.#i]}isString(){return typeof this.#t[this.#i]=="string"}isGlobstar(){return this.#t[this.#i]===Tt}isRegExp(){return this.#t[this.#i]instanceof RegExp}globString(){return this.#S=this.#S||(this.#i===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new go(this.#t,this.#s,this.#i+1,this.#n),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#w=this.#w,this.#o):this.#o=null}isUNC(){let e=this.#t;return this.#u!==void 0?this.#u:this.#u=this.#n==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#n==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#t;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#t[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},mu=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",_i=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:r,noglobstar:n,platform:i=mu}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:r,noglobstar:n,optimizationLevel:2,platform:i,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new fe(t,this.mmopts);for(let s=0;s<e.set.length;s++){let r=e.set[s],n=e.globParts[s];if(!r||!n)throw new Error("invalid pattern object");for(;r[0]==="."&&n[0]===".";)r.shift(),n.shift();let i=new fo(r,n,0,this.platform),o=new fe(i.globString(),this.mmopts),a=n[n.length-1]==="**",l=i.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),s=`${e}/`,r=t.relative()||".",n=`${r}/`;for(let i of this.relative)if(i.match(r)||i.match(n))return!0;for(let i of this.absolute)if(i.match(e)||i.match(s))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",s=(t.relative()||".")+"/";for(let r of this.relativeChildren)if(r.match(s))return!0;for(let r of this.absoluteChildren)if(r.match(e))return!0;return!1}},wu=class mo{store;constructor(e=new Map){this.store=e}copy(){return new mo(new Map(this.store))}hasWalked(e,s){return this.store.get(e.fullpath())?.has(s.globString())}storeWalked(e,s){let r=e.fullpath(),n=this.store.get(r);n?n.add(s.globString()):this.store.set(r,new Set([s.globString()]))}},yu=class{store=new Map;add(t,e,s){let r=(e?2:0)|(s?1:0),n=this.store.get(t);this.store.set(t,n===void 0?r:r&n)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},bu=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(r=>r.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},Ii=class wo{hasWalkedCache;matches=new yu;subwalks=new bu;patterns;follow;dot;opts;constructor(e,s){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=s?s.copy():new wu}processPatterns(e,s){this.patterns=s;let r=s.map(n=>[e,n]);for(let[n,i]of r){this.hasWalkedCache.storeWalked(n,i);let o=i.root(),a=i.isAbsolute()&&this.opts.absolute!==!1;if(o){n=n.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=i.rest();if(d)i=d;else{this.matches.add(n,!0,!1);continue}}if(n.isENOENT())continue;let l,c,h=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)n=n.resolve(l),i=c,h=!0;if(l=i.pattern(),c=i.rest(),h){if(this.hasWalkedCache.hasWalked(n,i))continue;this.hasWalkedCache.storeWalked(n,i)}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(n.resolve(l),a,d);continue}else if(l===Tt){(!n.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(n,i);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(n,a,d===""||d===".");else if(d===".."){let g=n.parent||n;m?this.hasWalkedCache.hasWalked(g,m)||this.subwalks.add(g,m):this.matches.add(g,a,!0)}}else l instanceof RegExp&&this.subwalks.add(n,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new wo(this.opts,this.hasWalkedCache)}filterEntries(e,s){let r=this.subwalks.get(e),n=this.child();for(let i of s)for(let o of r){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===Tt?n.testGlobstar(i,o,c,a):l instanceof RegExp?n.testRegExp(i,l,c,a):n.testString(i,l,c,a)}return n}testGlobstar(e,s,r,n){if((this.dot||!e.name.startsWith("."))&&(s.hasMore()||this.matches.add(e,n,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,s):e.isSymbolicLink()&&(r&&s.checkFollowGlobstar()?this.subwalks.add(e,r):s.markFollowGlobstar()&&this.subwalks.add(e,s)))),r){let i=r.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,r.rest(),n);else if(i===".."){let o=e.parent||e;this.subwalks.add(o,r)}else i instanceof RegExp&&this.testRegExp(e,i,r.rest(),n)}}testRegExp(e,s,r,n){s.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,n,!1))}testString(e,s,r,n){e.isNamed(s)&&(r?this.subwalks.add(e,r):this.matches.add(e,n,!1))}},Su=(t,e)=>typeof t=="string"?new _i([t],e):Array.isArray(t)?new _i(t,e):t,yo=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#i;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Su(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let r="cannot ignore child matches, ignore lacks add() method.";throw new Error(r)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#n(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#o(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let n=await r.realpath();n&&(n.isUnknown()||this.opts.stat)&&await n.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#n(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let n=r.realpathSync();n&&(n?.isUnknown()||this.opts.stat)&&n.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#n(t))return;if(!this.includeChildMatches&&this.#s?.add){let n=`${t.relativePosix()}/**`;this.#s.add(n)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let r=this.opts.mark&&t.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let n=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(n+r)}else{let n=this.opts.posix?t.relativePosix():t.relative(),i=this.opts.dotRelative&&!n.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(n?i+n+r:"."+r)}}async match(t,e,s){let r=await this.matchCheck(t,s);r&&this.matchFinish(r,e)}matchSync(t,e,s){let r=this.matchCheckSync(t,s);r&&this.matchFinish(r,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Ii(this.opts),s)}walkCB2(t,e,s,r){if(this.#o(t))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,r));return}s.processPatterns(t,e);let n=1,i=()=>{--n===0&&r()};for(let[o,a,l]of s.matches.entries())this.#n(o)||(n++,this.match(o,a,l).then(()=>i()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;n++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,s,i):o.readdirCB((l,c)=>this.walkCB3(o,c,s,i),!0)}i()}walkCB3(t,e,s,r){s=s.filterEntries(t,e);let n=1,i=()=>{--n===0&&r()};for(let[o,a,l]of s.matches.entries())this.#n(o)||(n++,this.match(o,a,l).then(()=>i()));for(let[o,a]of s.subwalks.entries())n++,this.walkCB2(o,a,s.child(),i);i()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Ii(this.opts),s)}walkCB2Sync(t,e,s,r){if(this.#o(t))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,r));return}s.processPatterns(t,e);let n=1,i=()=>{--n===0&&r()};for(let[o,a,l]of s.matches.entries())this.#n(o)||this.matchSync(o,a,l);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;n++;let a=o.readdirSync();this.walkCB3Sync(o,a,s,i)}i()}walkCB3Sync(t,e,s,r){s=s.filterEntries(t,e);let n=1,i=()=>{--n===0&&r()};for(let[o,a,l]of s.matches.entries())this.#n(o)||this.matchSync(o,a,l);for(let[o,a]of s.subwalks.entries())n++,this.walkCB2Sync(o,a,s.child(),i);i()}},$i=class extends yo{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Mi=class extends yo{results;constructor(t,e,s){super(t,e,s),this.results=new Zs({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},vu=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ee=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=Fc(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||vu,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?on:e.platform==="darwin"?po:e.platform?an:du;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",r={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},n=this.pattern.map(a=>new fe(a,r)),[i,o]=n.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=i.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new fo(a,c,0,this.platform)})}async walk(){return[...await new $i(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new $i(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Mi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Mi(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},ku=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let s of t)if(new fe(s,e).hasMagic())return!0;return!1};function tr(t,e={}){return new Ee(t,e).streamSync()}function bo(t,e={}){return new Ee(t,e).stream()}function So(t,e={}){return new Ee(t,e).walkSync()}async function Fi(t,e={}){return new Ee(t,e).walk()}function er(t,e={}){return new Ee(t,e).iterateSync()}function vo(t,e={}){return new Ee(t,e).iterate()}var xu=tr,Tu=Object.assign(bo,{sync:tr}),Cu=er,Eu=Object.assign(vo,{sync:er}),Ru=Object.assign(So,{stream:tr,iterate:er}),Ge=Object.assign(Fi,{glob:Fi,globSync:So,sync:Ru,globStream:bo,stream:Tu,globStreamSync:tr,streamSync:xu,globIterate:vo,iterate:Eu,globIterateSync:er,iterateSync:Cu,Glob:Ee,hasMagic:ku,escape:ji,unescape:ze});Ge.glob=Ge;var sr=_u(Au);async function Iu(t){try{return await sr(t,["--version"],{timeout:5e3}),!0}catch{return!1}}async function $u(t){try{return await sr("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3}),!0}catch{return!1}}function Mu(t,e){let s=[],r=t.split(`
9
+ `).filter(Boolean);for(let n of r){let i=n.match(/^(.+?)[:-](\d+)[:-](.*)$/),[,o,a,l]=i??[];o&&a&&l!==void 0&&s.push({file:ko.isAbsolute(o)?o:ko.join(e,o),line:Number.parseInt(a,10),content:l.slice(0,500)})}return s}var xo=async t=>{let e=t.path?$t(t.path):process.cwd(),s=Math.min(t.limit??100,500),r=t.context_lines??0;try{let n="",i="native";if(await Iu("rg")){i="ripgrep";let a=["--line-number","--no-heading","--color=never",`--max-count=${s}`];r>0&&a.push(`-C${r}`),t.include&&a.push(`--glob=${t.include}`),a.push("--",t.pattern,e);try{n=(await sr("rg",a,{timeout:es,maxBuffer:ts})).stdout}catch(l){let c=l;if(c.code===1&&!c.stdout)n="";else if(c.stdout)n=c.stdout;else throw l}}else if(await $u(e)){i="git-grep";let a=["grep","-n","--no-color",`-m${s}`];r>0&&a.push(`-C${r}`),a.push("-e",t.pattern);try{n=(await sr("git",a,{cwd:e,timeout:es,maxBuffer:ts})).stdout}catch(l){if(l.code===1)n="";else throw l}}else{i="native";let a=[],l=new RegExp(t.pattern,"gi"),c=t.include||"**/*",h=await Ge(c,{cwd:e,nodir:!0,absolute:!0}),d=await Ns(e);h=Bs(h,e,d);for(let m of h){if(a.length>=s)break;try{let p=(await Pu.readFile(m,"utf-8")).split(`
10
+ `);for(let[y,v]of p.entries()){if(a.length>=s)break;l.test(v)&&(a.push({file:m,line:y+1,content:v.slice(0,500)}),l.lastIndex=0)}}catch{}}return{success:!0,matches:a,tool:i,total:a.length}}let o=Mu(n,e).slice(0,s);return{success:!0,matches:o,tool:i,total:o.length}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to search file contents"}}};import Fu from"fs/promises";var To=async t=>{try{let e=await Nt(t.path);return{success:!0,entries:(await Fu.readdir(e,{withFileTypes:!0})).map(n=>({name:n.name,type:n.isDirectory()?"directory":n.isFile()?"file":n.isSymbolicLink()?"symlink":"unknown"}))}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to list directory"}}};import rr from"fs/promises";import Du from"path";var Co=async t=>{try{let e=await Nt(t.source),s=$t(t.destination);await rr.mkdir(Du.dirname(s),{recursive:!0});try{await rr.rename(e,s)}catch(r){if(r.code!=="EXDEV")throw r;await rr.cp(e,s,{recursive:!0}),await rr.rm(e,{recursive:!0})}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to move file"}}};import ln from"fs/promises";var Eo=async t=>{try{let e=await Nt(t.path),s=await Ls(e);if(s.type==="binary"){let h=await ln.stat(e);if(h.size>We){let g=Math.round(h.size/1024/1024),p=Math.round(We/1024/1024);return{success:!1,error:`Binary file too large (${g}MB). Maximum size is ${p}MB.`}}let m=(await ln.readFile(e)).toString("base64");return{success:!0,type:"binary",mimeType:s.mimeType,content:m,size:h.size,encoding:"base64"}}let n=(await ln.readFile(e,"utf-8")).split(`
11
+ `),i=n.length,o=Math.max(1,t.start_line??1),a=Math.min(i,t.end_line??o+499),c=n.slice(o-1,a).join(`
12
+ `);return{success:!0,type:"text",content:ne(c),lines:{total:i,start:o,end:Math.min(a,i)},truncated:c.length>Gr}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to read file"}}};import un from"fs/promises";function Ro(t){if(t&&typeof t=="object"&&"code"in t)return String(t.code);let e=t instanceof Error?t.message:String(t);return/^([A-Z]+):/u.exec(e)?.[1]}function Ou(t){let e=Ro(t);return e==="EPERM"||e==="EACCES"}function cn(t){let e=t instanceof Error?t.message:String(t);switch(Ro(t)){case"EACCES":case"EPERM":return`${e}
13
+ Permission denied by the operating system. On macOS this is usually a privacy restriction \u2014 access can be granted under System Settings \u2192 Privacy & Security \u2192 Files and Folders (or Full Disk Access).`;case"ENOENT":return`${e}
14
+ The path does not exist.`;case"ENOTDIR":return`${e}
15
+ A component of the path is not a directory.`;case"EISDIR":return`${e}
16
+ The path is a directory, not a file.`;default:return e}}function Ao(t,e){return async s=>{let r=await t(s);return!r.success&&typeof r.error=="string"?(Ou(r.error)&&e?.(r.error),{...r,error:cn(r.error)}):r}}async function Lu(t){let e=await Nt(t),s=await Ls(e);if(s.type!=="binary")return ne(await un.readFile(e,"utf-8"),ri);let r=await un.stat(e);if(r.size>We){let i=Math.round(r.size/1024/1024),o=Math.round(We/1024/1024);return{error:`Binary file too large (${i}MB). Maximum size is ${o}MB.`}}let n=await un.readFile(e);return{type:"binary",mimeType:s.mimeType,content:n.toString("base64"),size:r.size,encoding:"base64"}}var Po=async t=>{try{let e=t.paths.slice(0,ii),s={};return await Promise.all(e.map(async r=>{try{s[r]=await Lu(r)}catch(n){let i=n instanceof Error?n.message:"Failed to read file";s[r]={error:cn(i)}}})),{success:!0,files:s}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to read files"}}};var _o=async t=>{try{let e=t.path?$t(t.path):process.cwd(),s=t.respect_gitignore??!0,r=await Ge(t.pattern,{cwd:e,nodir:!0,absolute:!0,maxDepth:ni});if(s){let n=await Ns(e);r=Bs(r,e,n)}return{success:!0,files:r.slice(0,Hr),total:r.length,truncated:r.length>Hr}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to search files"}}};import hn from"fs/promises";import Nu from"path";var Io=async t=>{try{let e=$t(t.path),s=Nu.dirname(e);if(await hn.mkdir(s,{recursive:!0}),t.encoding==="base64"){let r=Buffer.from(t.content,"base64");await hn.writeFile(e,r)}else if(!t.encoding||t.encoding==="utf-8")await hn.writeFile(e,t.content,"utf-8");else{let r=t.encoding;throw new Error(`Unsupported encoding: ${String(r)}`)}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to write file"}}};import Kp from"fs/promises";import Zp from"path";var $o={filesystem__read_file:Eo,filesystem__read_multiple_files:Po,filesystem__write_file:Io,filesystem__edit_file:ui,filesystem__create_directory:li,filesystem__list_directory:To,filesystem__search_files:_o,filesystem__grep_files:xo,filesystem__get_file_info:di,filesystem__move_file:Co,filesystem__execute_command:hi};function Fo(){return{name:"filesystem",systemPrompt:Wn({toolNames:$r.map(t=>t.name),env:{home:Wu.homedir(),cwd:process.cwd()}}),tools:[...$r]}}var Mo=!1;function Uu(){process.platform==="darwin"&&(Mo||process.stdout.isTTY&&(Mo=!0,Bu('open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"',()=>{})))}async function Do(t,e){let s=$o[t];if(!s)return{success:!1,error:`Unknown tool: ${t}`};let r=t==="filesystem__execute_command"&&!e.cwd?{...e,cwd:process.cwd()}:e,n=await Ao(s,Uu)(r);if(!n.success){let{success:a,error:l,...c}=n,h=Object.keys(c).length>0;return{success:!1,error:l,result:h?c:void 0}}let{success:i,...o}=n;return{success:!0,result:o}}function dn(t){return t.startsWith("filesystem__")}function Oo(){return[Fo()]}function nr(){return Oo().flatMap(t=>t.tools)}function ir(){return Oo().map(t=>t.systemPrompt).filter(Boolean).join(`
17
+
18
+ `)}function ps(t){return dn(t)}async function or(t,e){return dn(t)?Do(t,e):{success:!1,error:`Unknown client tool: ${t}`}}function ar(t){if(!t.success){let i=[{type:"text",text:t.error||"Unknown error"}];return t.result&&i.push({type:"text",text:JSON.stringify(t.result)}),i}let{payload:e,images:s,notes:r}=Un(t.result),n=[{type:"text",text:JSON.stringify(e)},...r.map(i=>({type:"text",text:i}))];for(let i of s)i.path&&n.push({type:"text",text:`File: ${i.path}`}),n.push({type:"image",data:i.data,mimeType:i.mimeType});return n}import{Box as dt,Text as W,useInput as xs}from"ink";import $n from"ink-spinner";import{useCallback as Mn,useEffect as Rr,useRef as Fn,useState as qa}from"react";import{Box as lr,Text as fs}from"ink";import{jsx as cr,jsxs as gs}from"react/jsx-runtime";function Lo(t,e){return t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function No({items:t,activeIndex:e,selectedIds:s,multiSelect:r=!1,visible:n,title:i,pageSize:o=10}){if(!n||t.length===0)return null;let a=process.stdout.columns??80,l=r?4:0,c=Math.max(20,a-2-2-l),h=Math.max(1,o),d=Math.floor(e/h)*h,m=Math.min(t.length,d+h),g=t.slice(d,m);return gs(lr,{flexDirection:"column",marginBottom:1,children:[cr(fs,{bold:!0,color:"cyan",children:i}),cr(lr,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:g.map((p,y)=>{let S=d+y===e,b=s?.has(p.id),R=Lo(p.name,c),_=p.description?Lo(p.description,Math.max(0,c-l)):"",A=r?" ".repeat(l):"";return gs(lr,{paddingX:1,flexDirection:"column",children:[gs(lr,{children:[r&&cr(fs,{color:b?"green":"gray",children:b?"[\u2713] ":"[ ] "}),cr(fs,{backgroundColor:S?"cyan":void 0,color:S?"black":b?"green":"white",bold:!0,children:R})]}),_&&gs(fs,{dimColor:!0,children:[A,"\xB7 ",_]})]},p.id)})}),gs(fs,{dimColor:!0,children:[r?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",t.length>h?` \xB7 Showing ${d+1}-${m} of ${t.length}`:""]})]})}import{Box as pn,Text as ms}from"ink";import{jsx as ws,jsxs as fn}from"react/jsx-runtime";function Bo({suggestions:t,activeIndex:e,visible:s}){return!s||t.length===0?null:fn(pn,{flexDirection:"column",marginBottom:1,children:[ws(pn,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:t.map((r,n)=>{let i=n===e,o=r.aliases.length>0?` (${r.aliases.join(", ")})`:"";return fn(pn,{paddingX:1,children:[fn(ms,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",r.name]}),ws(ms,{dimColor:!0,children:o}),ws(ms,{children:" - "}),ws(ms,{color:i?"white":"gray",children:r.description})]},r.name)})}),ws(ms,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as ju,Text as Wo,useInput as zu,useStdout as Gu}from"ink";import{useCallback as Uo,useEffect as jo,useMemo as gn,useRef as zo,useState as Go}from"react";import{jsx as yn}from"react/jsx-runtime";function ur(t,e){return t<0?0:t>e?e:t}function mn(t){return[...t]}function hr(t){return/\s/.test(t)}function wn(t,e){let s=e;for(;s>0&&hr(t[s-1]??"");)s-=1;for(;s>0&&!hr(t[s-1]??"");)s-=1;return s}function Ho(t,e){let s=e;for(;s<t.length&&hr(t[s]??"");)s+=1;for(;s<t.length&&!hr(t[s]??"");)s+=1;return s}function Hu(t){let e=[],s=[],r=[],n=0;s.push(0),t.forEach((o,a)=>{if(o===`
19
+ `){e.push(r),r=[],n=a+1,s.push(n);return}r.push(o)}),e.push(r);let i=e.map(o=>o.length);return{lines:e,lineStarts:s,lineLengths:i}}function qo(t,e,s){for(let n=0;n<e.length;n+=1){let i=e[n]??0,o=s[n]??0,a=i+o;if(t<=a)return{row:n,col:t-i}}let r=Math.max(0,e.length-1);return{row:r,col:s[r]??0}}var qu=2;function Xo({value:t,onChange:e,onSubmit:s,onPaste:r,focus:n=!0,leadingOffset:i=0,multiline:o=!1}){let[a,l]=Go(()=>mn(t).length),c=zo(null),[h,d]=Go(0),m=zo(null),{stdout:g}=Gu(),p=gn(()=>mn(t),[t]),{lines:y,lineStarts:v,lineLengths:S}=gn(()=>Hu(p),[p]),{row:b,col:R}=gn(()=>qo(a,v,S),[a,v,S]),_=Math.max(1,(g?.columns??80)-i);jo(()=>{c.current===t?l(L=>ur(L,p.length)):(l(p.length),m.current=null),c.current=t},[t,p.length]),jo(()=>{d(L=>{let I=L;R<I?I=R:R>=I+_&&(I=R-_+1);let f=S[b]??0,N=R===f?f+1:f,K=Math.max(0,N-_);return I>K&&(I=K),I<0&&(I=0),I})},[_,R,b,S]);let A=Uo((L,I)=>{c.current=L,e(L),l(I),m.current=null},[e]),G=Uo(async(L,I)=>{if(!n)return;let{row:f,col:N}=qo(a,v,S),K=y[f]??[],et=S[f]??0,H=y.length>1;if(o&&(I.meta&&I.return||I.ctrl&&L==="j"||I.shift&&I.return)){let k=[...p.slice(0,a),`
20
+ `,...p.slice(a)].join("");A(k,a+1);return}if(I.return){s(t);return}if(I.leftArrow){I.ctrl||I.meta?(N===0&&f>0?l(v[f]-1):l(v[f]+wn(K,N)),m.current=null):(N===0&&f>0?l(v[f]-1):l(k=>ur(k-1,p.length)),m.current=null);return}if(I.rightArrow){I.ctrl||I.meta?(N>=et&&f<y.length-1?l(v[f+1]):l(v[f]+Ho(K,N)),m.current=null):(N>=et&&f<y.length-1?l(v[f+1]):l(k=>ur(k+1,p.length)),m.current=null);return}if(o&&H&&I.upArrow){let k=m.current??N,q=Math.max(0,f-1),V=Math.min(k,S[q]??0);l((v[q]??0)+V),m.current=k;return}if(o&&H&&I.downArrow){let k=m.current??N,q=Math.min(y.length-1,f+1),V=Math.min(k,S[q]??0);l((v[q]??0)+V),m.current=k;return}if(I.ctrl){if(L==="a"){l(v[f]??0),m.current=null;return}if(L==="e"){l((v[f]??0)+et),m.current=null;return}if(L==="u"){if(N>0){let k=v[f]??0,q=[...p.slice(0,k),...p.slice(a)].join("");A(q,k)}return}if(L==="k"){if(N<et){let k=(v[f]??0)+et,q=[...p.slice(0,a),...p.slice(k)].join("");A(q,a)}return}if(L==="w"){if(N===0&&f>0){let q=[...p.slice(0,a-1),...p.slice(a)].join("");A(q,a-1);return}let k=wn(K,N);if(k!==N){let q=(v[f]??0)+k,V=[...p.slice(0,q),...p.slice(a)].join("");A(V,q)}return}if(L==="d"){if(a<p.length){let k=[...p.slice(0,a),...p.slice(a+1)].join("");A(k,a)}return}return}if(I.meta){L==="b"?(N===0&&f>0?l(v[f]-1):l(v[f]+wn(K,N)),m.current=null):L==="f"&&(N>=et&&f<y.length-1?l(v[f+1]):l(v[f]+Ho(K,N)),m.current=null);return}if(I.backspace||I.delete){if(a<=0)return;let k=[...p.slice(0,a-1),...p.slice(a)].join("");A(k,a-1);return}if(!(I.tab||I.escape)&&L.length>0){let k=o?L.replace(/\r\n/g,`
21
+ `).replace(/\r/g,`
22
+ `):L.replace(/\r?\n/g,"");if(!k||(k=k.replace(/^\u001B?\[200~/,"").replace(/\u001B?\[201~$/,""),!k))return;if((k.length>=qu||k.includes(`
23
+ `))&&r){let Pt=!1,ot={text:k,preventDefault:()=>{Pt=!0}};if(await Promise.resolve(r(ot)),Pt)return}let V=mn(k),Q=[...p.slice(0,a),...V,...p.slice(a)].join("");A(Q,a+V.length)}},[p,a,n,S,v,y,o,r,s,A,t]);return zu(G,{isActive:n}),yn(ju,{flexDirection:"column",children:y.map((L,I)=>{let f=I===b,K=(f&&R===L.length?[...L," "]:L).slice(h,h+_),et=K.join("");if(!f)return yn(Wo,{children:et||" "},I);let H=ur(R-h,Math.max(0,K.length-1)),k=K.slice(0,H).join(""),q=K[H]??" ",V=K.slice(H+1).join(""),ot=`${k}\x1B[7m${q}\x1B[27m${V}`;return yn(Wo,{children:ot},I)})})}import{Box as Kt,Text as ge}from"ink";import kn from"react";import{Text as jt}from"ink";import Xu from"react";import{Fragment as Ku,jsx as qt,jsxs as Ko}from"react/jsx-runtime";var bn=2,Sn=1,vn=2,Vu=1,Vo=3,Yo=4,Yu=({text:t,defaultColor:e,linkColor:s,codeColor:r})=>{let n=e;if(!/[*_~`<[https?:]/.test(t))return qt(jt,{color:n,children:t});let i=[],o=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(t))!==null;){l.index>o&&i.push(qt(jt,{color:n,children:t.slice(o,l.index)},`t-${o}`));let c=l[0],h=null,d=`m-${l.index}`;try{if(c.startsWith("**")&&c.endsWith("**")&&c.length>bn*2)h=qt(jt,{bold:!0,color:n,children:c.slice(bn,-bn)},d);else if(c.length>Sn*2&&(c.startsWith("*")&&c.endsWith("*")||c.startsWith("_")&&c.endsWith("_"))&&!/\w/.test(t.slice(Math.max(0,l.index-1),l.index))&&!/\w/.test(t.slice(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(t.slice(Math.max(0,l.index-2),l.index))&&!/[./\\]\S/.test(t.slice(a.lastIndex,a.lastIndex+2)))h=qt(jt,{italic:!0,color:n,children:c.slice(Sn,-Sn)},d);else if(c.startsWith("~~")&&c.endsWith("~~")&&c.length>vn*2)h=qt(jt,{strikethrough:!0,color:n,children:c.slice(vn,-vn)},d);else if(c.startsWith("`")&&c.endsWith("`")&&c.length>Vu){let m=c.match(/^(`+)(.+?)\1$/s);m&&m[2]&&(h=qt(jt,{color:r,children:m[2]},d))}else if(c.startsWith("[")&&c.includes("](")&&c.endsWith(")")){let m=c.match(/\[(.*?)\]\((.*?)\)/);if(m){let g=m[1],p=m[2];h=Ko(jt,{color:n,children:[g,Ko(jt,{color:s,children:[" (",p,")"]})]},d)}}else c.startsWith("<u>")&&c.endsWith("</u>")&&c.length>Vo+Yo-1?h=qt(jt,{underline:!0,color:n,children:c.slice(Vo,-Yo)},d):/^https?:\/\//.test(c)&&(h=qt(jt,{color:s,children:c},d))}catch{h=null}i.push(h??qt(jt,{color:n,children:c},d)),o=a.lastIndex}return o<t.length&&i.push(qt(jt,{color:n,children:t.slice(o)},`t-${o}`)),qt(Ku,{children:i.filter(c=>c!==null)})},ys=Xu.memo(Yu);import{Fragment as rh,jsx as nt,jsxs as ta}from"react/jsx-runtime";var Ju=1,Qo=1,Zu=1,Qu=1,th=({content:t})=>{let e=t.join(`
24
+ `);return nt(Kt,{paddingLeft:Qo,flexDirection:"column",children:nt(ge,{color:"yellow",children:e})})},Jo=kn.memo(th),eh=({itemText:t,type:e,marker:s,leadingWhitespace:r=""})=>{let n=e==="ol"?`${s}. `:`${s} `,i=n.length,o=r.length;return ta(Kt,{paddingLeft:o+Zu,flexDirection:"row",children:[nt(Kt,{width:i,children:nt(ge,{children:n})}),nt(Kt,{flexGrow:Qu,children:nt(ge,{wrap:"wrap",children:nt(ys,{text:t,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Zo=kn.memo(eh),sh=({text:t,renderMarkdown:e=!0})=>{if(!t)return null;if(!e)return nt(Kt,{paddingLeft:Qo,flexDirection:"column",children:nt(ge,{wrap:"wrap",children:t})});let s=t.split(/\r?\n/),r=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,o=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,c=[],h=!1,d=!0,m=[],g="";function p(y){y&&(c.push(y),d=!1)}return s.forEach((y,v)=>{let S=`line-${v}`;if(h){let I=y.match(n);I&&I[1].startsWith(g[0])&&I[1].length>=g.length?(p(nt(Jo,{content:m},S)),h=!1,m=[],g=""):m.push(y);return}let b=y.match(n),R=y.match(r),_=y.match(i),A=y.match(o),G=y.match(a),L=y.match(l);if(b)h=!0,g=b[1];else if(G)p(nt(Kt,{children:nt(ge,{dimColor:!0,children:"---"})},S));else if(R){let I=R[1].length,f=R[2],N=I<=2?"cyan":"blue";p(nt(Kt,{children:nt(ge,{color:N,...(I===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:nt(ys,{text:f,defaultColor:N,linkColor:"cyan",codeColor:"yellow"})})},S))}else if(L){let I=L[1];p(nt(Kt,{paddingLeft:1,children:ta(ge,{dimColor:!0,children:["> ",nt(ys,{text:I,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},S))}else if(_){let I=_[1],f=_[2],N=_[3];p(nt(Zo,{itemText:N,type:"ul",marker:f,leadingWhitespace:I},S))}else if(A){let I=A[1],f=A[2],N=A[3];p(nt(Zo,{itemText:N,type:"ol",marker:f,leadingWhitespace:I},S))}else y.trim().length===0?d||(c.push(nt(Kt,{height:Ju},`spacer-${v}`)),d=!0):p(nt(Kt,{children:nt(ge,{wrap:"wrap",children:nt(ys,{text:y,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},S))}),h&&p(nt(Jo,{content:m},"line-eof")),nt(rh,{children:c})},xn=kn.memo(sh);import{execFile as nh}from"child_process";import ih from"fs";import He from"fs/promises";import ea from"os";import pr from"path";import{promisify as oh}from"util";var dr=oh(nh);async function ah(){let t=pr.join(ea.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let e=`
25
+ set imageData to the clipboard as "PNGf"
26
+ set fileRef to open for access POSIX file "${t}" with write permission
27
+ set eof fileRef to 0
28
+ write imageData to fileRef
29
+ close access fileRef
30
+ `;return await dr("osascript",["-e",e]),(await He.stat(t)).size===0?void 0:{buffer:await He.readFile(t),mime:"image/png"}}catch{return}finally{try{ih.existsSync(t)&&await He.unlink(t)}catch{}}}async function lh(){try{let t=`
31
+ Add-Type -AssemblyName System.Windows.Forms
32
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
33
+ if ($img) {
34
+ $ms = New-Object System.IO.MemoryStream
35
+ $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
36
+ [System.Convert]::ToBase64String($ms.ToArray())
37
+ }
38
+ `,{stdout:e}=await dr("powershell.exe",["-command",t]),s=e.trim();if(!s)return;let r=Buffer.from(s,"base64");return r.length===0?void 0:{buffer:r,mime:"image/png"}}catch{return}}async function ch(){try{let{stdout:t}=await dr("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(t&&t.length>0)return{buffer:t,mime:"image/png"}}catch{}try{let{stdout:t}=await dr("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(t&&t.length>0)return{buffer:t,mime:"image/png"}}catch{}}async function sa(){let t=ea.platform();if(t==="darwin")return ah();if(t==="win32")return lh();if(t==="linux")return ch()}var uh=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function ra(t){let e=pr.extname(t).toLowerCase();return uh.has(e)}function hh(t){let e=pr.extname(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[e]||"application/octet-stream"}function fr(t){let e=t.trim();return e.startsWith("file://")&&(e=decodeURIComponent(e.slice(7))),(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))&&(e=e.slice(1,-1)),e=e.replace(/\\(.)/g,"$1"),e}async function na(t){let e=fr(t);if(/^https?:\/\//.test(e))return!1;try{return await He.access(e),!0}catch{return!1}}async function ia(t){let e=fr(t);try{if(!(await He.stat(e)).isFile())return;let r=await He.readFile(e),n=hh(e),i=pr.basename(e);return{buffer:r,mimeType:n,filename:i}}catch{return}}var me="\x1B[2m",tt="\x1B[0m",Et="\x1B[36m",Tn="\x1B[32m",oa="\x1B[31m",Re="\x1B[38;2;59;91;204m",Cn="\x1B[38;2;126;200;248m",En="\x1B[38;2;244;196;78m";function aa(t){return{requests:t,index:0,decisions:new Map}}function la(t,e){let{requests:s,index:r,decisions:n}=t;if(e==="approveAll"||e==="rejectAll"){let a=e==="approveAll";return{submit:new Map(s.map(l=>[l.approvalId,a]))}}if(e==="undo"){if(r===0)return{state:t};let a=s[r-1],l=new Map(n);return l.delete(a.approvalId),{state:{requests:s,index:r-1,decisions:l,lastUndoneToolName:a.toolName}}}let i=s[r],o=new Map([...n,[i.approvalId,e==="approve"]]);return r===s.length-1?{submit:o}:{state:{requests:s,index:r+1,decisions:o}}}function qe(t){return t.replace(/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/gu,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/gu,"").replace(/[\u0000-\u001F\u007F-\u009F]/gu,"")}function gr({agentId:t,agentDetails:e,activeConnectorIds:s,availableConnectors:r}){if(t)return e?e.connectors?.length?e.connectors.map(i=>i.name).join(", "):"none":"loading\u2026";if(!s?.length)return"all";let n=r.filter(i=>s.includes(i.id)).map(i=>i.name);return n.length>0?n.join(", "):`${s.length} connector(s)`}import{useCallback as ca,useRef as ua,useState as dh}from"react";function ph(t,e){switch(t){case"y":return"approve";case"n":return"reject";case"u":return e?"undo":void 0;case"a":return e?"approveAll":void 0;case"r":return e?"rejectAll":void 0;default:return}}function ha(){let[t,e]=dh(null),s=ua(null),r=ua(null),n=ca(o=>{let a=aa(o);return s.current=a,e(a),new Promise(l=>{r.current=l})},[]),i=ca(o=>{let a=s.current;if(!a)return;let l=ph(o.toLowerCase(),a.requests.length>1);if(!l)return;let c=la(a,l),h=c.submit?null:c.state??null;s.current=h,e(h),c.submit&&(r.current?.(c.submit),r.current=null)},[]);return{approvalRound:t,handleApprovalRequest:n,handleApprovalKey:i}}import{useState as ae}from"react";import{v4 as da}from"uuid";function pa(t,e){let[s,r]=ae({status:"loading"}),[n,i]=ae([]),[o,a]=ae(""),[l,c]=ae(()=>t||da()),[h,d]=ae(e),[m,g]=ae(!!t),[p,y]=ae(null),[v,S]=ae(""),[b,R]=ae(!1),_=G=>{i(L=>[...L,{role:"system",content:G}])};return{state:s,setState:r,messages:n,setMessages:i,input:o,setInput:a,taskId:l,setTaskId:c,currentTaskTitle:h,setCurrentTaskTitle:d,hasPersistedTask:m,setHasPersistedTask:g,credentials:p,setCredentials:y,currentResponse:v,setCurrentResponse:S,fullOutput:b,setFullOutput:R,addSystemMessage:_,startNewTask:G=>{let L=da();c(L),d(void 0),g(!1),i([]),G&&_(G)}}}import{useEffect as fh,useState as fa}from"react";function ga(t){let[e,s]=fa(null),[r,n]=fa(!0);return fh(()=>{let i=!1;async function o(){try{let a=await zt();if(i)return;s({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof xe){if(a.code==="not-logged-in"){t({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){t({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Authentication failed";t({status:"error",message:l}),n(!1)}}return o(),()=>{i=!0}},[t]),{credentials:e,loading:r}}import{useEffect as gh,useState as bs}from"react";function ma(t){let[e,s]=bs([]),[r,n]=bs([]),[i,o]=bs([]),[a,l]=bs([]),[c,h]=bs(!1);return gh(()=>{if(!t)return;let d=!1;h(!0);async function m(){if(t)try{let g=new lt,[p,y,v,S]=await Promise.all([g.getConnectors(t.accessToken,t.workspaceId),g.listSelectableModels(t.accessToken,t.workspaceId),g.getAgents(t.accessToken,t.workspaceId),g.getModelProviders(t.accessToken,t.workspaceId)]);if(d)return;s(p.connectors),n(y.models),o(v.agents),l(S.providers??[])}catch{}finally{d||h(!1)}}return m(),()=>{d=!0}},[t]),{availableConnectors:e,availableModels:r,availableAgents:i,modelProviders:a,loading:c}}import{useChat as Uh}from"@ai-sdk/react";import{getToolName as _n,isToolUIPart as jh}from"ai";import{useCallback as ye,useEffect as Jt,useRef as Rt,useState as Er}from"react";import{v4 as zh}from"uuid";import{isTextUIPart as mh}from"ai";function wh(t){return typeof t=="object"&&t!==null}function Xe(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return null}if(!wh(e))return null;let{id:s,role:r,parts:n}=e;return typeof s!="string"||r!=="assistant"||!Array.isArray(n)?null:{id:s,role:r,parts:n}}function wa(){let t=new Set;return{noteMessageId:e=>{e&&t.add(e)},shouldRender:e=>{let s=Xe(e);return s?t.has(s.id)?!1:(t.add(s.id),!0):!0}}}function Rn(t){let e=Xe(t);return e?e.parts.filter(mh).map(s=>s.text).join(""):""}var ya="data: ";async function yh({response:t,onEvent:e,signal:s}){if(s.aborted||!t.body)return;let r=t.body.pipeThrough(new TextDecoderStream).getReader(),n=()=>{r.cancel().catch(()=>{})};s.addEventListener("abort",n,{once:!0});let i="";try{for(;!s.aborted;){let{done:o,value:a}=await r.read();if(o)return;i+=a;let l=i.indexOf(`
39
+
40
+ `);for(;l!==-1;){let c=i.slice(0,l);i=i.slice(l+2);for(let h of c.split(`
41
+ `))h.startsWith(ya)&&e(h.slice(ya.length));l=i.indexOf(`
42
+
43
+ `)}}}finally{s.removeEventListener("abort",n)}}function bh(t){return Math.min(3e4,500*2**Math.min(t,6))}function Sh(t,e){return new Promise(s=>{let r,n=()=>{clearTimeout(r),e.removeEventListener("abort",n),s()};r=setTimeout(n,t),e.addEventListener("abort",n,{once:!0})})}function mr({open:t,onEvent:e,backoffMs:s=bh}){let r=new AbortController;return(async()=>{let i=0;for(;!r.signal.aborted;){try{let o=await t(r.signal);if(r.signal.aborted){o.body?.cancel().catch(()=>{});return}let a=!1;await yh({response:o,onEvent:l=>{a=!0,e(l)},signal:r.signal}),i=a?0:i+1}catch{i+=1}if(r.signal.aborted)return;await Sh(s(i),r.signal)}})(),{dispose:()=>r.abort()}}var wr={status:"queued",activity:void 0,steps:[],stepCount:0};function vh(t){return"data"in t}function ba(t,e){switch(e.type){case"snapshot":{let s=e.data.progress;return{...t,status:e.data.status,activity:s?.activity??t.activity,steps:s?.steps??t.steps,stepCount:s?.stepCount??t.stepCount,usage:s?.usage??t.usage}}case"data-subagent-activity":return{...t,status:t.status==="queued"?"running":t.status,activity:{activity:e.activity,...e.toolName===void 0?{}:{toolName:e.toolName},...e.toolTitle===void 0?{}:{toolTitle:e.toolTitle}}};case"data-subagent-step":{let s=[...t.steps,{stepIndex:e.stepIndex,toolCallCount:e.toolCallCount,reasoningTokens:e.reasoningTokens,...e.toolCalls===void 0?{}:{toolCalls:e.toolCalls}}];return{...t,status:t.status==="queued"?"running":t.status,steps:s,stepCount:s.length,usage:e.usage}}case"data-subagent-done":return vh(e)?{...t,status:e.data.status}:{...t,status:e.status==="success"?"completed":"failed",...e.error===void 0?{}:{doneError:e.error}};default:return t}}var kh=2e3;function xh(t){if(typeof t!="object"||t===null)return;let{type:e,data:s}=t;if(e!=="data-subagent-start"||typeof s!="object"||s===null)return;let r=s;if(!(typeof r.runId!="string"||typeof r.toolCallId!="string"))return r}function yr({openRunEvents:t,getRun:e,pollIntervalMs:s=kh}){let r=new Map,n=new Map,i=new Set,o=new Set,a={runs:[],activeCount:0},l=!1,c=g=>(i.add(g),()=>i.delete(g)),h=()=>{let g=[...r.values()];a={runs:g,activeCount:g.filter(p=>!se(p.stream.status)).length};for(let p of i)p()},d=(g,p)=>{if(l)return;let y=r.get(g);y&&(r.set(g,{...y,stream:p}),se(p.status)&&n.get(g)?.(),h())},m=g=>{let p=mr({open:b=>t(g,b),onEvent:b=>{let R;try{R=JSON.parse(b)}catch{return}let _=r.get(g)?.stream??wr;d(g,ba(_,R))}}),y=new AbortController,v,S=()=>{v=setTimeout(()=>{e(g,y.signal).then(b=>{let R=r.get(g)?.stream??wr;se(R.status)||!se(b.status)&&R.steps.length>0||d(g,{...R,status:b.status,steps:b.progress?.steps??R.steps,stepCount:b.progress?.stepCount??R.stepCount,activity:b.progress?.activity??R.activity,...b.progress?.usage?{usage:b.progress.usage}:{}})}).catch(()=>{}).finally(()=>{y.signal.aborted||S()})},s)};S(),n.set(g,()=>{p.dispose(),y.abort(),clearTimeout(v)})};return{ingestChunk:g=>{if(l)return;let p=xh(g);!p||r.has(p.runId)||(r.set(p.runId,{runId:p.runId,toolCallId:p.toolCallId,description:p.description,stream:wr}),m(p.runId),h())},getSnapshot:()=>a,subscribe:c,waitForNoActiveRuns:({timeoutMs:g})=>new Promise(p=>{if(a.activeCount===0){p(!0);return}if(l){p(!1);return}let y,v,S=b=>{clearTimeout(y),v(),o.delete(S),p(b)};y=setTimeout(()=>S(!1),g),v=c(()=>{a.activeCount===0&&S(!0)}),o.add(S)}),dispose:()=>{l=!0;for(let g of n.values())g();n.clear();for(let g of o)g(!1);i.clear()}}}function br({agentId:t,model:e,connectorIds:s,clientTools:r,clientToolSystemPrompt:n,toolApprovalMode:i}){return{...t?{agentId:t}:{...e?{model:e}:{},...s?.length?{connectorIds:s}:{}},...r?{clientTools:r}:{},...n?{clientToolSystemPrompt:n}:{},...i?{toolApprovalMode:i}:{}}}import{DefaultChatTransport as Th,isToolUIPart as Ch}from"ai";import Ss from"fs";import Sa from"path";var vs=Sa.join(zn(),"stream-debug.log");function va(){try{Ss.existsSync(vs)&&Ss.unlinkSync(vs),process.env.DEBUG&&(Ss.mkdirSync(Sa.dirname(vs),{recursive:!0}),Ss.writeFileSync(vs,`=== Debug session started at ${new Date().toISOString()} ===
44
+ `))}catch{}}function An(t,e){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${t}`;e!==void 0&&(s+=`
45
+ DATA: ${JSON.stringify(e,null,2)}`);try{Ss.appendFileSync(vs,s+`
46
+ `)}catch{}}function ka(t,e,s){let r=!!process.env.DEBUG;return!r&&!e&&!s?t:t.pipeThrough(new TransformStream({transform(n,i){r&&An(`SSE chunk: ${n.type}`,n),e?.(n),i.enqueue(n)},flush(){s?.()}}))}var Ve=class extends Th{resolveCredentials;resolveTaskConfig;sendTask;resumeTask;resumeSignal;onToolPartsSubmitted;onChunk;onStreamEnd;constructor(e){super(),this.resolveCredentials=e.resolveCredentials,this.resolveTaskConfig=e.resolveTaskConfig,this.sendTask=e.sendTask,this.resumeTask=e.resumeTask,this.resumeSignal=e.resumeSignal,this.onToolPartsSubmitted=e.onToolPartsSubmitted,this.onChunk=e.onChunk,this.onStreamEnd=e.onStreamEnd}async sendMessages(e){let s=await this.resolveCredentials(),r=jn(e.messages.at(-1)),n=r&&r.role!=="system"?{id:r.id,role:r.role,parts:r.parts}:void 0;n?.role!=="assistant"&&va(),An("=== Sending task request ===",{taskId:e.chatId,messageRole:n?.role,partCount:n?.parts.length});let i=await this.sendTask(s,{...this.resolveTaskConfig(),...e.body,id:e.chatId,message:n});if(r?.role==="assistant"&&this.onToolPartsSubmitted?.(r.parts.filter(Ch).map(o=>o.toolCallId)),!i.body)throw new Error("Task stream response has no body.");return Mr(ka(this.processResponseStream(i.body),this.onChunk,this.onStreamEnd),e.abortSignal)}async reconnectToStream(e){if(!this.resumeTask)return null;let s=this.resumeSignal?.(),r=await this.resolveCredentials(),n=await this.resumeTask(r,e.chatId);return n.body?Mr(ka(this.processResponseStream(n.body),this.onChunk,this.onStreamEnd),s):null}};function Eh({getStatus:t,resumeStream:e}){let s=!1,r=!1,n=!1,i=()=>{if(n)return;let o=t();o!=="ready"&&o!=="error"||!s||r||(s=!1,r=!0,e().then(()=>{r=!1,i()},()=>{s=!0,r=!1}))};return{notifyWake:()=>{n||(s=!0,i())},notifyStatusChange:i,dispose:()=>{n=!0,s=!1}}}function Rh(t,e){let s;try{s=JSON.parse(t)}catch{return!1}return s.type==="wake"&&s.taskId===e}function Ah({open:t,taskId:e,onWake:s}){return mr({open:t,onEvent:r=>{Rh(r,e)&&s()}})}var Ph=3;function _h(t){if(t.type==="start")return t.messageId??null;if(t.type==="data-appendMessage")return Xe(t.data)?.id}function Sr({taskId:t,getStatus:e,resumeStream:s,isKnownMessage:r,openWakeEvents:n,onWake:i,onResumeTurn:o,onResumeSettled:a}){let l=new AbortController,c=!1,h=!1,d=!1,m=0,g=Promise.resolve(),p=Eh({getStatus:e,resumeStream:()=>{c=!0,h=!1,d=!1;let S=s().then(()=>{c=!1;let b=d;if(a?.({delivered:h&&!b,failed:b}),!b){m=0;return}m+=1,m<=Ph&&p.notifyWake()});return g=S.then(()=>{},()=>{}),S}}),y=()=>{m=0,p.notifyWake()},v=n?Ah({open:n,taskId:t,onWake:()=>{y(),i?.()}}):void 0;return{notifyWake:y,notifyStatusChange:p.notifyStatusChange,notifyChunk:S=>{if(!c||h)return;let b=_h(S);b!==void 0&&(b!==null&&r(b)||(h=!0,o?.()))},notifyError:()=>{c&&(d=!0)},whenResumeSettled:()=>g,resumeSignal:l.signal,dispose:()=>{v?.dispose(),p.dispose(),l.abort()}}}function xa(t,e){if(!t)return"(no result)";if(typeof t!="object"){let n=String(t);return e||n.length<=200?n:n.slice(0,200)+"\u2026"}let s=t;if("structuredContent"in s&&s.structuredContent){let n=s.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return e||i.length<=200?i:i.slice(0,200)+"\u2026"}}if("content"in s&&Array.isArray(s.content)){let n=s.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
47
+ `);return n?e||n.length<=200?n:n.slice(0,200)+"\u2026":"(result)"}if(s.type==="text"&&typeof s.content=="string"){let n=s.content;return e||n.length<=200?n:n.slice(0,200)+"\u2026"}let r=JSON.stringify(t,null,e?2:void 0);return e||r.length<=200?r:r.slice(0,200)+"\u2026"}function we(t,e=!1){let s=[];for(let r of t)if(r.type==="text"&&r.text)s.push(r.text);else if(r.type==="reasoning"&&r.text)e?s.push(`${me}[Thinking]
48
+ ${r.text}${tt}`):s.push(`${me}[Thinking\u2026]${tt}`);else if(r.type==="tool-call"&&r.toolName){let n=[`${Et}\u250C\u2500 Tool: ${r.toolName}${tt}`];if(r.args){let i=JSON.stringify(r.args,null,e?2:void 0),o=e||i.length<=100?i:i.slice(0,100)+"\u2026";n.push(`${me}\u2502 Input: ${o}${tt}`)}r.result===void 0?n.push(`${Et}\u2514\u2500${tt}`):(n.push(`${Tn}\u2502 Output: ${xa(r.result,e)}${tt}`),n.push(`${Et}\u2514\u2500 completed${tt}`)),s.push(n.join(`
49
+ `))}else if(r.type.startsWith("tool-")&&r.type!=="tool-call"){let n=r.title||r.type.slice(5).replace(/__/g," "),i=[`${Et}\u250C\u2500 Tool: ${n}${tt}`];if(r.input){let o=JSON.stringify(r.input,null,e?2:void 0),a=e||o.length<=100?o:o.slice(0,100)+"\u2026";i.push(`${me}\u2502 Input: ${a}${tt}`)}r.output!==void 0&&r.state==="output-available"?(i.push(`${Tn}\u2502 Output: ${xa(r.output,e)}${tt}`),i.push(`${Et}\u2514\u2500 completed${tt}`)):r.state==="error"?i.push(`${Et}\u2514\u2500 failed${tt}`):i.push(`${Et}\u2514\u2500${tt}`),s.push(i.join(`
50
+ `))}return s.join(`
51
+
52
+ `).trim()}import{getToolName as Tr,isReasoningUIPart as Pa,isTextUIPart as _a,isToolUIPart as Ia}from"ai";var Ih=new Set(["data-subagent-activity","data-subagent-step","data-subagent-done"]);function $h(t){return t.type!==void 0&&Ih.has(t.type)}function Mh(t,e){let s=t.data;if(!(typeof s!="object"||s===null))return s.toolCallId===e?s:void 0}function Ta(t,e){let s=[],r,n;for(let i of t){let o=Mh(i,e);o&&(i.type==="data-subagent-step"&&s.push(o),i.type==="data-subagent-activity"&&(r=o),i.type==="data-subagent-done"&&(n=o))}return{activity:r,steps:s,latestStep:s.at(-1),done:n}}function Ca(t,e){return`${t} ${e}${t===1?"":"s"}`}function vr(t){return t>0?[Ca(t,"tool call")]:[]}function kr(t){return t>=999500?`${(t/1e6).toFixed(1)}M tokens`:t>=1e3?`${(t/1e3).toFixed(1)}k tokens`:`${t} tokens`}function Fh(t){let e=Math.round(t/1e3);if(e<60)return`${e}s`;let s=Math.floor(e/60),r=e%60;return`${s}m ${r}s`}function Ea(t){return[Ca(t.stepCount,"step"),...vr(t.totalToolCalls),kr(t.usage.totalTokens),...t.durationMs===void 0?[]:[Fh(t.durationMs)]]}function Ra(t,e){let{activity:s,latestStep:r,done:n}=t;if(n)return n.status==="error"?`failed \xB7 ${n.error??"no detail"}`:["completed",...Ea(n)].join(" \xB7 ");let i=t.steps.length>0?Dr(t.steps):0,o=[...s?[s.activity]:[],...vr(i),...r?[kr(r.usage.totalTokens)]:[]];return o.length===0?"":[...o,...e===void 0?[]:[`${e}s`]].join(" \xB7 ")}function xr(t,e){if(t.status==="failed")return`failed \xB7 ${t.doneError??"no detail"}`;let s=[...vr(Dr(t.steps)),...t.usage?[kr(t.usage.totalTokens)]:[],...e===void 0?[]:[`${e}s`]];return[se(t.status)?t.status:t.activity?.activity??t.status,...s].join(" \xB7 ")}function Dh(t,e){return e?.trim()||t.split(Ms).join(" ")}function Oh(t){return t.activity==="tool-calling"&&t.toolName?`Calling ${Dh(t.toolName,t.toolTitle)}`:t.activity}function Lh(t,e){if(t.type==="data-subagent-activity")return Oh(e);if(t.type==="data-subagent-step"){let r=e;return[`step ${r.stepIndex+1}`,...vr(r.toolCallCount),kr(r.usage.totalTokens)].join(" \xB7 ")}let s=e;return s.status==="error"?`failed \xB7 ${s.error??"no detail"}`:["completed",...Ea(s)].join(" \xB7 ")}function Aa(t,e){if(!$h(t))return;let s=t.data;if(typeof s!="object"||s===null)return;let r=Lh(t,s),n=s.toolCallId,i=typeof n=="string"?n:"";if(e.get(i)!==r)return e.set(i,r),`sub-agent: ${r}`}function Nh(t,e){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Bh(t){return t.split(Ms).join(" ")}function Pn(t){let e=[];for(let s of t.parts){if(_a(s)){s.text&&e.push({type:"text",text:s.text});continue}if(Pa(s)){s.text&&e.push({type:"reasoning",text:s.text});continue}Ia(s)&&e.push({type:`tool-${Tr(s)}`,input:s.input,output:s.state==="output-error"?s.errorText:s.output,state:s.state==="output-error"?"error":s.state})}return e}function $a(t,e){if(t?.role!=="assistant")return"";let s=t.parts,r=[];for(let n of t.parts){if(_a(n)){n.text&&r.push(n.text);continue}if(Pa(n)){n.state==="streaming"&&n.text&&r.push(`${me}[Thinking\u2026]${tt}
53
+ ${n.text}`);continue}if(!Ia(n))continue;let i=Tr(n)===Fr.SPAWN?e.backgroundRuns?.runs.find(a=>a.toolCallId===n.toolCallId):void 0;if(!i&&(n.state==="output-available"||n.state==="output-error")){r.push(we(Pn({parts:[n]})));continue}let o=[`${Et}\u250C\u2500 Tool: ${Bh(Tr(n))}${tt}`];if(n.input!==void 0&&o.push(`${me}\u2502 Input: ${Nh(qe(JSON.stringify(n.input)),100)}${tt}`),i){let a=e.startTimes.get(n.toolCallId)??e.now;e.startTimes.set(n.toolCallId,a);let l=Math.floor((e.now-a)/1e3);o.push(`${Et}\u2502${tt} (${xr(i.stream,l)})`)}else if(n.state==="input-streaming")o.push(`${Et}\u2502${tt} (preparing\u2026)`);else if(n.state==="approval-requested")o.push(`${Et}\u2502${tt} (awaiting approval\u2026)`);else if(n.state==="approval-responded"&&!n.approval.approved)o.push(`${oa}\u2502 rejected${tt}`);else{let a=e.startTimes.get(n.toolCallId)??e.now;e.startTimes.set(n.toolCallId,a);let l=Math.floor((e.now-a)/1e3),c=Tr(n)===Fr.SPAWN?Ra(Ta(s,n.toolCallId),l):"";o.push(c?`${Et}\u2502${tt} (${c})`:`${Et}\u2502${tt} (executing\u2026 ${l}s)`)}r.push(o.join(`
54
+ `))}return r.join(`
55
+
56
+ `)}import{useSyncExternalStore as Wh}from"react";function Cr(t){return Wh(t.subscribe,t.getSnapshot)}async function Gh(t,e,s,r,n){let i=new Map;if(e)try{let{messages:o}=await n.getMessages(e.accessToken,e.workspaceId,s,t.length+2);i=new Map(o.map(a=>[a.id,a.parts]))}catch{}return t.map(o=>{let a=i.get(o.id)??Pn(o);return{role:"assistant",content:we(a,r),parts:a}})}function Ma(t){let{taskId:e,setMessages:s,setState:r,setCurrentResponse:n,hasPersistedTask:i,setHasPersistedTask:o}=t,a=Rt(t);a.current=t;let l=Rt(new Set),c=Rt(new Set),h=Rt(new Set),d=Rt(new Set),m=Rt(new Map),g=Rt(null),p=Rt(null),y=Rt(Promise.resolve());Jt(()=>{l.current=new Set,c.current=new Set,h.current=new Set,d.current=new Set,m.current=new Map},[e]);let[v,S]=Er(!1),b=Rt(v);b.current=v;let R=Rt(null),_=ye(O=>a.current.localTools&&ps(_n(O)),[]),A=Rt(null),[{transport:G,apiClient:L}]=Er(()=>{let O=new lt;return{apiClient:O,transport:new Ve({resolveCredentials:async()=>{let P=await zt(),M=a.current.credentials;if(!M)return a.current.setCredentials(P),P;let U={accessToken:P.accessToken,workspaceId:M.workspaceId};return P.accessToken!==M.accessToken&&a.current.setCredentials(U),U},resolveTaskConfig:()=>{let P=a.current;return br({agentId:P.currentAgentId,model:P.currentModel,connectorIds:P.activeConnectorIds,clientTools:P.localTools?nr():void 0,clientToolSystemPrompt:P.localTools?ir():void 0,toolApprovalMode:P.toolApprovalMode})},sendTask:(P,M)=>O.task(P.accessToken,P.workspaceId,M),resumeTask:(P,M)=>O.resumeTaskStream(P.accessToken,P.workspaceId,M),onToolPartsSubmitted:P=>{for(let M of P)d.current.add(M)},onChunk:P=>{g.current?.notifyChunk(P),A.current?.ingestChunk(P)},resumeSignal:()=>g.current?.resumeSignal})}}),I=ye(()=>yr({openRunEvents:async(O,P)=>{let M=await zt();return L.openSubagentRunEvents(M.accessToken,M.workspaceId,O,P)},getRun:async(O,P)=>{let M=await zt();return L.getSubagentRun(M.accessToken,M.workspaceId,O,P)}}),[L]),[f,N]=Er(I),K=Rt(e);A.current=f,Jt(()=>{K.current!==e&&(K.current=e,N(I()))},[e,I]),Jt(()=>()=>f.dispose(),[f]);let et=Cr(f),H=Uh({id:e,transport:G,generateId:zh,experimental_throttle:100,sendAutomaticallyWhen:O=>Je({messages:O.messages,isClientTool:_,submittedToolCallIds:d.current}),onData:O=>{if(O.type!=="data-appendMessage")return;let P=Xe(O.data);P&&R.current?.(M=>{let U=M.findIndex(T=>T.id===P.id);return U===-1?[...M,P]:M.with(U,P)})},onError:O=>{if(g.current?.notifyError(),S(!1),O instanceof xe&&O.code==="not-logged-in"){a.current.setState({status:"not-logged-in"});return}if(O instanceof xe&&O.code==="no-workspace"){a.current.setState({status:"no-workspace"});return}a.current.setState({status:"error",message:O.message||"Failed to send message"})}}),k=Rt(H);k.current=H,R.current=H.setMessages;let q=Rt(!1);Jt(()=>{(H.status==="submitted"||H.status==="streaming")&&(q.current=!0)},[H.status]),Jt(()=>{S(!1),q.current=!1},[e]);let V=ye(O=>{let P=()=>a.current.taskId===O;return Sr({taskId:O,getStatus:()=>b.current?"streaming":k.current.status,resumeStream:async()=>{if(P()&&(await y.current,!!P()))return q.current=!1,k.current.resumeStream()},isKnownMessage:M=>h.current.has(M)||k.current.messages.some(U=>U.id===M),openWakeEvents:async M=>{let U=await zt();return L.openWakeEvents(U.accessToken,U.workspaceId,O,M)},onResumeTurn:()=>{P()&&(r({status:"sending"}),n(""),S(!0))}})},[L,n,r]);Jt(()=>{if(!i)return;let O=p.current;p.current=null,y.current=O?O.then(M=>{for(let U of M)h.current.add(U)}).catch(()=>{}):Promise.resolve();let P=V(e);return g.current=P,P.notifyWake(),()=>{g.current===P&&(g.current=null),P.dispose()}},[i,e,V]),Jt(()=>{g.current?.notifyStatusChange()},[H.status,v]);let Q=H.messages.some(O=>O.role==="assistant"&&!h.current.has(O.id)&&O.parts.some(P=>jh(P)&&(P.state==="input-available"||P.state==="approval-responded"&&P.approval.approved))),[Pt,ot]=Er(0);Jt(()=>{if(!v||!Q)return;let O=setInterval(()=>ot(P=>P+1),1e3);return()=>clearInterval(O)},[v,Q]),Jt(()=>{if(!v)return;let O=H.messages.filter(U=>U.role==="assistant"&&!h.current.has(U.id));if(O.length===0)return;let P=Date.now(),M=O.map(U=>$a(U,{now:P,startTimes:m.current,backgroundRuns:et})).filter(Boolean).join(`
57
+
58
+ `);n(M)},[H.messages,Pt,v,n,et]);let yt=ye(O=>{S(!1),a.current.setState({status:"error",message:O instanceof Error?O.message:String(O)})},[]),ft=ye(async O=>{let{onApprovalRequest:P}=a.current,M=P?await P(O):new Map;for(let U of O){let T=M.get(U.approvalId)===!0;await k.current.addToolApprovalResponse({id:U.approvalId,approved:T,...T?{}:{reason:"Rejected by user."}})}},[]),kt=ye(async(O,P)=>{let M;try{M=await or(O,P.input??{})}catch(U){await k.current.addToolOutput({tool:O,toolCallId:P.toolCallId,state:"output-error",errorText:U instanceof Error?U.message:String(U)});return}await k.current.addToolOutput({tool:O,toolCallId:P.toolCallId,state:"output-available",output:{content:ar(M),isError:!M.success}})},[]);Jt(()=>{if(!v||H.status!=="ready"||!q.current)return;let O=H.messages.at(-1);if(O?.role!=="assistant")return;let P=$s(O),M=[];for(let F of P)F.state==="approval-requested"&&(c.current.has(F.approval.id)||(c.current.add(F.approval.id),M.push({approvalId:F.approval.id,toolCallId:F.toolCallId,toolName:_n(F),input:F.input??{}})));M.length>0&&ft(M).catch(yt);for(let F of P){if(!_(F))continue;let Y=F.state==="approval-responded"&&!F.approval.approved,Ot=F.state==="input-available"||F.state==="approval-responded"&&F.approval.approved;if(!Y&&!Ot||l.current.has(F.toolCallId))continue;l.current.add(F.toolCallId);let _t=_n(F);if(Y){Promise.resolve(k.current.addToolOutput({tool:_t,toolCallId:F.toolCallId,state:"output-error",errorText:"Tool execution rejected by user."})).catch(yt);continue}kt(_t,F).catch(yt)}let U=P.some(F=>F.state==="approval-requested"),T=P.some(F=>_(F)&&(F.state==="input-available"||F.state==="approval-responded"));if(U||T||Je({messages:H.messages,isClientTool:_,submittedToolCallIds:d.current}))return;S(!1),q.current=!1;let D=H.messages.filter(F=>F.role==="assistant"&&!h.current.has(F.id));for(let F of D)h.current.add(F.id);(async()=>{if(D.length>0){let F=await Gh(D,a.current.credentials,a.current.taskId,a.current.fullOutput,L);s(Y=>[...Y,...F])}n(""),r({status:"ready"}),o(!0)})().catch(yt)},[H.messages,H.status,v,_,ft,kt,yt,L,s,n,r,o]);let bt=ye(async O=>{s(M=>[...M,{role:"user",content:O}]),r({status:"sending"}),n(""),q.current=!1,S(!0);let P=a.current.getFileIds?.()??[];(async()=>{await g.current?.whenResumeSettled(),await k.current.sendMessage({text:O},P.length>0?{body:{fileIds:P}}:void 0),P.length>0&&a.current.clearFiles?.()})().catch(yt)},[s,r,n,yt]),Dt=ye(O=>{p.current=O},[]);return{sendMessage:bt,backgroundRuns:f,noteTranscriptLoad:Dt}}import{useState as Hh}from"react";var Fa=new Map([["sandbox","Sandbox"],["web_search","Web Search"],["image_generation","Image Generation"],["chart","Chart"],["file_system","FileSystem"]]);function Da(t){let[e,s]=Hh(t);return{fileSystem:e,setFileSystem:s,capabilityLabelMap:Fa}}import{useEffect as qh,useState as Xh}from"react";function Oa(t,e){let[s,r]=Xh(null);return qh(()=>{let n=!1;async function i(){if(!t||!e){r(null);return}try{let a=await new lt().getAgent(e.accessToken,e.workspaceId,t);n||r(a)}catch{n||r(null)}}return i(),()=>{n=!0}},[t,e]),{currentAgentDetails:s}}import{useState as In}from"react";function La(t,e,s){let[r,n]=In(t),[i,o]=In(e),[a,l]=In(s);return{currentModel:r,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:o,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Yh,useInput as Kh}from"ink";import{useCallback as le,useRef as Jh,useState as vt}from"react";import{spawn as Vh}from"child_process";function Na(t){return new Promise((e,s)=>{let r,n;process.platform==="darwin"?(r="open",n=[t]):process.platform==="win32"?(r="cmd",n=["/c","start","",t]):(r="xdg-open",n=[t]);let i=Vh(r,n,{stdio:"ignore",detached:!0});i.once("error",o=>{s(o)}),i.once("spawn",()=>{i.unref(),e()})})}var Ba=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new task"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Toggle client capabilities"},{name:"approval",aliases:[],description:"Choose when tool calls need your approval"},{name:"tasks",aliases:["c"],description:"Switch to another task"},{name:"runs",aliases:[],description:"List background runs / stop one"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current task in browser"},{name:"share",aliases:[],description:"Get share link for current task"},{name:"delete",aliases:["del"],description:"Delete current task"},{name:"quit",aliases:["exit","q"],description:"Exit task"}];function Wa(t){if(!t.startsWith("/"))return[];let e=t.slice(1).toLowerCase();return e?Ba.filter(s=>s.name.startsWith(e)||s.aliases.some(r=>r.startsWith(e))):Ba}function Ua(t){let e=t.trim();if(!e.startsWith("/"))return null;let s=e.slice(1).split(/\s+/),r=s[0]?.toLowerCase(),n=s.slice(1).join(" ");switch(r){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"approval":return{type:"approval"};case"tasks":case"c":return{type:"tasks"};case"runs":return{type:"runs"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:e}}}var ja=`Available commands:
59
+ /help, /h, /? Show this help message
60
+ /clear, /cls, /new Start a new task
61
+ /model [name], /m Show current model or switch to [name]
62
+ /agent [name], /a Show current agent or switch to [name]
63
+ /skills [name], /sk List skills or show details for [name]
64
+ /schedules [id], /sch List schedules or show details for [id]
65
+ /connectors, /conn Select active connectors
66
+ /capabilities, /cap Toggle client capabilities (FileSystem)
67
+ /approval Choose when tool calls need your approval
68
+ /tasks, /c Switch to another task
69
+ /runs List background runs / stop one
70
+ /workspace [id], /ws List or switch workspace
71
+ /budget [amount], /bg View or set workspace budget
72
+ /usage, /u View current month usage (top 10 by cost)
73
+ /status, /s Show current session status
74
+ /profile [args], /p Manage profiles (list/show/use/create/delete/rename/clone)
75
+ /open-in-browser Open current task in browser
76
+ /share Get share link for current task
77
+ /delete, /del Delete current task
78
+ /quit, /exit, /q Exit interactive mode
79
+
80
+ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
81
+
82
+ Keyboard shortcuts:
83
+ Ctrl+O Toggle full output mode
84
+ Ctrl+C Exit`;function za(t){if(t.type==="no-repeat")return"No repeat";let{interval:e}=t;switch(e.unit){case"minutes":return`Every ${e.every} min`;case"hours":return`Every ${e.every} hr`;case"days":return`Every ${e.every} day at ${String(e.time.hour).padStart(2,"0")}:${String(e.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${e.every} week`;case"months":return`Every ${e.every} month`;default:return"Unknown"}}function Ga({input:t,setInput:e,taskId:s,setTaskId:r,currentTaskTitle:n,setCurrentTaskTitle:i,currentModel:o,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:c,currentAgentDetails:h,setCurrentAgentDetails:d,activeConnectorIds:m,setActiveConnectorIds:g,fileSystem:p,setFileSystem:y,toolApprovalMode:v,setToolApprovalMode:S,availableModels:b,availableAgents:R,availableConnectors:_,messages:A,hasPersistedTask:G,setHasPersistedTask:L,setMessages:I,addSystemMessage:f,startNewTask:N,sendMessage:K,noteTranscriptLoad:et,setFullOutput:H,credentials:k,setCredentials:q,setState:V,defaultCapabilities:Q,capabilityLabelMap:Pt,hasUploadingFiles:ot=!1}){let{exit:yt}=Yh(),[ft,kt]=vt([]),[bt,Dt]=vt(0),[O,P]=vt(!1),[M,U]=vt(null),[T,D]=vt([]),[F,Y]=vt(0),[Ot,_t]=vt(new Set),[Ae,Pe]=vt(new Set),[Es,Rs]=vt([]),[_e,Nn]=vt([]),[Zt,_r]=vt([]),[ue,As]=vt([]),[Xt,Ir]=vt([]),[Qt,te]=vt(null),[Ps,Ie]=vt(""),be=Jh(!1),[he,$e]=vt(!1),Me=le(async()=>{if(!k)return[];let $=new lt,x=[],u;do{let w=await $.listAvailableSkills(k.accessToken,k.workspaceId,{limit:100,nextKey:u});x.push(...w.skills),u=w.nextKey}while(u);return _r(x),x},[k]),Fe=le(async()=>{if(!k)return[];let $=new lt,x=[],u;do{let w=await $.getSchedules(k.accessToken,k.workspaceId,{limit:100,nextKey:u});x.push(...w.schedules),u=w.nextKey}while(u);return As(x),x},[k]),ht=le(async $=>{if($==="model"){if(b.length===0){f("No models available.");return}let x=b.map(w=>({id:w.id,name:w.name,description:w.description}));D(x);let u=o?x.findIndex(w=>w.id===o):-1;Y(Math.max(u,0)),U("model")}else if($==="agent"){if(R.length===0){f("No agents available.");return}let x=R.map(w=>({id:w.id,name:w.name,description:w.description}));D(x);let u=l?x.findIndex(w=>w.id===l):-1;Y(Math.max(u,0)),U("agent")}else if($==="skills"){let x=Zt;if(x.length===0)try{x=await Me()}catch{f("Failed to load skills.");return}if(x.length===0){f("No skills available.");return}let u=x.map(w=>({id:w.id,name:w.name,description:w.description}));D(u),Y(0),U("skills")}else if($==="schedules"){let x=ue;if(x.length===0)try{x=await Fe()}catch{f("Failed to load schedules.");return}if(x.length===0){f("No schedules found.");return}let u=x.map(w=>({id:w.id,name:w.name,description:`${w.agent.name} - ${w.isActive?"Active":"Paused"}`}));D(u),Y(0),U("schedules")}else if($==="connectors"){if(_.length===0){f("No connectors available.");return}let x=_.map(u=>({id:u.id,name:u.name}));D(x),Y(0),_t(new Set(m)),U("connectors")}else if($==="capabilities"){D([{id:"fileSystem",name:"FileSystem",description:"Local file operations"}]),Y(0);let u=new Set;p&&u.add("fileSystem"),Pe(u),U("capabilities")}else if($==="approval"){let x=Object.values(Oe);D(x.map(u=>({id:u,name:Le[u],description:u===v?`${Ke[u]} (current)`:Ke[u]}))),Y(Math.max(0,x.indexOf(v))),U("approval")}else if($==="tasks"){if(!k){f("Not logged in.");return}try{let x=new lt,{tasks:u}=await x.getTasks(k.accessToken,k.workspaceId,20);if(u.length===0){f("No tasks available.");return}Rs(u);let w=u.map(B=>({id:B.id,name:B.title||"Untitled",description:new Date(B.createdAt).toLocaleDateString()}));D(w);let C=w.findIndex(B=>B.id===s);Y(Math.max(C,0)),U("tasks")}catch{f("Failed to load tasks.")}}else if($==="runs"){if(!k){f("Not logged in.");return}try{let x=new lt,{runs:u}=await x.listBackgroundRuns(k.accessToken,k.workspaceId,s);if(u.length===0){f("No background runs.");return}Nn(u),D(u.map(w=>({id:w.runId,name:w.label,description:`${w.kind} \xB7 ${w.status}`}))),Y(0),U("runs")}catch{f("Failed to load background runs.")}}else if($==="profile"){let x=it.getProfileNames(),u=it.getCurrentProfileName(),w=x.map(B=>({id:B,name:B,description:B===u?"(current)":void 0}));D(w);let C=w.findIndex(B=>B.id===u);Y(Math.max(C,0)),U("profile")}P(!1),kt([])},[b,R,Zt,ue,_,m,o,l,p,v,Me,Fe,k,s,f]),ct=le($=>{let x=at.getAll($);a(x.model?.default),c(void 0),d(null);let u=x.connectors?.defaults;g(u&&u.length>0?u:void 0);let w=x.localTools;y(w?.fileSystem??Q.fileSystem),S(x.toolApprovalMode??ve)},[a,c,d,g,y,S,Q]),Se=le(async()=>{try{let $=await zt();q({accessToken:$.accessToken,workspaceId:$.workspaceId}),V({status:"ready"})}catch($){if(q(null),$ instanceof xe){if($.code==="not-logged-in"){V({status:"not-logged-in"});return}if($.code==="no-workspace"){V({status:"no-workspace"});return}}let x=$ instanceof Error?$.message:"Authentication failed";V({status:"error",message:x})}},[q,V]),De=le(async $=>{switch($.type){case"help":return f(ja),!0;case"clear":return N("Started a new task."),!0;case"model":if($.value){let x=$.value.toLowerCase(),u=b.find(w=>w.id.toLowerCase()===x||w.name.toLowerCase().includes(x));if(u)l?N(`Switched to model: ${u.name} (new task)`):f(`Switched to model: ${u.name}`),a(u.id),c(void 0),d(null),at.setDefaultModel(u.id);else{let w=b.map(C=>C.name).join(", ");f(`Model "${$.value}" not found.
85
+ Available: ${w||"none"}`)}}else{let x=b.find(u=>u.id===o)?.name||o;f(o?`Current model: ${x}`:"No model selected. Using agent mode.")}return!0;case"agent":{if(!$.value)return R.length===0?(f("No agents available."),!0):(ht("agent"),!0);let x=$.value.toLowerCase(),u=R.find(w=>w.id.toLowerCase()===x||w.name.toLowerCase().includes(x));if(u)u.id===l?f(`Switched to agent: ${u.name}`):N(`Switched to agent: ${u.name} (new task)`),c(u.id),a(void 0);else{let w=R.map(C=>C.name).join(", ");f(`Agent "${$.value}" not found.
86
+ Available: ${w||"none"}`)}return!0}case"skills":{if(!$.value)return ht("skills"),!0;let x=$.value.toLowerCase();return(Zt.length>0?Promise.resolve(Zt):Me().catch(()=>[])).then(w=>{let C=w.find(B=>B.id.toLowerCase()===x||B.name.toLowerCase().includes(x));f(C?`Skill: ${C.name}
87
+ ${C.description}
88
+ Provider: ${C.provider}
89
+ Author: ${C.author.name}
90
+ ID: ${C.id}`:`Skill "${$.value}" not found.`)}),!0}case"schedules":{if(!$.value)return ht("schedules"),!0;let x=$.value.toLowerCase();return(ue.length>0?Promise.resolve(ue):Fe().catch(()=>[])).then(w=>{let C=w.find(B=>B.id.toLowerCase()===x||B.name.toLowerCase().includes(x));if(C){let B=C.nextRunAt?new Date(C.nextRunAt).toLocaleString():"-";f(`Schedule: ${C.name}
91
+ Agent: ${C.agent.name}
92
+ Status: ${C.isActive?"Active":"Paused"}
93
+ Repeat: ${za(C.config)}
94
+ Next run: ${B}
95
+ ID: ${C.id}`)}else f(`Schedule "${$.value}" not found.`)}),!0}case"connectors":{if(l){let u=h?.connectors??[];if(u.length===0)f("No agent connectors.");else{let w=u.map(C=>` - ${C.name}`).join(`
96
+ `);f(`Agent connectors:
97
+ ${w}`)}return!0}let x=_.filter(u=>m?.includes(u.id));if(x.length===0)f("No active connectors.");else{let u=x.map(w=>` - ${w.name}`).join(`
98
+ `);f(`Active connectors:
99
+ ${u}`)}return!0}case"capabilities":{if(l){let w=(h?.capabilities??[]).map(C=>Pt.get(C)??C);return f(w.length>0?`Agent capabilities:
100
+ ${w.map(C=>` - ${C}`).join(`
101
+ `)}`:"No agent capabilities."),!0}let x=[];return p&&x.push("FileSystem"),f(x.length>0?`Active capabilities:
102
+ ${x.map(u=>` - ${u}`).join(`
103
+ `)}`:"No capabilities enabled."),!0}case"approval":return f(`Tool approval: ${Le[v]} \u2014 ${Ke[v]}`),!0;case"tasks":return f(n?`Current task: ${n}`:`Current task: ${s.slice(0,8)}\u2026`),!0;case"runs":return ht("runs"),!0;case"workspace":{if(!k)return f("Not logged in."),!0;let x=new lt;if(!$.value){try{let{workspaces:w}=await x.getWorkspaces(k.accessToken);if(w.length===0)f("No workspaces found.");else{let C=w.map(B=>` ${B.id===k.workspaceId?"* ":" "}${B.name}
104
+ ID: ${B.id}`);f(`Workspaces:
105
+ ${C.join(`
106
+ `)}`)}}catch(w){f(`Failed to load workspaces: ${w instanceof Error?w.message:"Unknown error"}`)}return!0}let u=$.value;try{let{workspaces:w}=await x.getWorkspaces(k.accessToken),C=w.find(B=>B.id===u);if(!C)return f(`Workspace not found: ${u}`),!0;await ke.saveWorkspaceId(u),f(`Switched to workspace: ${C.name}`),f("Restart the task to apply the change.")}catch(w){f(`Failed to switch workspace: ${w instanceof Error?w.message:"Unknown error"}`)}return!0}case"budget":{if(!k)return f("Not logged in."),!0;let x=new lt;if(!$.value){try{let C=await x.getBudget(k.accessToken,k.workspaceId);C.budget===null?f("No budget set for this workspace."):f(`Current budget: $${C.budget}`)}catch(C){f(`Failed to get budget: ${C instanceof Error?C.message:"Unknown error"}`)}return!0}let u=$.value.toLowerCase();if(u==="clear"||u==="null"){try{await x.updateBudget(k.accessToken,k.workspaceId,null),f("Budget cleared.")}catch(C){f(`Failed to clear budget: ${C instanceof Error?C.message:"Unknown error"}`)}return!0}let w=Number.parseFloat(u);if(Number.isNaN(w)||w<0)return f("Invalid budget amount. Must be a positive number."),!0;try{await x.updateBudget(k.accessToken,k.workspaceId,u),f(`Budget set to: $${u}`)}catch(C){f(`Failed to set budget: ${C instanceof Error?C.message:"Unknown error"}`)}return!0}case"usage":{if(!k)return f("Not logged in."),!0;let x=new lt;try{let u=[],w,C=0,B=10;do{let Z=await x.getMonthlyUsages(k.accessToken,k.workspaceId,{nextKey:w,limit:20});if(u.push(...Z.monthlyUsages),w=Z.nextKey,C++,C>=B){f(`Warning: Showing first ${u.length} entries (pagination limit reached)`);break}}while(w);if(u.length===0)return f("No usage data found for this workspace."),!0;let st=0,rt=0;for(let Z of u)st+=Number.parseFloat(Z.totalCost),rt+=Z.operationCount;let ee=[...u].toSorted((Z,Lt)=>Number.parseFloat(Lt.totalCost)-Number.parseFloat(Z.totalCost)),E=10,j=ee.slice(0,E),J=[`Total cost: $${st.toFixed(2)}`,`Total operations: ${rt.toLocaleString()}`,`Users: ${u.length}`,"",`Top ${j.length} users by cost:`,...j.map(Z=>` ${Z.user.name}: $${Number.parseFloat(Z.totalCost).toFixed(2)} (${Z.operationCount.toLocaleString()} ops)`)];u.length>E&&(J.push("",`\u2026 and ${u.length-E} more users`),J.push("For the full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),f(J.join(`
107
+ `))}catch(u){f(`Failed to get usage: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"status":{let x=it.getCurrentProfileName(),u=o?b.find(st=>st.id===o)?.name||o:null,w=l?R.find(st=>st.id===l)?.name||l:null,C=gr({agentId:l,agentDetails:h,activeConnectorIds:m,availableConnectors:_}),B=[];return p&&B.push("FileSystem"),ke.getEmail().then(st=>{let rt=[`Profile: ${x}${x==="default"?"":" (non-default)"}`,st?`Logged in as: ${st}`:"Not logged in",k?.workspaceId?`Workspace: ${k.workspaceId}`:null,G?`Task ID: ${s}`:null,u?`Model: ${u}`:null,w?`Agent: ${w}`:null,`Connectors: ${C}`,`Capabilities: ${B.length>0?B.join(", "):"none"}`].filter(Boolean);f(rt.join(`
108
+ `))}).catch(()=>{let st=[`Profile: ${x}`,"Not logged in",G?`Task ID: ${s}`:null,u?`Model: ${u}`:null,w?`Agent: ${w}`:null,`Connectors: ${C}`,`Capabilities: ${B.length>0?B.join(", "):"none"}`].filter(Boolean);f(st.join(`
109
+ `))}),!0}case"profile":{let x=$.value?$.value.split(/\s+/).filter(Boolean):[];if(x.length===0)return ht("profile"),!0;let u=x[0]?.toLowerCase()||"list",w=x[1],C=x[2],B=it.getProfileNames(),st=it.getCurrentProfileName(),rt=it.getOverrideProfile(),ee=(E,j=!1)=>{if(E)return E;if(j&&B.length===1)return B[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(u==="list"){let E=[`Profiles (${B.length}):`];for(let j of B){let J=j===st?" (current)":"";E.push(` ${j}${J}`)}return f(E.join(`
110
+ `)),!0}if(u==="current")return f(`Current profile: ${st}`),!0;if(u==="show"){let E=ee(w,!0),j=at.getAll(E),J=await ke.getAll(E),Z=!!J?.accessToken,Lt=j.connectors?.defaults&&j.connectors.defaults.length>0?j.connectors.defaults.join(", "):"unset",el=[`Profile: ${E}${E===st?" (current)":""}`,`API URL: ${j.apiUrl??"default"}`,`Hub URL: ${j.hubUrl??"default"}`,`Model: ${j.model?.default??"unset"}`,`Connectors: ${Lt}`,Z?`Logged in as: ${J?.email??"unknown"}`:"Not logged in",Z&&J?.workspaceId?`Workspace ID: ${J.workspaceId}`:null].filter(Boolean);return f(el.join(`
111
+ `)),!0}if(u==="create"){let E=w||it.DEFAULT_PROFILE;return it.createProfile(E),f(`Profile created: ${E}`),!0}if(u==="use"||u==="switch"){let E=ee(w,!0);return it.setOverrideProfile(E),it.setCurrentProfile(E),ct(E),await Se(),N(`Switched to profile: ${E} (new task)`),!0}if(u==="delete"||u==="remove"||u==="rm"){let E=ee(w,!0),j=E===st,J=it.deleteProfile(E);await ke.deleteProfileCredentials(E);let Z=`Profile deleted: ${E}`;if(j)it.setOverrideProfile(J.currentProfile),ct(J.currentProfile),await Se(),N(`${Z}
112
+ Switched to profile: ${J.currentProfile} (new task)`);else if(rt===E){let Lt=it.getCurrentProfileName();it.setOverrideProfile(Lt),ct(Lt),await Se(),N(`${Z}
113
+ Switched to profile: ${Lt} (new task)`)}else f(Z);return!0}if(u==="rename"||u==="move"||u==="mv"){let E=ee(w,!0);if(!C)throw new Error("New profile name is required.");let j=it.renameProfile(E,C);return await ke.moveProfileCredentials(E,C),f(`Profile renamed: ${E} -> ${C}`),rt===E?(it.setOverrideProfile(C),ct(C)):j.currentProfile===C&&ct(C),!0}if(u==="clone"||u==="copy"){let E=ee(w,!0);if(!C)throw new Error("Target profile name is required.");let j=at.getAll(E);return it.createProfile(C),at.setAll(j,C),await ke.clear(C),f(`Profile cloned: ${E} -> ${C}`),!0}f(`Unknown profile command: ${u}`)}catch(E){let j=E instanceof Error?E.message:"Unknown error";f(`Profile error: ${j}`)}return!0}case"open-in-browser":{let x=Or().hubUrl.replace(/\/$/,""),u=G||A.some(rt=>rt.role!=="system"),w=k?`/${k.workspaceId}`:"",C=u?`${w}/task/${s}`:`${w}/task/new`,B=l?`?agentId=${encodeURIComponent(l)}`:"",st=`${x}${C}${B}`;try{await Na(st),f(`Opened in browser: ${st}`)}catch(rt){f(`Failed to open browser: ${rt instanceof Error?rt.message:"Unknown error"}
114
+ URL: ${st}`)}return!0}case"share":{if(!k)return f("Not logged in."),!0;if(!(G||A.some(u=>u.role!=="system")))return f("No task to share. Start a task first."),!0;try{let w=await new lt().createTaskShare(k.accessToken,k.workspaceId,s,"public"),B=`${Or().hubUrl.replace(/\/$/,"")}/share/${w.id}`;f(`Share link: ${B}`)}catch(u){f(`Failed to create share link: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"delete":return k?G?($e(!0),f("Delete this task? [y/N]"),!0):(f("No task to delete."),!0):(f("Not logged in."),!0);case"quit":return yt(),!0;case"unknown":return f(`Unknown command: ${$.input}
115
+ Type /help for available commands.`),!0;default:return!1}},[f,b,R,_,Zt,ue,o,l,m,p,s,n,yt,ht,N,Pt,h,G,A,Me,Fe,I,a,c,d,a,ct,Se]),_s=le($=>{if(be.current=!1,he){($===""||$.startsWith("/"))&&(e($),$.startsWith("/")&&$e(!1));return}if(e($),Ie($),Qt!==null&&te(null),M&&(U(null),D([])),$.startsWith("/")&&!$.includes(" ")){let x=Wa($);kt(x),Dt(0),P(x.length>0)}else P(!1),kt([])},[M,Qt,he,e]),Ye=le(($,x=!1)=>{if($>=0&&$<ft.length){let u=ft[$];P(!1),kt([]),u.name==="model"?(e("/model "),ht("model")):u.name==="agent"?(e("/agent "),ht("agent")):u.name==="skills"?(e("/skills "),ht("skills")):u.name==="schedules"?(e("/schedules "),ht("schedules")):u.name==="connectors"?(e("/connectors "),ht("connectors")):u.name==="capabilities"?(e("/capabilities "),ht("capabilities")):u.name==="approval"?(e("/approval "),ht("approval")):u.name==="tasks"?(e("/tasks "),ht("tasks")):u.name==="runs"?(e("/runs "),ht("runs")):u.name==="profile"?(e("/profile "),ht("profile")):x?(e(""),De({type:u.name})):e(`/${u.name}`)}},[ft,ht,e,De]),Is=le(async $=>{be.current=!1;let x=$.trim();if(!x||he)return;if(O&&ft.length>0){Ye(bt,!0);return}te(null),Ie(""),Ir(w=>w.length>0&&w.at(-1)===x?w:[...w,x]);let u=Ua(x);if(u){await De(u),e(""),P(!1);return}if(ot){f("Wait for the uploads to finish.");return}e(""),P(!1),K(x)},[K,De,O,ft,bt,Ye,f,e,ot,he,k,G,s]);return Kh(($,x)=>{if(x.ctrl&&$==="c"){if(t.length>0){_s(""),be.current=!0,f("Press Ctrl+C again to exit.");return}if(be.current){yt();return}yt();return}if(x.ctrl&&$==="o"){H(u=>!u);return}if(he){if(x.escape||x.return||$==="n"||$==="N"){$e(!1),e(""),f("Task deletion canceled.");return}if($==="y"||$==="Y"){$e(!1),e(""),k&&G&&new lt().deleteTask(k.accessToken,k.workspaceId,s).then(()=>{N("Task deleted. Started a new task.")}).catch(w=>{f(`Failed to delete task: ${w.message||"Unknown error"}`)});return}return}if(M&&T.length>0){if(x.upArrow){Y(u=>u<=0?T.length-1:u-1);return}if(x.downArrow){Y(u=>u>=T.length-1?0:u+1);return}if(x.escape){U(null),D([]),e("");return}if(x.return){if(M==="model"){let u=T[F];u&&(l?N(`Switched to model: ${u.name} (new task)`):f(`Switched to model: ${u.name}`),a(u.id),c(void 0),d(null),at.setDefaultModel(u.id))}else if(M==="agent"){let u=T[F];u&&(u.id===l?f(`Switched to agent: ${u.name}`):N(`Switched to agent: ${u.name} (new task)`),c(u.id),a(void 0))}else if(M==="skills"){let u=T[F];if(u){let w=Zt.find(C=>C.id===u.id);w&&f(`Skill: ${w.name}
116
+ ${w.description}
117
+ Provider: ${w.provider}
118
+ Author: ${w.author.name}
119
+ ID: ${w.id}`)}}else if(M==="schedules"){let u=T[F];if(u){let w=ue.find(C=>C.id===u.id);if(w){let C=w.nextRunAt?new Date(w.nextRunAt).toLocaleString():"-";f(`Schedule: ${w.name}
120
+ Agent: ${w.agent.name}
121
+ Status: ${w.isActive?"Active":"Paused"}
122
+ Repeat: ${za(w.config)}
123
+ Next run: ${C}
124
+ ID: ${w.id}`)}}}else if(M==="connectors"){let u=[...Ot];g(u.length>0?u:void 0),at.setDefaultConnectorIds(u);let w=_.filter(C=>Ot.has(C.id)).map(C=>C.name);f(w.length>0?`Active connectors: ${w.join(", ")}`:"No connector selected \u2014 every connected connector is available.")}else if(M==="capabilities"){let u=Ae.has("fileSystem");y(u),at.setLocalTools({fileSystem:u});let w=[];u&&w.push("FileSystem"),f(w.length>0?`Active capabilities: ${w.join(", ")}`:"All capabilities disabled.")}else if(M==="approval"){let u=T[F];if(u){let w=u.id;S(w),at.setToolApprovalMode(w),f(`Tool approval: ${Le[w]} \u2014 ${Ke[w]}`)}}else if(M==="tasks"){let u=T[F];if(u){let w=Es.find(C=>C.id===u.id);if(w&&k){r(w.id),i(w.title||void 0),L(!0);let C=new lt;et(C.getMessages(k.accessToken,k.workspaceId,w.id,20).then(({messages:B})=>{let st=B.filter(rt=>rt.role==="user"||rt.role==="assistant").map(rt=>({role:rt.role,content:we(rt.parts,!1),parts:rt.parts})).filter(rt=>rt.content).toReversed();return I(st),f(`Switched to: ${w.title||"Untitled"}`),B.map(rt=>rt.id)}).catch(()=>(f("Failed to load task messages."),[])))}}}else if(M==="runs"){let u=T[F];if(u){let w=_e.find(C=>C.runId===u.id);w&&k&&new lt().stopBackgroundRun(k.accessToken,k.workspaceId,s,w.runId,w.kind).then(B=>{f(B==="stopping"?`Stopping: ${w.label}`:`Already finished: ${w.label}`)}).catch(()=>{f(`Failed to stop: ${w.label}`)})}}else if(M==="profile"){let u=T[F];if(u){let w=it.getCurrentProfileName();u.id===w?f(`Already using profile: ${u.name}`):(it.setOverrideProfile(u.id),it.setCurrentProfile(u.id),ct(u.id),Se(),N(`Switched to profile: ${u.name}`))}}U(null),D([]),e("");return}if($===" "&&(M==="connectors"||M==="capabilities")){let u=T[F];u&&(M==="connectors"?_t:Pe)(C=>{let B=new Set(C);return B.has(u.id)?B.delete(u.id):B.add(u.id),B});return}if($==="a"&&(M==="connectors"||M==="capabilities")){(M==="connectors"?_t:Pe)(new Set(T.map(w=>w.id)));return}if($==="n"&&(M==="connectors"||M==="capabilities")){(M==="connectors"?_t:Pe)(new Set);return}return}if(O&&ft.length>0){if(x.upArrow){Dt(u=>u<=0?ft.length-1:u-1);return}if(x.downArrow){Dt(u=>u>=ft.length-1?0:u+1);return}if(x.escape){P(!1),kt([]);return}if(x.tab){Ye(bt);return}}if(x.upArrow){if(t.includes(`
125
+ `)||Xt.length===0)return;if(Qt===null){Ie(t);let w=Xt.length-1;te(w),e(Xt[w]);return}let u=Math.max(0,Qt-1);te(u),e(Xt[u]);return}if(x.downArrow){if(t.includes(`
126
+ `)||Qt===null)return;if(Qt>=Xt.length-1){te(null),e(Ps);return}let u=Qt+1;te(u),e(Xt[u])}}),{suggestions:ft,suggestionIndex:bt,showSuggestions:O,argMode:M,argItems:T,argIndex:F,selectedConnectorIds:Ot,selectedCapabilities:Ae,deleteConfirmMode:he,handleInputChange:_s,handleSubmit:Is}}import{useCallback as ks,useRef as Zh,useState as Qh}from"react";function Ha({credentials:t,currentModel:e,modelProviders:s,onUploadSuccess:r,onUploadError:n}){let[i,o]=Qh([]),a=Zh(0),l=ks(y=>{if(!(!Array.isArray(s)||s.length===0)){for(let v of s)if(v.models.some(b=>b.id===y))return v.id;return s[0]?.id}},[s]),c=ks(async y=>{if(!t){n?.(y.filename,"Not logged in");return}if(!Array.isArray(s)||s.length===0){n?.(y.filename,"Model providers are still loading. Try again in a moment.");return}let v=e?l(e):s[0]?.id;if(!v){n?.(y.filename,"No model provider available");return}let S=`file-${++a.current}`;o(b=>[...b,{id:S,filename:y.filename,mimeType:y.mimeType,status:"uploading"}]);try{let R=await new lt().uploadFile(t.accessToken,t.workspaceId,y,v);o(_=>_.map(A=>A.id===S?{...A,status:"uploaded",fileId:R.id}:A)),r?.(y.filename)}catch(b){let R=b instanceof Error?b.message:"Upload failed";o(_=>_.map(A=>A.id===S?{...A,status:"error",error:R}:A)),n?.(y.filename,R)}},[t,e,l,s,r,n]),h=ks(y=>{o(v=>v.filter(S=>S.id!==y))},[]),d=ks(()=>{o([])},[]),m=ks(()=>i.filter(y=>y.status==="uploaded").map(y=>y.fileId).filter(Bn),[i]),g=i.some(y=>y.status==="uploading"),p=i.length>0;return{pendingFiles:i,addFile:c,removeFile:h,clearFiles:d,getUploadedFileIds:m,hasUploadingFiles:g,hasFiles:p}}import{Fragment as Va,jsx as z,jsxs as X}from"react/jsx-runtime";var td=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],ed=[En,En,Cn,Cn,Re,Re,Re,Re],Xa=td.map((t,e)=>`${ed[e]??Re}${t}${tt}`).join(`
127
+ `),sd=`${Re}EntryDesk${tt}`,rd=500;function nd(t){let e="",s=0;for(;s<t.length;){if(t.charCodeAt(s)===27&&t[s+1]==="["){for(s+=2;s<t.length;){let r=t.charCodeAt(s);if(r>=64&&r<=126){s+=1;break}s+=1}continue}e+=t[s],s+=1}return e}function id(t){let e=nd(t);return Math.max(...e.split(`
128
+ `).map(s=>s.length))}function od(t){let e=id(Xa);return t>=e?Xa:sd}function Ya({agentId:t,model:e,message:s,taskId:r,taskTitle:n,connectorIds:i,enableFileSystem:o=!0,toolApprovalMode:a=ve}){let[l,c]=qa(a),{approvalRound:h,handleApprovalRequest:d,handleApprovalKey:m}=ha(),g=process.stdout.columns??80,p=od(g),y=Fn(null),v=pa(r,n),{state:S,setState:b,messages:R,setMessages:_,input:A,setInput:G,taskId:L,setTaskId:I,currentTaskTitle:f,setCurrentTaskTitle:N,hasPersistedTask:K,setHasPersistedTask:et,credentials:H,setCredentials:k,currentResponse:q,setCurrentResponse:V,fullOutput:Q,setFullOutput:Pt,addSystemMessage:ot,startNewTask:yt}=v,{credentials:ft}=ga(b);Rr(()=>{ft&&!H&&k(ft)},[ft,H,k]);let{availableConnectors:kt,availableModels:bt,availableAgents:Dt,modelProviders:O,loading:P}=ma(H),{currentModel:M,setCurrentModel:U,currentAgentId:T,setCurrentAgentId:D,activeConnectorIds:F,setActiveConnectorIds:Y}=La(e,t,i),Ot=Fn(!1);Rr(()=>{if(!Ot.current){if(Ot.current=!0,!e&&!t){let E=at.getDefaultModel();E&&U(E)}if(!i&&!t){let E=at.getDefaultConnectorIds();E&&Y(E.length>0?E:void 0)}}},[e,t,i,U,Y]);let{currentAgentDetails:_t}=Oa(T,H),{fileSystem:Ae,setFileSystem:Pe,capabilityLabelMap:Es}=Da(o),{pendingFiles:Rs,addFile:_e,removeFile:Nn,clearFiles:Zt,getUploadedFileIds:_r,hasUploadingFiles:ue,hasFiles:As}=Ha({credentials:H,currentModel:M,modelProviders:O,onUploadSuccess:E=>{ot(`\u2713 Attached: ${E}`)},onUploadError:(E,j)=>{ot(`\u2717 Failed to upload ${E}: ${j}`)}}),{sendMessage:Xt,backgroundRuns:Ir,noteTranscriptLoad:Qt}=Ma({taskId:L,credentials:H,currentAgentId:T,currentModel:M,activeConnectorIds:F,localTools:Ae,toolApprovalMode:l,onApprovalRequest:d,fullOutput:Q,setMessages:_,setState:b,setCurrentResponse:V,setCredentials:k,hasPersistedTask:K,setHasPersistedTask:et,getFileIds:_r,clearFiles:Zt}),te=Cr(Ir),Ps=Mn(E=>{yt(E),V("")},[yt]),[Ie,be]=qa(!1),he=Mn(async E=>{let j=E.text.trim(),J=fr(j);if(/^https?:\/\//.test(J))return;if(await na(j)&&ra(J)){let Lt=await ia(j);Lt&&(E.preventDefault(),await _e(Lt))}},[_e]),$e=Mn(async()=>{if(!(Ie||S.status!=="ready")){if(P||O.length===0){ot("Wait for resources to load before pasting images.");return}ot("Reading clipboard\u2026"),be(!0);try{let E=await sa();if(E){let j=`clipboard-${Date.now()}.png`;ot(`Uploading: ${j} (${Math.round(E.buffer.length/1024)}KB)`),await _e({buffer:E.buffer,filename:j,mimeType:E.mime})}else ot("No image found in clipboard. Copy an image first.")}catch(E){let j=E instanceof Error?E.message:"Failed to read clipboard";ot(`Clipboard error: ${j}`)}finally{be(!1)}}},[_e,ot,Ie,S.status,P,O.length]),{suggestions:Me,suggestionIndex:Fe,showSuggestions:ht,argMode:ct,argItems:Se,argIndex:De,selectedConnectorIds:_s,selectedCapabilities:Ye,deleteConfirmMode:Is,handleInputChange:$,handleSubmit:x}=Ga({input:A,setInput:G,taskId:L,setTaskId:I,currentTaskTitle:f,setCurrentTaskTitle:N,currentModel:M,setCurrentModel:U,currentAgentId:T,setCurrentAgentId:D,currentAgentDetails:_t,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:Y,fileSystem:Ae,setFileSystem:Pe,toolApprovalMode:l,setToolApprovalMode:c,availableModels:bt,availableAgents:Dt,availableConnectors:kt,messages:R,hasPersistedTask:K,setHasPersistedTask:et,setMessages:_,addSystemMessage:ot,startNewTask:Ps,sendMessage:Xt,noteTranscriptLoad:Qt,setFullOutput:Pt,credentials:H,setCredentials:k,setState:b,defaultCapabilities:{fileSystem:o},capabilityLabelMap:Es,hasUploadingFiles:ue});xs((E,j)=>{(j.ctrl||j.meta)&&E==="v"&&$e()},{isActive:S.status==="ready"&&!ct}),xs((E,j)=>{if(!j.escape)return;let J=Date.now(),Z=y.current;y.current=J,!(!Z||J-Z>rd)&&(ct||ht||(y.current=null,As&&Zt(),A.length>0&&$("")))},{isActive:S.status==="ready"}),xs((E,j)=>{j.return&&(Ps("Started a new task."),b({status:"ready"}))},{isActive:S.status==="error"}),xs((E,j)=>{if(!j.tab||!j.shift)return;let J=Object.values(Oe),Z=J[(J.indexOf(l)+1)%J.length]??ve;c(Z),at.setToolApprovalMode(Z)},{isActive:S.status==="ready"&&!ct}),xs(m,{isActive:h!==null}),Rr(()=>{if(H&&!P&&S.status==="loading")if(!M&&!T){let E=at.getDefaultModel(),j=E&&bt.some(Z=>Z.id===E),J=j?E:bt[0]?.id;J?(j||at.setDefaultModel(J),U(J),b({status:"ready"})):Dt.length===0?b({status:"no-model"}):b({status:"ready"})}else b({status:"ready"})},[H,P,M,T,bt,Dt,S.status,U,b]);let u=Fn(!1);if(Rr(()=>{u.current||s&&H&&S.status==="ready"&&(u.current=!0,Xt(s))},[H,s,S.status,Xt]),S.status==="loading")return X(dt,{flexDirection:"column",children:[z(W,{children:p}),X(dt,{children:[z(W,{color:"cyan",children:z($n,{type:"dots"})}),z(W,{children:" Initializing task\u2026"})]})]});if(S.status==="not-logged-in")return X(dt,{flexDirection:"column",children:[z(W,{children:p}),z(W,{color:"yellow",children:"Not logged in"}),z(W,{dimColor:!0,children:"Run `entrydesk login` first."})]});if(S.status==="no-workspace")return X(dt,{flexDirection:"column",children:[z(W,{children:p}),z(W,{color:"yellow",children:"No workspace selected"}),z(W,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(S.status==="no-model")return X(dt,{flexDirection:"column",children:[z(W,{children:p}),z(W,{color:"yellow",children:"No model or agent specified"}),r&&z(W,{dimColor:!0,children:"Could not determine the model used in this task."}),z(W,{dimColor:!0,children:"Specify a model with --model, or an agent with -a."}),z(W,{dimColor:!0,children:"Example: entrydesk task -c 1 -i --model gemini-2.5-flash-lite"})]});if(S.status==="error")return X(dt,{flexDirection:"column",children:[z(W,{children:p}),X(W,{color:"red",children:["Error: ",S.message]}),z(W,{dimColor:!0,children:"Press Enter to start a new task, or Ctrl+C to exit"})]});let w=gr({agentId:T,agentDetails:_t,activeConnectorIds:F,availableConnectors:kt}),C=[];if(T)if(_t?.capabilities)for(let E of _t.capabilities)C.push(Es.get(E)??E);else C.push("loading\u2026");Ae&&C.push("FileSystem");let B=it.getCurrentProfileName(),st=B!=="default",rt=(()=>{switch(ct){case"model":return"Select model:";case"agent":return"Select agent:";case"skills":return"Select skill:";case"connectors":return"Select connectors:";case"capabilities":return"Select capabilities:";case"approval":return"Select approval mode:";case"runs":return"Select a run to stop:";default:return"Select task:"}})(),ee=(()=>{if(ct==="connectors")return _s;if(ct==="capabilities")return Ye})();return X(dt,{flexDirection:"column",children:[X(dt,{marginBottom:1,flexDirection:"column",children:[z(W,{children:p}),X(dt,{children:[z(W,{bold:!0,color:"cyan",children:f?`Continuing: ${f}`:"EntryDesk CLI"}),X(W,{dimColor:!0,children:[" v","1.32.0-beta"]}),st&&X(W,{color:"magenta",children:[" [",B,"]"]}),z(W,{dimColor:!0,children:" (type /help for commands)"})]})]}),R.map((E,j)=>{let J=E.parts&&Q?we(E.parts,!0):E.content,Z=E.role==="user"?"green":E.role==="system"?"yellow":"blue",Lt=E.role==="user"?"You":E.role==="system"?"System":"Assistant";return X(dt,{flexDirection:"column",marginBottom:1,children:[X(W,{bold:!0,color:Z,children:[Lt,":"]}),z(xn,{text:J})]},j)}),q&&X(dt,{flexDirection:"column",marginBottom:1,children:[z(W,{bold:!0,color:"blue",children:"Assistant:"}),z(xn,{text:q})]}),S.status==="ready"&&z(Bo,{suggestions:Me,activeIndex:Fe,visible:ht}),S.status==="ready"&&ct&&z(No,{items:Se,activeIndex:De,pageSize:ct==="agent"||ct==="skills"||ct==="model"?5:10,selectedIds:ee,multiSelect:ct==="connectors"||ct==="capabilities",visible:!0,title:rt}),h&&h.requests[h.index]&&X(dt,{flexDirection:"column",marginY:1,borderStyle:"round",borderColor:"yellow",paddingX:1,children:[X(W,{color:"yellow",bold:!0,children:["Approve tool call?",h.requests.length>1&&X(W,{dimColor:!0,children:[" ","(",h.index+1," of ",h.requests.length,")"]})]}),z(W,{children:qe(h.requests[h.index].toolName)}),z(W,{dimColor:!0,wrap:"truncate-end",children:qe(JSON.stringify(h.requests[h.index].input))}),h.lastUndoneToolName&&X(W,{dimColor:!0,children:["undid ",qe(h.lastUndoneToolName)," \u2014 back to pending"]}),X(W,{dimColor:!0,children:["[y] approve [n] reject",h.requests.length>1&&X(Va,{children:[" ","[a] approve all [r] reject all",h.index>0&&z(Va,{children:" [u] undo"})]})]})]}),S.status==="sending"&&!q?X(dt,{children:[z(W,{color:"cyan",children:z($n,{type:"dots"})}),z(W,{children:" Thinking\u2026"})]}):S.status==="ready"&&!ct?X(dt,{flexDirection:"column",children:[Is&&z(dt,{marginBottom:1,children:z(W,{color:"yellow",children:"\u26A0\uFE0F Delete this task? [y/N] "})}),As&&!Is&&X(dt,{marginBottom:1,flexDirection:"row",gap:1,children:[z(W,{dimColor:!0,children:"Attachments:"}),Rs.map((E,j)=>X(W,{children:[E.status==="uploading"?X(W,{color:"yellow",children:[z($n,{type:"dots"})," ",E.filename]}):E.status==="error"?X(W,{color:"red",children:["\u2717 ",E.filename]}):X(W,{color:"green",children:["\u2713 ",E.filename]}),j<Rs.length-1&&z(W,{children:", "})]},E.id))]}),X(dt,{children:[z(W,{color:"green",children:"> "}),z(Xo,{value:A,onChange:$,onSubmit:x,onPaste:he,leadingOffset:2,multiline:!0})]})]}):null,te.activeCount>0&&z(dt,{children:X(W,{dimColor:!0,children:["background: ",te.activeCount," running \u2014 /runs"]})}),X(dt,{marginTop:1,flexDirection:"column",children:[X(dt,{gap:2,children:[X(W,{children:[z(W,{dimColor:!0,children:"Model: "}),z(W,{color:"magenta",children:T?_t?.model?.name||"loading\u2026":bt.find(E=>E.id===M)?.name||M||"none"})]}),X(W,{children:[z(W,{dimColor:!0,children:"Connectors: "}),z(W,{color:"cyan",children:w})]}),X(W,{children:[z(W,{dimColor:!0,children:"Capabilities: "}),z(W,{color:"green",children:C.length>0?C.join(", "):"none"})]}),X(W,{children:[z(W,{dimColor:!0,children:"Approval: "}),z(W,{color:"yellow",children:Le[l]})]})]}),X(W,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",Q?"(ON)":"(OFF)"," | Shift+Tab: Approval mode | Ctrl+C: Exit"]})]})]})}import{Chat as ad}from"@ai-sdk/react";import{getToolName as Dn}from"ai";import{v4 as ld}from"uuid";var Ka="Non-interactive run: no one is available to approve.",cd=300*1e3;function ud(t,e){return new Promise(s=>{let r=setTimeout(s,e),n=()=>{clearTimeout(r),s()};t.then(n,n)})}function Ja(t){return t.status==="ready"||t.status==="error"}function On(t,e){return Ja(t)?Promise.resolve():new Promise(s=>{let r,n,i=()=>{clearTimeout(r),n(),s()};e!==void 0&&(r=setTimeout(i,e)),n=t["~registerStatusCallback"](()=>{Ja(t)&&i()})})}async function Za({taskId:t,text:e,resolveCredentials:s,resolveTaskConfig:r,sendTask:n,isClientTool:i,runClientTool:o,onChunk:a,onStreamEnd:l,onApprovalDenied:c,resumeTask:h,backgroundRuns:d,openWakeEvents:m,onBackgroundWaitTimeout:g,backgroundWaitTimeoutMs:p=cd}){let y=new Set,v,S=new Ve({resolveCredentials:s,resolveTaskConfig:r,sendTask:n,onToolPartsSubmitted:A=>{for(let G of A)y.add(G)},onChunk:A=>{v?.notifyChunk(A),a?.(A)},...l?{onStreamEnd:l}:{},...h?{resumeTask:h,resumeSignal:()=>v?.resumeSignal}:{}}),b=new ad({id:t,transport:S,generateId:ld,onError:()=>v?.notifyError(),sendAutomaticallyWhen:A=>Je({messages:A.messages,isClientTool:i,submittedToolCallIds:y})});async function R(){let A=$s(b.messages.at(-1)),G=A.filter(f=>f.state==="approval-requested");for(let f of G)await b.addToolApprovalResponse({id:f.approval.id,approved:!1,reason:Ka}),c?.(Dn(f));if(G.length>0)return!0;let L=A.filter(f=>i(f)&&f.state==="approval-responded"&&!f.approval.approved);for(let f of L)await b.addToolOutput({tool:Dn(f),toolCallId:f.toolCallId,state:"output-error",errorText:Ka});let I=A.filter(f=>i(f)&&f.state==="input-available");for(let f of I){let N=Dn(f),K=await o(N,f.input??{});await b.addToolOutput({tool:N,toolCallId:f.toolCallId,state:"output-available",output:K})}return L.length+I.length>0}async function _(A){let G,L=!0,I,f=Sr({taskId:t,getStatus:()=>b.status,resumeStream:()=>{let k=b.resumeStream().finally(()=>{G===k&&(G=void 0)});return G=k,k},isKnownMessage:k=>b.messages.some(q=>q.id===k),...m?{openWakeEvents:m}:{},onWake:()=>I?.(),onResumeSettled:({delivered:k})=>{k&&(L=!1)}});v=f;let N=A.subscribe(()=>{A.getSnapshot().activeCount>0&&(L=!0)}),K=Date.now()+p,et=()=>K-Date.now(),H=k=>new Promise(q=>{let V=setTimeout(()=>{I=void 0,q(!1)},k);I=()=>{clearTimeout(V),I=void 0,q(!0)}});try{for(f.notifyWake();et()>0&&!(!await A.waitForNoActiveRuns({timeoutMs:et()})||(await On(b,et()),et()<=0));)if(f.notifyStatusChange(),!(A.getSnapshot().activeCount>0)){if(G){await ud(G,et());continue}if(!(b.status!=="error"&&await R())){if(!L)return;if(!await H(et()))break}}g?.(A.getSnapshot().runs.filter(k=>!se(k.stream.status)))}finally{N(),f.dispose()}}for(await b.sendMessage({text:e}),await On(b);b.status!=="error"&&await R();)await On(b);return d&&d.getSnapshot().runs.length>0&&await _(d),b}import{jsx as yd}from"react/jsx-runtime";function Ow(){console.log(`
129
+ Usage: entrydesk task [options]
130
+
131
+ Send a message to a model or agent, or start an interactive session.
132
+
133
+ Options:
134
+ -m, --message <text> Message to send (or pipe via stdin)
135
+ --model <modelId> Model to use (required if no agent and no default)
136
+ -a, --agent <agentId> Agent to use (instead of --model)
137
+ -c, --continue <n> Continue recent task #n
138
+ -i, --interactive Interactive mode (continuous chat)
139
+ --connectors id1,id2 Limit to specific connectors (default: all connected)
140
+ --plain Plain text output
141
+ --output stream-json Stream events as JSON
142
+ --full-output Show full tool outputs
143
+ --no-file-system Disable local file operations
144
+ --tool-approval-mode <mode>
145
+ always_ask | auto | always_allow. Defaults to the
146
+ mode /approval saved. Non-interactive runs deny
147
+ every approval they are asked for
148
+ --dangerously-auto-approve-tools
149
+ Deprecated alias for --tool-approval-mode always_allow
150
+ --json Output JSON
151
+
152
+ Examples:
153
+ entrydesk task -m "Hello" --model <model>
154
+ entrydesk task -m "Hello" -a <agentId>
155
+ entrydesk task -c 1 -m "Follow up" # Continue recent task
156
+ entrydesk task -i # Interactive mode
157
+ echo "Explain this" | entrydesk task --model <model> # Pipe stdin
158
+ entrydesk task -m "Hi" --model <m> --output stream-json
159
+
160
+ List available models: entrydesk models
161
+ List available agents: entrydesk agents
162
+ List recent tasks: entrydesk tasks
163
+ `)}async function fd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf8").trim()}async function gd(t,e,s,r){if(r<1)return console.error("Task number must be 1 or greater"),null;let{tasks:n}=await t.getTasks(e,s,20);if(n.length===0)return console.error("No tasks found. Start a new task first."),null;if(r>n.length)return console.error(`Task number ${r} not found. You have ${n.length} recent tasks.`),console.error("Use `entrydesk tasks` to see available tasks."),null;let i=n[r-1],o;if(!i.agentId){let{messages:a}=await t.getMessages(e,s,i.id,10);o=a.find(c=>c.role==="assistant"&&c.modelId)?.modelId}return{task:i,modelId:o}}var ce="\x1B[2m",pt="\x1B[0m",Ln="\x1B[36m",Pr="\x1B[33m",Ar="\x1B[32m",Qa="stream-json";function md(t,e,s,r){t&&e&&(console.error(`Error: Cannot use both ${s} and ${r}`),process.exit(1))}function Ts(t,e){let s=e===void 0?{event:t}:{event:t,data:e};process.stdout.write(`${JSON.stringify(s)}
164
+ `)}function Cs(t,e){if(e)return t;let s=t.split(`
165
+ `);if(s.length<=20)return t;let r=s.slice(0,5),n=s.slice(-5),i=s.length-10;return[...r,`${ce}\u2026 (${i} lines omitted, use --full-output to see all) \u2026${pt}`,...n].join(`
166
+ `)}function wd(t){try{return JSON.stringify(t,null,2)}catch{return String(t)}}function tl(t,e){if(!t)return"(no result)";if(typeof t!="object")return Cs(String(t),e);let s=t;if("structuredContent"in s&&s.structuredContent){let r=s.structuredContent,n=[];if(r.stdout&&typeof r.stdout=="string"&&r.stdout.trim()&&n.push(r.stdout.trim()),r.stderr&&typeof r.stderr=="string"&&r.stderr.trim()&&n.push(`${Pr}[stderr]${pt} ${r.stderr.trim()}`),r.urls&&Array.isArray(r.urls)){let i=r.urls;for(let o of i)o.path&&o.url&&n.push(`${o.path}: ${o.url}`)}return n.length===0&&n.push(JSON.stringify(r,null,2)),Cs(n.join(`
167
+ `),e)}if("content"in s&&Array.isArray(s.content)){let n=s.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
168
+ `);return Cs(n||JSON.stringify(t,null,2),e)}return s.type==="text"&&typeof s.content=="string"?Cs(s.content,e):Cs(JSON.stringify(t,null,2),e)}async function Lw(t){t.interactive&&!process.stdin.isTTY&&(console.error("Interactive mode requires a terminal (stdin is not a TTY) \u2014 falling back to non-interactive output. Pass -m/--message or pipe a message via stdin."),t.interactive=!1);let e,s;try{let T=await zt();e=T.accessToken,s=T.workspaceId}catch(T){Lr(T)}let r=t.output===Qa;t.output&&!r&&(console.error(`Invalid --output value. Supported: ${Qa}`),process.exit(1)),t.dangerouslyAutoApproveTools&&console.error("--dangerously-auto-approve-tools is deprecated. Use --tool-approval-mode instead.");let i=t.toolApprovalMode??(t.dangerouslyAutoApproveTools?Oe.ALWAYS_ALLOW:void 0)??at.getToolApprovalMode()??void 0,o=!r&&(t.plain||!process.stdout.isTTY),a=at.getDefaultModel(),l=t.message;!l&&!process.stdin.isTTY&&(l=await fd());let c=new lt,h,d=!1;async function m(){if(d)return h;d=!0;try{({models:h}=await c.listSelectableModels(e,s))}catch{h=void 0}return h}async function g(){let T=await m();if(!T||a&&T.some(F=>F.id===a))return;let D=T[0]?.id;D&&(at.setDefaultModel(D),a=D)}let p,y,v,S;if(t.continue){let T=await gd(c,e,s,t.continue);if(T||process.exit(1),p=T.task.id,y=T.task.title??void 0,v=T.task.agentId??void 0,S=T.modelId,S&&!v&&!t.model){let F=await m();F&&!F.some(Y=>Y.id===S)&&(S=void 0)}let D=t.agentId||t.model||v||S||a;!D&&!t.interactive&&(await g(),D=t.agentId||t.model||v||S||a),!D&&!t.interactive&&(o||console.log(`Continuing task: ${T.task.title||"Untitled"}`),console.error(`
169
+ Could not determine the model for this task. Specify --model or -a.`),console.error('Example: entrydesk task -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!o&&!t.interactive&&console.log(`Continuing task: ${T.task.title||"Untitled"}
170
+ `)}let b=t.agentId||v,R=t.model||S||void 0;!b&&!R&&(await g(),R=t.model||S||a||void 0),md(t.fileSystem,t.noFileSystem,"--file-system","--no-file-system");let _=at.getDefaultConnectorIds(),A=t.connectors??_??void 0,G=at.getLocalTools(),L=t.noFileSystem?!1:t.fileSystem?!0:G?.fileSystem??!0;if(t.interactive){dd(yd(Ya,{agentId:b,model:R,message:t.message,taskId:p,taskTitle:y??void 0,connectorIds:A,enableFileSystem:L,toolApprovalMode:i??ve}),{exitOnCtrlC:!1});return}let I=!t.continue&&!R&&!b;(!l||I)&&(console.error("Provide a message, plus either a model or an agent. For example:"),console.error(" entrydesk task -m <message> --model <model>"),console.error(" entrydesk task -m <message> -a <agent>"),console.error(" entrydesk task -c <number> -m <message>"),console.error(' echo "message" | entrydesk task --model <model>'),console.error(" entrydesk task -i # Interactive mode"),console.error(""),console.error("Run `entrydesk task --help` for all options."),process.exit(1));let f=t.fullOutput??!1,N=p||pd(),K=L?nr():void 0,et=L?ir():void 0,H=()=>br({agentId:b,model:R,connectorIds:A,clientTools:K,clientToolSystemPrompt:et,toolApprovalMode:i}),k=yr({openRunEvents:(T,D)=>c.openSubagentRunEvents(e,s,T,D),getRun:(T,D)=>c.getSubagentRun(e,s,T,D)}),q=!0,V=T=>{process.stdout.write(T),q=T.endsWith(`
171
+ `)},Q=T=>V(`${T}
172
+ `),Pt=new Map,ot=()=>{if(!(o||r||!q))for(let T of k.getSnapshot().runs){let D=`${T.description}: ${xr(T.stream)}`;D!==Pt.get(T.runId)&&(Pt.set(T.runId,D),Q(`${ce}\u2502 ${D}${pt}`))}};k.subscribe(ot);let yt=new Set(["text-delta","reasoning-delta","tool-call","tool-input-available","tool-result","data-appendMessage"]),ft=!1,kt=new Set,bt=new Map,Dt=wa(),O=new Map,P=T=>{let D=Aa(T,O);if(D){Q(`${ce}\u2502 ${D}${pt}`);return}switch(T.type){case"reasoning-delta":T.delta&&V(`${ce}${T.delta}${pt}`);break;case"reasoning-end":V(`
173
+
174
+ `);break;case"text-delta":T.delta&&V(T.delta);break;case"data-appendMessage":V(Rn(T.data));break;case"tool-call-streaming-start":case"tool-input-start":if(T.toolCallId&&T.toolName){bt.set(T.toolCallId,T.toolName);let Y=L&&ps(T.toolName)?`${Ar}[LOCAL]${pt} `:"";Q(`
175
+ ${Ln}\u250C\u2500 ${Y}Tool: ${T.toolName}${pt}`)}break;case"tool-call":case"tool-input-available":if(T.toolCallId&&T.toolName){let F=wd(T.args||T.input||{});Q(`${Pr}\u2502 Input:${pt}`);for(let Y of F.split(`
176
+ `))Q(`${ce}\u2502 ${Y}${pt}`)}break;case"tool-result":if(T.toolCallId){let F=bt.get(T.toolCallId),Y=tl(T.result,f);Q(`${Ar}\u2502 Output:${pt}`);for(let Ot of Y.split(`
177
+ `))Q(`${ce}\u2502 ${Ot}${pt}`);Q(`${Ln}\u2514\u2500 ${F||"Tool"} completed${pt}
178
+ `),bt.delete(T.toolCallId)}break;case"error":T.errorText&&console.error(`${ce}Error: ${T.errorText}${pt}`);break;default:break}},M=T=>{let D=T;if(D.type&&yt.has(D.type)&&(ft=!0),k.ingestChunk(T),D.type==="start"&&Dt.noteMessageId(D.messageId),!(D.type==="data-appendMessage"&&!Dt.shouldRender(D.data))){if(r){D.type==="text-delta"&&D.delta!==void 0?Ts("text-delta",D.delta):D.type==="reasoning-delta"&&D.delta!==void 0?Ts("reasoning-delta",D.delta):Ts(D.type||"event",D);return}if(o){D.type==="text-delta"&&D.delta&&V(D.delta),D.type==="data-appendMessage"&&V(Rn(D.data));return}P(D),ot()}},U;try{U=await Za({taskId:N,text:l,resolveCredentials:()=>Promise.resolve({accessToken:e,workspaceId:s}),resolveTaskConfig:H,sendTask:(T,D)=>c.task(T.accessToken,T.workspaceId,D),isClientTool:T=>L&&ps(hd(T)),runClientTool:async(T,D)=>{!o&&!r&&Q(`${Ar}\u2502 Executing locally\u2026${pt}`);let F=await or(T,D);if(!o&&!r){let Y=tl(F.success?F.result:{error:F.error},f);Q(`${Ar}\u2502 Output:${pt}`);for(let Ot of Y.split(`
179
+ `))Q(`${ce}\u2502 ${Ot}${pt}`);Q(`${Ln}\u2514\u2500 ${T} completed${pt}
180
+ `)}return{content:ar(F),isError:!F.success}},onChunk:M,onStreamEnd:()=>{r&&Ts("done")},onApprovalDenied:T=>kt.add(T),resumeTask:T=>c.resumeTaskStream(T.accessToken,T.workspaceId,N),backgroundRuns:k,openWakeEvents:T=>c.openWakeEvents(e,s,N,T),onBackgroundWaitTimeout:T=>{let D=T.map(F=>({runId:F.runId,description:F.description,status:F.stream.status}));if(r){Ts("background-runs-pending",{runs:D});return}q||Q(""),Q(D.length>0?`Still running in the background: ${D.map(F=>`${F.description} (${F.status})`).join(", ")}`:"Timed out waiting for the background result.")}})}finally{k.dispose()}kt.size>0&&console.error(`${Pr}Tool approval denied (non-interactive run has no approver): ${[...kt].toSorted().join(", ")}${pt}`),U.status==="error"&&U.error&&Lr(U.error),ft||(console.error(`${Pr}No response received from the server (empty stream).${pt}`),console.error(`${ce}The task may have failed server-side. Re-run with DEBUG=1 for details.${pt}`),process.exit(1)),r||(Q(""),ot())}export{Ow as printTaskHelp,Lw as runTask};