@entrydesk/cli 1.29.0 → 1.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/{agents-HRFKKSCB.js → agents-JG6OXKYV.js} +1 -1
  2. package/dist/{billing-LXGGM4BO.js → billing-MGDBCV6I.js} +1 -1
  3. package/dist/{budget-3KJ75AIF.js → budget-YYGSDB4J.js} +1 -1
  4. package/dist/{chunk-YAWZE3PA.js → chunk-NC63CPWW.js} +60 -33
  5. package/dist/chunk-RJGB52EF.js +4 -0
  6. package/dist/{config-53QOLH2T.js → config-PBKYHI2B.js} +1 -1
  7. package/dist/{config-help-2YHNIPHU.js → config-help-RTQDCM2A.js} +1 -1
  8. package/dist/{connectors-YUVHSMJD.js → connectors-EEPEIQ76.js} +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/{login-BKSNJT4R.js → login-HL5KEHEN.js} +1 -1
  11. package/dist/{logout-U64RQTQO.js → logout-QI7X4M4E.js} +1 -1
  12. package/dist/{marketplace-4NZ4R2RK.js → marketplace-5QZCY7QH.js} +1 -1
  13. package/dist/mcp-5764U6QO.js +4 -0
  14. package/dist/{meeting-NAS2QHFI.js → meeting-5RUQYMWF.js} +1 -1
  15. package/dist/{models-E3O6GOH5.js → models-PFIG6ACY.js} +1 -1
  16. package/dist/{notifications-CSXLCFK2.js → notifications-ZCJVVQIC.js} +1 -1
  17. package/dist/{profile-4GVYKBJP.js → profile-RIAXCLXG.js} +1 -1
  18. package/dist/{recordings-GJIO55FV.js → recordings-FMD3YL7B.js} +1 -1
  19. package/dist/{schedules-7CGTNN5S.js → schedules-JFVHBBM3.js} +1 -1
  20. package/dist/{skills-OOY3DP3O.js → skills-L4AGJVTQ.js} +1 -1
  21. package/dist/{status-KK6P75DT.js → status-DBKKDZAF.js} +1 -1
  22. package/dist/task-PBX6HRS3.js +194 -0
  23. package/dist/{tasks-SJWOHL6F.js → tasks-7SK2EZZS.js} +1 -1
  24. package/dist/{tool-TW7BI2LH.js → tool-YOUXWQ76.js} +5 -5
  25. package/dist/{update-B3LT5ALF.js → update-3SS5DWV3.js} +1 -1
  26. package/dist/{usage-IQW77ZHI.js → usage-6PXKAMOY.js} +1 -1
  27. package/dist/{version-TG5WFL3B.js → version-RYL2AKE2.js} +1 -1
  28. package/dist/{workflow-J6RX65V7.js → workflow-6MU3A6LB.js} +1 -1
  29. package/dist/{workspaces-KDZIJPII.js → workspaces-EQSJKVVV.js} +1 -1
  30. package/package.json +7 -4
  31. package/dist/chunk-GN6HSCLY.js +0 -4
  32. package/dist/chunk-NOSHH4TO.js +0 -8
  33. package/dist/mcp-EON5KZPT.js +0 -4
  34. package/dist/task-ET6X7N52.js +0 -211
@@ -1,211 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as sn}from"./chunk-NOSHH4TO.js";import{a as lt,b as dt,c as oi,f as we,g as mt,p as be,s as nn,t as ue,v as rn}from"./chunk-GN6HSCLY.js";import{b as ta,d as ea}from"./chunk-ZIAOI7B2.js";var bn=ta((Xh,ws)=>{"use strict";function fn(t){return Array.isArray(t)?t:[t]}var oa=void 0,ci="",un=" ",li="\\",aa=/^\s+$/,la=/(?:[^\\]|^)\\$/,ca=/^\\!/,ha=/^\\#/,ua=/\r?\n/g,da=/^\.{0,2}\/|^\.{1,2}$/,fa=/\/$/,Pe="/",pn="node-ignore";typeof Symbol<"u"&&(pn=Symbol.for("node-ignore"));var mn=pn,Re=(t,e,s)=>(Object.defineProperty(t,e,{value:s}),s),pa=/([0-z])-([0-z])/g,gn=()=>!1,ma=t=>t.replace(pa,(e,s,i)=>s.charCodeAt(0)<=i.charCodeAt(0)?e:ci),ga=t=>{let{length:e}=t;return t.slice(0,e-e%2)},ya=[[/^\uFEFF/,()=>ci],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,s)=>e+(s.indexOf("\\")===0?un:ci)],[/(\\+?)\s/g,(t,e)=>{let{length:s}=e;return e.slice(0,s-s%2)+un}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,s)=>e+6<s.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(t,e,s)=>{let i=s.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>li],[/\\\\/g,()=>li],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,s,i,n)=>e===li?`\\[${s}${ga(i)}${n}`:n==="]"&&i.length%2===0?`[${ma(s)}${i}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`]],wa=/(^|\\\/)?\\\*$/,ze="regex",gs="checkRegex",dn="_",ba={[ze](t,e){return`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`},[gs](t,e){return`${e?`${e}[^/]*`:"[^/]*"}(?=$|\\/$)`}},xa=t=>ya.reduce((e,[s,i])=>e.replace(s,i.bind(t)),t),ys=t=>typeof t=="string",Sa=t=>t&&ys(t)&&!aa.test(t)&&!la.test(t)&&t.indexOf("#")!==0,va=t=>t.split(ua).filter(Boolean),hi=class{constructor(e,s,i,n,r,o){this.pattern=e,this.mark=s,this.negative=r,Re(this,"body",i),Re(this,"ignoreCase",n),Re(this,"regexPrefix",o)}get regex(){let e=dn+ze;return this[e]?this[e]:this._make(ze,e)}get checkRegex(){let e=dn+gs;return this[e]?this[e]:this._make(gs,e)}_make(e,s){let i=this.regexPrefix.replace(wa,ba[e]),n=this.ignoreCase?new RegExp(i,"i"):new RegExp(i);return Re(this,s,n)}},ka=({pattern:t,mark:e},s)=>{let i=!1,n=t;n.indexOf("!")===0&&(i=!0,n=n.substr(1)),n=n.replace(ca,"!").replace(ha,"#");let r=xa(n);return new hi(t,e,n,s,i,r)},ui=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[mn]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(ys(e)&&(e={pattern:e}),Sa(e.pattern)){let s=ka(e,this._ignoreCase);this._added=!0,this._rules.push(s)}}add(e){return this._added=!1,fn(ys(e)?va(e):e).forEach(this._add,this),this._added}test(e,s,i){let n=!1,r=!1,o;this._rules.forEach(l=>{let{negative:c}=l;r===c&&n!==r||c&&!n&&!r&&!s||!l[i].test(e)||(n=!c,r=c,o=c?oa:l)});let a={ignored:n,unignored:r};return o&&(a.rule=o),a}},Ta=(t,e)=>{throw new e(t)},ie=(t,e,s)=>ys(t)?t?ie.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),yn=t=>da.test(t);ie.isNotRelative=yn;ie.convert=t=>t;var di=class{constructor({ignorecase:e=!0,ignoreCase:s=e,allowRelativePaths:i=!1}={}){Re(this,mn,!0),this._rules=new ui(s),this._strictPathCheck=!i,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,i,n){let r=e&&ie.convert(e);return ie(r,e,this._strictPathCheck?Ta:gn),this._t(r,s,i,n)}checkIgnore(e){if(!fa.test(e))return this.test(e);let s=e.split(Pe).filter(Boolean);if(s.pop(),s.length){let i=this._t(s.join(Pe)+Pe,this._testCache,!0,s);if(i.ignored)return i}return this._rules.test(e,!1,gs)}_t(e,s,i,n){if(e in s)return s[e];if(n||(n=e.split(Pe).filter(Boolean)),n.pop(),!n.length)return s[e]=this._rules.test(e,i,ze);let r=this._t(n.join(Pe)+Pe,s,i,n);return s[e]=r.ignored?r:this._rules.test(e,i,ze)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return fn(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},fi=t=>new di(t),Ca=t=>ie(t&&ie.convert(t),t,gn),wn=()=>{let t=s=>/^\\\\\?\\/.test(s)||/["<>|\u0000-\u001F]+/u.test(s)?s:s.replace(/\\/g,"/");ie.convert=t;let e=/^[a-z]:\//i;ie.isNotRelative=s=>e.test(s)||yn(s)};typeof process<"u"&&process.platform==="win32"&&wn();ws.exports=fi;fi.default=fi;ws.exports.isPathValid=Ca;Re(ws.exports,Symbol.for("setupWindows"),wn)});import{render as Oh}from"ink";import{v4 as Jo}from"uuid";var Ae={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},ai=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem. Text files support an optional line range; image files are returned as viewable images.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."},start_line:{type:"number",description:"1-based starting line number (default: 1). Only applies to text files."},end_line:{type:"number",description:"1-based ending line number (default: start_line + 499). Only applies to text files."}},required:["path"]},annotations:Ae},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]},annotations:Ae},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."},encoding:{type:"string",enum:["utf-8","base64"],description:'The encoding of the content. Use "base64" to write binary files. Defaults to "utf-8".'}},required:["path","content"]},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},{name:"filesystem__edit_file",description:"Make precise text replacements in a file. Safer than write_file as it only modifies specific sections. Each edit must have a unique old_text that matches exactly once in the file.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to edit."},edits:{type:"array",description:"Array of text replacements to apply.",items:{type:"object",properties:{old_text:{type:"string",description:"The exact text to find and replace. Must be unique in the file. Include surrounding context (3+ lines) to ensure uniqueness."},new_text:{type:"string",description:"The text to replace old_text with."}},required:["old_text","new_text"]}},dry_run:{type:"boolean",description:"If true, return the diff without applying changes. Useful for previewing edits."}},required:["path","edits"]},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]},annotations:Ae},{name:"filesystem__search_files",description:"Search for files matching a glob pattern. Respects .gitignore by default.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},path:{type:"string",description:"Base directory to search in (optional)."},respect_gitignore:{type:"boolean",description:"Whether to respect .gitignore rules (default: true). Set to false to include ignored files."}},required:["pattern"]},annotations:Ae},{name:"filesystem__grep_files",description:"Search for text patterns within file contents using regex. Respects .gitignore rules. Uses ripgrep if available, falls back to git grep or native search.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Regex pattern to search for (e.g., "function\\s+\\w+", "TODO:").'},path:{type:"string",description:"Directory to search in (optional, defaults to current directory)."},include:{type:"string",description:'Glob pattern to filter files (e.g., "*.ts", "*.{js,jsx}").'},limit:{type:"number",description:"Maximum number of matches to return (default: 100, max: 500)."},context_lines:{type:"number",description:"Number of context lines before and after each match."}},required:["pattern"]},annotations:Ae},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]},annotations:Ae},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]},annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}}],on={filesystem__read_file:"**Read File**: Read a text file with an optional line range, or an image file as a viewable image",filesystem__read_multiple_files:"**Read Multiple Files**: Read multiple files at once (max 10); images among them are returned as viewable images",filesystem__write_file:"**Write File**: Create or overwrite a file (use for new files or complete replacements)",filesystem__edit_file:"**Edit File**: Make precise text replacements in a file (preferred for modifications)",filesystem__create_directory:"**Create Directory**: Create a new directory (including parent directories)",filesystem__list_directory:"**List Directory**: List files and subdirectories",filesystem__search_files:"**Search Files**: Search for files matching a glob pattern (by filename, respects .gitignore)",filesystem__grep_files:"**Grep Files**: Search for text patterns within file contents (respects .gitignore)",filesystem__get_file_info:"**Get File Info**: Get metadata about a file or directory",filesystem__move_file:"**Move File**: Move or rename a file or directory",filesystem__execute_command:"**Execute Command**: Run shell commands on the user's machine"},sa={filesystem__read_file:["For large text files, use start_line and end_line to read specific sections"],filesystem__edit_file:["**Prefer edit_file over write_file** for modifying existing files \u2014 it is safer and shows a diff","For edit_file, the old_text must match exactly and be unique in the file","Include 3+ lines of surrounding context in old_text to ensure uniqueness","Use dry_run=true to preview changes before applying"],filesystem__search_files:["Search results respect .gitignore rules by default"],filesystem__grep_files:["Use grep_files to search code content with regex patterns"],filesystem__execute_command:["Execute Command has a default timeout of 30 seconds (max 5 minutes)"]},ia=["Always use absolute paths when possible","Be mindful of file permissions and access restrictions","Large files and command output are truncated in responses"],na=[["platform","Platform"],["username","Username"],["home","Home"],["cwd","Current working directory"],["desktop","Desktop"],["downloads","Downloads"]];function ra(t){let e=na.flatMap(([s,i])=>{let n=t[s];return n?[`- ${i}: \`${n}\``]:[]});return e.length>0?`### Environment Context
3
-
4
- ${e.join(`
5
- `)}
6
-
7
- `:""}function an(t){let{toolNames:e,env:s,extraNotes:i}=t,n=e.flatMap(o=>on[o]?[`- ${on[o]}`]:[]),r=[...ia,...e.flatMap(o=>sa[o]??[]),...i??[]].map(o=>`- ${o}`);return`## Filesystem Tool Instructions
8
-
9
- You have access to filesystem tools that operate on the user's local machine.
10
-
11
- ${s?ra(s):""}### Available Operations
12
-
13
- ${n.join(`
14
- `)}
15
-
16
- ### Important Notes
17
-
18
- ${r.join(`
19
- `)}
20
- `}function ln(t){if(!t||typeof t!="object")return;let e=t;return e.type==="binary"&&typeof e.content=="string"?e:void 0}function cn(t){return t.mimeType?.startsWith("image/")??!1}function hn(t){let e=[],s=[],i=0,n=(l,c)=>{if(i+l.content.length>4194304){let h=`${cn(l)?"Image too large to view":"File too large"} inline (${l.size} bytes); the combined inline binary size for this read exceeds the limit.`;return s.push(c?`${c}: ${h}`:h),{...l,content:`[${h}]`}}if(i+=l.content.length,!!cn(l))return e.push({path:c,data:l.content,mimeType:l.mimeType??"application/octet-stream"}),{...l,content:`[image inlined above: ${l.mimeType??"binary"}, ${l.size} bytes]`}},r=ln(t);if(r)return{payload:n(r)??t,images:e,notes:s};let o=t?.files;if(!o||typeof o!="object"||Array.isArray(o))return{payload:t,images:e,notes:s};let a={};for(let[l,c]of Object.entries(o)){let d=ln(c);a[l]=d?n(d,l)??c:c}return{payload:{...t,files:a},images:e,notes:s}}import{exec as Wc}from"child_process";import Uc from"os";import _a from"fs/promises";var kn=ea(bn(),1);import Ge from"fs/promises";import xn from"os";import Ft from"path";function Dt(t){let e=t.startsWith("~/")||t.startsWith("~\\")?Ft.join(xn.homedir(),t.slice(2)):t==="~"?xn.homedir():t;return Ft.resolve(e)}function Sn(t){return t.normalize("NFC").replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/gu," ")}async function Mt(t){let e=Dt(t);try{return await Ge.access(e),e}catch(s){if((s&&typeof s=="object"&&"code"in s?String(s.code):void 0)!=="ENOENT")throw s;let n=Ft.dirname(e),r=Ft.basename(e),o;try{o=await Ge.readdir(n)}catch{throw s}let a=Sn(r),l=o.filter(d=>Sn(d)===a),[c]=l;if(l.length===1&&c)return Ft.join(n,c);if(l.length>1){let d=new Error(`Multiple files match "${r}" after whitespace normalization: ${l.join(", ")}. Use filesystem__list_directory and pass an exact name.`);throw d.code="EAMBIG",d}throw s}}var pi=100*1024,Tn=50*1024,He=10*1024*1024,Cn=10,mi=100,En=10,Ne=10*1024*1024,qe=3e4,_n=3e5;function ne(t,e=pi){return t.length>e?t.slice(0,e)+`
21
- ... [truncated, ${t.length-e} more characters]`:t}var vn={".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"},Ea=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 bs(t){let e=Ft.extname(t).toLowerCase();if(vn[e])return{type:"binary",mimeType:vn[e]};if(Ea.has(e))return{type:"text"};try{let s=await Ge.open(t,"r"),i=Buffer.alloc(8);if(await s.read(i,0,8,0),await s.close(),i[0]===137&&i[1]===80&&i[2]===78&&i[3]===71)return{type:"binary",mimeType:"image/png"};if(i[0]===255&&i[1]===216&&i[2]===255)return{type:"binary",mimeType:"image/jpeg"};if(i[0]===71&&i[1]===73&&i[2]===70&&i[3]===56)return{type:"binary",mimeType:"image/gif"};if(i[0]===37&&i[1]===80&&i[2]===68&&i[3]===70)return{type:"binary",mimeType:"application/pdf"};if(i[0]===82&&i[1]===73&&i[2]===70&&i[3]===70)return{type:"binary",mimeType:"image/webp"};for(let n of i)if(n===0)return{type:"binary"}}catch{}return{type:"text"}}async function xs(t){let e=(0,kn.default)();e.add([".git","node_modules",".DS_Store"]);let s=t,i=[];for(;s!==Ft.dirname(s);){let n=Ft.join(s,".gitignore");try{await Ge.access(n),i.unshift(n)}catch{}s=Ft.dirname(s)}for(let n of i)try{let r=await Ge.readFile(n,"utf-8");e.add(r)}catch{}return e}function Ss(t,e,s){return t.filter(i=>{let n=Ft.relative(e,i);return!s.ignores(n.split(Ft.sep).join("/"))})}function $n(t,e,s){let i=e.split(`
22
- `),n=s.split(`
23
- `),r=[`--- a/${Ft.basename(t)}`,`+++ b/${Ft.basename(t)}`],o=0,a=0;for(;o<i.length||a<n.length;){if(o<i.length&&a<n.length&&i[o]===n[a]){o++,a++;continue}let l=o,c=a,d=!1;for(let h=1;h<10&&!d;h++)for(let f=l;f<=l+h;f++){for(let y=c;y<=c+h;y++)if(f<i.length&&y<n.length&&i[f]===n[y]){let g=Math.max(0,l-3),w=Math.min(i.length,f+3),C=Math.max(0,c-3),k=Math.min(n.length,y+3);r.push(`@@ -${g+1},${w-g} +${C+1},${k-C} @@`);for(let E=g;E<l;E++)r.push(` ${i[E]}`);for(let E=l;E<f;E++)r.push(`-${i[E]}`);for(let E=c;E<y;E++)r.push(`+${n[E]}`);for(let E=f;E<Math.min(f+3,i.length);E++)E<w&&r.push(` ${i[E]}`);o=f,a=y,d=!0;break}if(d)break}if(!d){for(r.push(`@@ -${l+1},${i.length-l} +${c+1},${n.length-c} @@`);o<i.length;)r.push(`-${i[o]}`),o++;for(;a<n.length;)r.push(`+${n[a]}`),a++}}return r.join(`
24
- `)}var In=async t=>{try{return await _a.mkdir(Dt(t.path),{recursive:!0}),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to create directory"}}};import An from"fs/promises";var Pn=async t=>{try{let e=await Mt(t.path),s=await An.readFile(e,"utf-8"),i=s,n=[];for(let[o,a]of t.edits.entries()){let l=i.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)i=i.replace(o.old_text,o.new_text);let r=$n(e,s,i);return t.dry_run?{success:!0,applied:0,dry_run:!0,diff:r}:(await An.writeFile(e,i,"utf-8"),{success:!0,applied:t.edits.length,diff:r})}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to edit file"}}};import{exec as $a}from"child_process";import{existsSync as Ia}from"fs";import Aa from"os";import{promisify as Pa}from"util";var Ra=Pa($a),Rn=async t=>{try{let e=Dt(t.cwd||Aa.homedir());if(!Ia(e))return{success:!1,error:`Working directory does not exist: ${e}`};let s=Math.min(t.timeout??qe,_n),{stdout:i,stderr:n}=await Ra(t.command,{cwd:e,timeout:s,maxBuffer:He,shell:process.platform==="win32"?"cmd.exe":"/bin/bash"});return{success:!0,stdout:ne(i),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 Na from"fs/promises";var Nn=async t=>{try{let e=await Na.stat(await Mt(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 Ac}from"child_process";import Pc from"fs/promises";import Ur from"path";import{promisify as Rc}from"util";import{fileURLToPath as Ol}from"url";import{posix as jl,win32 as Ci}from"path";import{fileURLToPath as Wl}from"url";import{lstatSync as Ul,readdir as zl,readdirSync as Gl,readlinkSync as Hl,realpathSync as ql}from"fs";import*as Xl from"fs";import{lstat as Yl,readdir as Jl,readlink as Vl,realpath as Kl}from"fs/promises";import{EventEmitter as $i}from"events";import wr from"stream";import{StringDecoder as Zl}from"string_decoder";var sr=(t,e,s)=>{let i=t instanceof RegExp?Fn(t,s):t,n=e instanceof RegExp?Fn(e,s):e,r=i!==null&&n!=null&&Fa(i,n,s);return r&&{start:r[0],end:r[1],pre:s.slice(0,r[0]),body:s.slice(r[0]+i.length,r[1]),post:s.slice(r[1]+n.length)}},Fn=(t,e)=>{let s=e.match(t);return s?s[0]:null},Fa=(t,e,s)=>{let i,n,r,o,a,l=s.indexOf(t),c=s.indexOf(e,l+1),d=l;if(l>=0&&c>0){if(t===e)return[l,c];for(i=[],r=s.length;d>=0&&!a;){if(d===l)i.push(d),l=s.indexOf(t,d+1);else if(i.length===1){let h=i.pop();h!==void 0&&(a=[h,c])}else n=i.pop(),n!==void 0&&n<r&&(r=n,o=c),c=s.indexOf(e,d+1);d=l<c&&l>=0?l:c}i.length&&o!==void 0&&(a=[r,o])}return a},ir="\0SLASH"+Math.random()+"\0",nr="\0OPEN"+Math.random()+"\0",Ei="\0CLOSE"+Math.random()+"\0",rr="\0COMMA"+Math.random()+"\0",or="\0PERIOD"+Math.random()+"\0",Da=new RegExp(ir,"g"),Oa=new RegExp(nr,"g"),La=new RegExp(Ei,"g"),Ma=new RegExp(rr,"g"),Ba=new RegExp(or,"g"),ja=/\\\\/g,Wa=/\\{/g,Ua=/\\}/g,za=/\\,/g,Ga=/\\./g,Ha=1e5;function gi(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function qa(t){return t.replace(ja,ir).replace(Wa,nr).replace(Ua,Ei).replace(za,rr).replace(Ga,or)}function Xa(t){return t.replace(Da,"\\").replace(Oa,"{").replace(La,"}").replace(Ma,",").replace(Ba,".")}function ar(t){if(!t)return[""];let e=[],s=sr("{","}",t);if(!s)return t.split(",");let{pre:i,body:n,post:r}=s,o=i.split(",");o[o.length-1]+="{"+n+"}";let a=ar(r);return r.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function Ya(t,e={}){if(!t)return[];let{max:s=Ha}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Qe(qa(t),s,!0).map(Xa)}function Ja(t){return"{"+t+"}"}function Va(t){return/^-?0\d/.test(t)}function Ka(t,e){return t<=e}function Za(t,e){return t>=e}function Qe(t,e,s){let i=[],n=sr("{","}",t);if(!n)return[t];let r=n.pre,o=n.post.length?Qe(n.post,e,!1):[""];if(/\$$/.test(n.pre))for(let a=0;a<o.length&&a<e;a++){let l=r+"{"+n.body+"}"+o[a];i.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,d=n.body.indexOf(",")>=0;if(!c&&!d)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+Ei+n.post,Qe(t,e,!0)):[t];let h;if(c)h=n.body.split(/\.\./);else if(h=ar(n.body),h.length===1&&h[0]!==void 0&&(h=Qe(h[0],e,!1).map(Ja),h.length===1))return o.map(y=>n.pre+h[0]+y);let f;if(c&&h[0]!==void 0&&h[1]!==void 0){let y=gi(h[0]),g=gi(h[1]),w=Math.max(h[0].length,h[1].length),C=h.length===3&&h[2]!==void 0?Math.abs(gi(h[2])):1,k=Ka;g<y&&(C*=-1,k=Za);let E=h.some(Va);f=[];for(let N=y;k(N,g);N+=C){let I;if(l)I=String.fromCharCode(N),I==="\\"&&(I="");else if(I=String(N),E){let P=w-I.length;if(P>0){let tt=new Array(P+1).join("0");N<0?I="-"+tt+I.slice(1):I=tt+I}}f.push(I)}}else{f=[];for(let y=0;y<h.length;y++)f.push.apply(f,Qe(h[y],e,!1))}for(let y=0;y<f.length;y++)for(let g=0;g<o.length&&i.length<e;g++){let w=r+f[y]+o[g];(!s||c||w)&&i.push(w)}}return i}var Rs=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},Qa={"[: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]},Xe=t=>t.replace(/[[\]\\-]/g,"\\$&"),tl=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Dn=t=>t.join(""),el=(t,e)=>{let s=e;if(t.charAt(s)!=="[")throw new Error("not in a brace expression");let i=[],n=[],r=s+1,o=!1,a=!1,l=!1,c=!1,d=s,h="";t:for(;r<t.length;){let g=t.charAt(r);if((g==="!"||g==="^")&&r===s+1){c=!0,r++;continue}if(g==="]"&&o&&!l){d=r+1;break}if(o=!0,g==="\\"&&!l){l=!0,r++;continue}if(g==="["&&!l){for(let[w,[C,k,E]]of Object.entries(Qa))if(t.startsWith(w,r)){if(h)return["$.",!1,t.length-s,!0];r+=w.length,E?n.push(C):i.push(C),a=a||k;continue t}}if(l=!1,h){g>h?i.push(Xe(h)+"-"+Xe(g)):g===h&&i.push(Xe(g)),h="",r++;continue}if(t.startsWith("-]",r+1)){i.push(Xe(g+"-")),r+=2;continue}if(t.startsWith("-",r+1)){h=g,r+=2;continue}i.push(Xe(g)),r++}if(d<r)return["",!1,0,!1];if(!i.length&&!n.length)return["$.",!1,t.length-s,!0];if(n.length===0&&i.length===1&&/^\\?.$/.test(i[0])&&!c){let g=i[0].length===2?i[0].slice(-1):i[0];return[tl(g),!1,d-s,!1]}let f="["+(c?"^":"")+Dn(i)+"]",y="["+(c?"":"^")+Dn(n)+"]";return[i.length&&n.length?"("+f+"|"+y+")":i.length?f:y,a,d-s,!0]},Oe=(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"),sl=new Set(["!","?","+","*","@"]),On=t=>sl.has(t),il="(?!(?:^|/)\\.\\.?(?:$|/))",vs="(?!\\.)",nl=new Set(["[","."]),rl=new Set(["..","."]),ol=new Set("().*{}+?[]^$\\!"),al=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),_i="[^/]",Ln=_i+"*?",Mn=_i+"+?",lr=class Lt{type;#t;#s;#r=!1;#n=[];#o;#x;#y;#h=!1;#a;#d;#u=!1;constructor(e,s,i={}){this.type=e,e&&(this.#s=!0),this.#o=s,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?i:this.#t.#a,this.#y=this.#t===this?[]:this.#t.#y,e==="!"&&!this.#t.#h&&this.#y.push(this),this.#x=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.#h)return this;this.toString(),this.#h=!0;let e;for(;e=this.#y.pop();){if(e.type!=="!")continue;let s=e,i=s.#o;for(;i;){for(let n=s.#x+1;!i.type&&n<i.#n.length;n++)for(let r of e.#n){if(typeof r=="string")throw new Error("string part in extglob AST??");r.copyIn(i.#n[n])}s=i,i=s.#o}}return this}push(...e){for(let s of e)if(s!==""){if(typeof s!="string"&&!(s instanceof Lt&&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.#h&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#x===0)return!0;let e=this.#o;for(let s=0;s<this.#x;s++){let i=e.#n[s];if(!(i instanceof Lt&&i.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.#x===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let s=new Lt(this.type,e);for(let i of this.#n)s.copyIn(i);return s}static#i(e,s,i,n){let r=!1,o=!1,a=-1,l=!1;if(s.type===null){let y=i,g="";for(;y<e.length;){let w=e.charAt(y++);if(r||w==="\\"){r=!r,g+=w;continue}if(o){y===a+1?(w==="^"||w==="!")&&(l=!0):w==="]"&&!(y===a+2&&l)&&(o=!1),g+=w;continue}else if(w==="["){o=!0,a=y,l=!1,g+=w;continue}if(!n.noext&&On(w)&&e.charAt(y)==="("){s.push(g),g="";let C=new Lt(w,s);y=Lt.#i(e,C,y,n),s.push(C);continue}g+=w}return s.push(g),y}let c=i+1,d=new Lt(null,s),h=[],f="";for(;c<e.length;){let y=e.charAt(c++);if(r||y==="\\"){r=!r,f+=y;continue}if(o){c===a+1?(y==="^"||y==="!")&&(l=!0):y==="]"&&!(c===a+2&&l)&&(o=!1),f+=y;continue}else if(y==="["){o=!0,a=c,l=!1,f+=y;continue}if(On(y)&&e.charAt(c)==="("){d.push(f),f="";let g=new Lt(y,d);d.push(g),c=Lt.#i(e,g,c,n);continue}if(y==="|"){d.push(f),f="",h.push(d),d=new Lt(null,s);continue}if(y===")")return f===""&&s.#n.length===0&&(s.#u=!0),d.push(f),f="",s.push(...h,d),c;f+=y}return s.type=null,s.#s=void 0,s.#n=[e.substring(i-1)],c}static fromGlob(e,s={}){let i=new Lt(null,void 0,s);return Lt.#i(e,i,0,s),i}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let e=this.toString(),[s,i,n,r]=this.toRegExpSource();if(!(n||this.#s||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return i;let o=(this.#a.nocase?"i":"")+(r?"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(f=>typeof f!="string"),c=this.#n.map(f=>{let[y,g,w,C]=typeof f=="string"?Lt.#S(f,this.#s,l):f.toRegExpSource(e);return this.#s=this.#s||w,this.#r=this.#r||C,y}).join(""),d="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&rl.has(this.#n[0]))){let f=nl,y=s&&f.has(c.charAt(0))||c.startsWith("\\.")&&f.has(c.charAt(2))||c.startsWith("\\.\\.")&&f.has(c.charAt(4)),g=!s&&!e&&f.has(c.charAt(0));d=y?il:g?vs:""}let h="";return this.isEnd()&&this.#t.#h&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[d+c+h,Oe(c),this.#s=!!this.#s,this.#r]}let i=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#f(s);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#s=void 0,[l,Oe(this.toString()),!1,!1]}let o=!i||e||s||!vs?"":this.#f(!0);o===r&&(o=""),o&&(r=`(?:${r})(?:${o})*?`);let a="";if(this.type==="!"&&this.#u)a=(this.isStart()&&!s?vs:"")+Mn;else{let l=this.type==="!"?"))"+(this.isStart()&&!s&&!e?vs:"")+Ln+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=n+r+l}return[a,Oe(r),this.#s=!!this.#s,this.#r]}#f(e){return this.#n.map(s=>{if(typeof s=="string")throw new Error("string type in extglob ast??");let[i,n,r,o]=s.toRegExpSource(e);return this.#r=this.#r||o,i}).filter(s=>!(this.isStart()&&this.isEnd())||!!s).join("|")}static#S(e,s,i=!1){let n=!1,r="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(n){n=!1,r+=(ol.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,r+=i&&/^[*]+$/.test(e)?Mn:Ln,s=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?r+="\\\\":n=!0;continue}if(c==="["){let[d,h,f,y]=el(e,l);if(f){r+=d,o=o||h,l+=f-1,s=s||y;continue}}if(c==="?"){r+=_i,s=!0;continue}r+=al(c)}return[r,Oe(e),!!s,o]}},cr=(t,{windowsPathsNoEscape:e=!1,magicalBraces:s=!1}={})=>s?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),It=(t,e,s={})=>(Rs(e),!s.nocomment&&e.charAt(0)==="#"?!1:new pe(e,s).match(t)),ll=/^\*+([^+@!?\*\[\(]*)$/,cl=t=>e=>!e.startsWith(".")&&e.endsWith(t),hl=t=>e=>e.endsWith(t),ul=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),dl=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),fl=/^\*+\.\*+$/,pl=t=>!t.startsWith(".")&&t.includes("."),ml=t=>t!=="."&&t!==".."&&t.includes("."),gl=/^\.\*+$/,yl=t=>t!=="."&&t!==".."&&t.startsWith("."),wl=/^\*+$/,bl=t=>t.length!==0&&!t.startsWith("."),xl=t=>t.length!==0&&t!=="."&&t!=="..",Sl=/^\?+([^+@!?\*\[\(]*)?$/,vl=([t,e=""])=>{let s=hr([t]);return e?(e=e.toLowerCase(),i=>s(i)&&i.toLowerCase().endsWith(e)):s},kl=([t,e=""])=>{let s=ur([t]);return e?(e=e.toLowerCase(),i=>s(i)&&i.toLowerCase().endsWith(e)):s},Tl=([t,e=""])=>{let s=ur([t]);return e?i=>s(i)&&i.endsWith(e):s},Cl=([t,e=""])=>{let s=hr([t]);return e?i=>s(i)&&i.endsWith(e):s},hr=([t])=>{let e=t.length;return s=>s.length===e&&!s.startsWith(".")},ur=([t])=>{let e=t.length;return s=>s.length===e&&s!=="."&&s!==".."},dr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Bn={win32:{sep:"\\"},posix:{sep:"/"}},El=dr==="win32"?Bn.win32.sep:Bn.posix.sep;It.sep=El;var $t=Symbol("globstar **");It.GLOBSTAR=$t;var _l="[^/]",$l=_l+"*?",Il="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Al="(?:(?!(?:\\/|^)\\.).)*?",Pl=(t,e={})=>s=>It(s,t,e);It.filter=Pl;var Bt=(t,e={})=>Object.assign({},t,e),Rl=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return It;let e=It;return Object.assign((s,i,n={})=>e(s,i,Bt(t,n)),{Minimatch:class extends e.Minimatch{constructor(s,i={}){super(s,Bt(t,i))}static defaults(s){return e.defaults(Bt(t,s)).Minimatch}},AST:class extends e.AST{constructor(s,i,n={}){super(s,i,Bt(t,n))}static fromGlob(s,i={}){return e.AST.fromGlob(s,Bt(t,i))}},unescape:(s,i={})=>e.unescape(s,Bt(t,i)),escape:(s,i={})=>e.escape(s,Bt(t,i)),filter:(s,i={})=>e.filter(s,Bt(t,i)),defaults:s=>e.defaults(Bt(t,s)),makeRe:(s,i={})=>e.makeRe(s,Bt(t,i)),braceExpand:(s,i={})=>e.braceExpand(s,Bt(t,i)),match:(s,i,n={})=>e.match(s,i,Bt(t,n)),sep:e.sep,GLOBSTAR:$t})};It.defaults=Rl;var fr=(t,e={})=>(Rs(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:Ya(t,{max:e.braceExpandMax}));It.braceExpand=fr;var Nl=(t,e={})=>new pe(t,e).makeRe();It.makeRe=Nl;var Fl=(t,e,s={})=>{let i=new pe(e,s);return t=t.filter(n=>i.match(n)),i.options.nonull&&!t.length&&t.push(e),t};It.match=Fl;var jn=/[?*]|[+@!]\(.*?\)|\[|\]/,Dl=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),pe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){Rs(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||dr,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 i=this.globParts.map((n,r,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=n[0]===""&&n[1]===""&&(n[2]==="?"||!jn.test(n[2]))&&!jn.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,i),this.set=i.filter(n=>n.indexOf(!1)===-1),this.isWindows)for(let n=0;n<this.set.length;n++){let r=this.set[n];r[0]===""&&r[1]===""&&this.globParts[n][2]==="?"&&typeof r[3]=="string"&&/^[a-z]:$/i.test(r[3])&&(r[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let s=0;s<t.length;s++)for(let i=0;i<t[s].length;i++)t[s][i]==="**"&&(t[s][i]="*");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 i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let n=s[s.length-1];return i==="**"&&n==="**"?s:i===".."&&n&&n!==".."&&n!=="."&&n!=="**"?(s.pop(),s):(s.push(i),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 i=1;i<t.length-1;i++){let n=t[i];i===1&&n===""&&t[0]===""||(n==="."||n==="")&&(e=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let s=0;for(;(s=t.indexOf("..",s+1))!==-1;){let i=t[s-1];i&&i!=="."&&i!==".."&&i!=="**"&&(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 i=-1;for(;(i=s.indexOf("**",i+1))!==-1;){let r=i;for(;s[r+1]==="**";)r++;r>i&&s.splice(i+1,r-i);let o=s[i+1],a=s[i+2],l=s[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let c=s.slice(0);c[i]="**",t.push(c),i--}if(!this.preserveMultipleSlashes){for(let r=1;r<s.length-1;r++){let o=s[r];r===1&&o===""&&s[0]===""||(o==="."||o==="")&&(e=!0,s.splice(r,1),r--)}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(e=!0,s.pop())}let n=0;for(;(n=s.indexOf("..",n+1))!==-1;){let r=s[n-1];if(r&&r!=="."&&r!==".."&&r!=="**"){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 i=this.partsMatch(t[e],t[s],!this.preserveMultipleSlashes);if(i){t[e]=[],t[s]=i;break}}return t.filter(e=>e.length)}partsMatch(t,e,s=!1){let i=0,n=0,r=[],o="";for(;i<t.length&&n<e.length;)if(t[i]===e[n])r.push(o==="b"?e[n]:t[i]),i++,n++;else if(s&&t[i]==="**"&&e[n]===t[i+1])r.push(t[i]),i++;else if(s&&e[n]==="**"&&t[i]===e[n+1])r.push(e[n]),n++;else if(t[i]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(o==="b")return!1;o="a",r.push(t[i]),i++,n++}else if(e[n]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(o==="a")return!1;o="b",r.push(e[n]),i++,n++}else return!1;return t.length===e.length&&r}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,s=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)e=!e,s++;s&&(this.pattern=t.slice(s)),this.negate=e}matchOne(t,e,s=!1){let i=this.options;if(this.isWindows){let g=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),w=!g&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),C=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),k=!C&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=w?3:g?0:void 0,N=k?3:C?0:void 0;if(typeof E=="number"&&typeof N=="number"){let[I,P]=[t[E],e[N]];I.toLowerCase()===P.toLowerCase()&&(e[N]=I,N>E?e=e.slice(N):E>N&&(t=t.slice(E)))}}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 r=0,o=0,a=t.length,l=e.length;r<a&&o<l;r++,o++){this.debug("matchOne loop");var c=e[o],d=t[r];if(this.debug(e,c,d),c===!1)return!1;if(c===$t){this.debug("GLOBSTAR",[e,c,d]);var h=r,f=o+1;if(f===l){for(this.debug("** at the end");r<a;r++)if(t[r]==="."||t[r]===".."||!i.dot&&t[r].charAt(0)===".")return!1;return!0}for(;h<a;){var y=t[h];if(this.debug(`
25
- globstar while`,t,h,e,f,y),this.matchOne(t.slice(h),e.slice(f),s))return this.debug("globstar found match!",h,a,y),!0;if(y==="."||y===".."||!i.dot&&y.charAt(0)==="."){this.debug("dot detected!",t,h,e,f);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(s&&(this.debug(`
26
- >>> no match, partial?`,t,h,e,f),h===a))}let g;if(typeof c=="string"?(g=d===c,this.debug("string match",c,d,g)):(g=c.test(d),this.debug("pattern match",c,d,g)),!g)return!1}if(r===a&&o===l)return!0;if(r===a)return s;if(o===l)return r===a-1&&t[r]==="";throw new Error("wtf?")}braceExpand(){return fr(this.pattern,this.options)}parse(t){Rs(t);let e=this.options;if(t==="**")return $t;if(t==="")return"";let s,i=null;(s=t.match(wl))?i=e.dot?xl:bl:(s=t.match(ll))?i=(e.nocase?e.dot?dl:ul:e.dot?hl:cl)(s[1]):(s=t.match(Sl))?i=(e.nocase?e.dot?kl:vl:e.dot?Tl:Cl)(s):(s=t.match(fl))?i=e.dot?ml:pl:(s=t.match(gl))&&(i=yl);let n=lr.fromGlob(t,this.options).toMMPattern();return i&&typeof n=="object"&&Reflect.defineProperty(n,"test",{value:i}),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?$l:e.dot?Il:Al,i=new Set(e.nocase?["i"]:[]),n=t.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let h of d.flags.split(""))i.add(h);return typeof d=="string"?Dl(d):d===$t?$t:d._src});l.forEach((d,h)=>{let f=l[h+1],y=l[h-1];d!==$t||y===$t||(y===void 0?f!==void 0&&f!==$t?l[h+1]="(?:\\/|"+s+"\\/)?"+f:l[h]=s:f===void 0?l[h-1]=y+"(?:\\/|\\/"+s+")?":f!==$t&&(l[h-1]=y+"(?:\\/|\\/"+s+"\\/)"+f,l[h+1]=$t))});let c=l.filter(d=>d!==$t);if(this.partial&&c.length>=1){let d=[];for(let h=1;h<=c.length;h++)d.push(c.slice(0,h).join("/"));return"(?:"+d.join("|")+")"}return c.join("/")}).join("|"),[r,o]=t.length>1?["(?:",")"]:["",""];n="^"+r+n+o+"$",this.partial&&(n="^(?:\\/|"+r+n.slice(1,-1)+o+")$"),this.negate&&(n="^(?!"+n+").+$");try{this.regexp=new RegExp(n,[...i].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 i=this.slashSplit(t);this.debug(this.pattern,"split",i);let n=this.set;this.debug(this.pattern,"set",n);let r=i[i.length-1];if(!r)for(let o=i.length-2;!r&&o>=0;o--)r=i[o];for(let o=0;o<n.length;o++){let a=n[o],l=i;if(s.matchBase&&a.length===1&&(l=[r]),this.matchOne(l,a,e))return s.flipNegate?!0:!this.negate}return s.flipNegate?!1:this.negate}static defaults(t){return It.defaults(t).Minimatch}};It.AST=lr;It.Minimatch=pe;It.escape=cr;It.unescape=Oe;var Ll=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,pr=new Set,Ti=typeof process=="object"&&process?process:{},mr=(t,e,s,i)=>{typeof Ti.emitWarning=="function"?Ti.emitWarning(t,e,s,i):console.error(`[${s}] ${e}: ${t}`)},Ns=globalThis.AbortController,Wn=globalThis.AbortSignal;if(typeof Ns>"u"){Wn=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(s,i){this._onabort.push(i)}},Ns=class{constructor(){e()}signal=new Wn;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=!0;for(let i of this.signal._onabort)i(s);this.signal.onabort?.(s)}}};let t=Ti.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,mr("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 Ml=t=>!pr.has(t),fe=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),gr=t=>fe(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?As:null:null,As=class extends Array{constructor(t){super(t),this.fill(0)}},Bl=class ts{heap;length;static#t=!1;static create(e){let s=gr(e);if(!s)return[];ts.#t=!0;let i=new ts(e,s);return ts.#t=!1,i}constructor(e,s){if(!ts.#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]}},Ds=class yr{#t;#s;#r;#n;#o;#x;#y;#h;get perf(){return this.#h}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#u;#l;#i;#f;#S;#b;#p;#$;#m;#T;#C;#g;#w;#v;#E;#e;#F;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#g,autopurgeTimers:e.#w,sizes:e.#T,keyMap:e.#u,keyList:e.#l,valList:e.#i,next:e.#f,prev:e.#S,get head(){return e.#b},get tail(){return e.#p},free:e.#$,isBackgroundFetch:s=>e.#c(s),backgroundFetch:(s,i,n,r)=>e.#U(s,i,n,r),moveToTail:s=>e.#O(s),indexes:s=>e.#A(s),rindexes:s=>e.#P(s),isStale:s=>e.#k(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.#x}get memoMethod(){return this.#y}get dispose(){return this.#r}get onInsert(){return this.#n}get disposeAfter(){return this.#o}constructor(e){let{max:s=0,ttl:i,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:d,disposeAfter:h,noDisposeOnSet:f,noUpdateTTL:y,maxSize:g=0,maxEntrySize:w=0,sizeCalculation:C,fetchMethod:k,memoMethod:E,noDeleteOnFetchRejection:N,noDeleteOnStaleGet:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:tt,ignoreFetchAbort:m,perf:S}=e;if(S!==void 0&&typeof S?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#h=S??Ll,s!==0&&!fe(s))throw new TypeError("max option must be a nonnegative integer");let F=s?gr(s):Array;if(!F)throw new Error("invalid max value: "+s);if(this.#t=s,this.#s=g,this.maxEntrySize=w||this.#s,this.sizeCalculation=C,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(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#y=E,k!==void 0&&typeof k!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#x=k,this.#E=!!k,this.#u=new Map,this.#l=new Array(s).fill(void 0),this.#i=new Array(s).fill(void 0),this.#f=new F(s),this.#S=new F(s),this.#b=0,this.#p=0,this.#$=Bl.create(s),this.#a=0,this.#d=0,typeof c=="function"&&(this.#r=c),typeof d=="function"&&(this.#n=d),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#v=!!this.#r,this.#F=!!this.#n,this.#e=!!this.#o,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!N,this.allowStaleOnFetchRejection=!!P,this.allowStaleOnFetchAbort=!!tt,this.ignoreFetchAbort=!!m,this.maxEntrySize!==0){if(this.#s!==0&&!fe(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!fe(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!I,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=fe(n)||n===0?n:1,this.ttlAutopurge=!!r,this.ttl=i||0,this.ttl){if(!fe(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}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 W="LRU_CACHE_UNBOUNDED";Ml(W)&&(pr.add(W),mr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",W,yr))}}getRemainingTTL(e){return this.#u.has(e)?1/0:0}#R(){let e=new As(this.#t),s=new As(this.#t);this.#g=e,this.#C=s;let i=this.ttlAutopurge?new Array(this.#t):void 0;this.#w=i,this.#M=(o,a,l=this.#h.now())=>{if(s[o]=a!==0?l:0,e[o]=a,i?.[o]&&(clearTimeout(i[o]),i[o]=void 0),a!==0&&i){let c=setTimeout(()=>{this.#k(o)&&this.#I(this.#l[o],"expire")},a+1);c.unref&&c.unref(),i[o]=c}},this.#_=o=>{s[o]=e[o]!==0?this.#h.now():0},this.#N=(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||r();let d=o.now-c;o.remainingTTL=l-d}};let n=0,r=()=>{let o=this.#h.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.#u.get(o);if(a===void 0)return 0;let l=e[a],c=s[a];if(!l||!c)return 1/0;let d=(n||r())-c;return l-d},this.#k=o=>{let a=s[o],l=e[o];return!!l&&!!a&&(n||r())-a>l}}#_=()=>{};#N=()=>{};#M=()=>{};#k=()=>!1;#G(){let e=new As(this.#t);this.#d=0,this.#T=e,this.#L=s=>{this.#d-=e[s],e[s]=0},this.#B=(s,i,n,r)=>{if(this.#c(i))return 0;if(!fe(n))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(n=r(i,s),!fe(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,i,n)=>{if(e[s]=i,this.#s){let r=this.#s-e[s];for(;this.#d>r;)this.#W(!0)}this.#d+=e[s],n&&(n.entrySize=i,n.totalCalculatedSize=this.#d)}}#L=e=>{};#D=(e,s,i)=>{};#B=(e,s,i,n)=>{if(i||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#a)for(let s=this.#p;!(!this.#j(s)||((e||!this.#k(s))&&(yield s),s===this.#b));)s=this.#S[s]}*#P({allowStale:e=this.allowStale}={}){if(this.#a)for(let s=this.#b;!(!this.#j(s)||((e||!this.#k(s))&&(yield s),s===this.#p));)s=this.#f[s]}#j(e){return e!==void 0&&this.#u.get(this.#l[e])===e}*entries(){for(let e of this.#A())this.#i[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#i[e])&&(yield[this.#l[e],this.#i[e]])}*rentries(){for(let e of this.#P())this.#i[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#i[e])&&(yield[this.#l[e],this.#i[e]])}*keys(){for(let e of this.#A()){let s=this.#l[e];s!==void 0&&!this.#c(this.#i[e])&&(yield s)}}*rkeys(){for(let e of this.#P()){let s=this.#l[e];s!==void 0&&!this.#c(this.#i[e])&&(yield s)}}*values(){for(let e of this.#A())this.#i[e]!==void 0&&!this.#c(this.#i[e])&&(yield this.#i[e])}*rvalues(){for(let e of this.#P())this.#i[e]!==void 0&&!this.#c(this.#i[e])&&(yield this.#i[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,s={}){for(let i of this.#A()){let n=this.#i[i],r=this.#c(n)?n.__staleWhileFetching:n;if(r!==void 0&&e(r,this.#l[i],this))return this.get(this.#l[i],s)}}forEach(e,s=this){for(let i of this.#A()){let n=this.#i[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(s,r,this.#l[i],this)}}rforEach(e,s=this){for(let i of this.#P()){let n=this.#i[i],r=this.#c(n)?n.__staleWhileFetching:n;r!==void 0&&e.call(s,r,this.#l[i],this)}}purgeStale(){let e=!1;for(let s of this.#P({allowStale:!0}))this.#k(s)&&(this.#I(this.#l[s],"expire"),e=!0);return e}info(e){let s=this.#u.get(e);if(s===void 0)return;let i=this.#i[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0)return;let r={value:n};if(this.#g&&this.#C){let o=this.#g[s],a=this.#C[s];if(o&&a){let l=o-(this.#h.now()-a);r.ttl=l,r.start=Date.now()}}return this.#T&&(r.size=this.#T[s]),r}dump(){let e=[];for(let s of this.#A({allowStale:!0})){let i=this.#l[s],n=this.#i[s],r=this.#c(n)?n.__staleWhileFetching:n;if(r===void 0||i===void 0)continue;let o={value:r};if(this.#g&&this.#C){o.ttl=this.#g[s];let a=this.#h.now()-this.#C[s];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[s]),e.unshift([i,o])}return e}load(e){this.clear();for(let[s,i]of e){if(i.start){let n=Date.now()-i.start;i.start=this.#h.now()-n}this.set(s,i.value,i)}}set(e,s,i={}){if(s===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:r,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=i,{noUpdateTTL:c=this.noUpdateTTL}=i,d=this.#B(e,s,i.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#I(e,"set"),this;let h=this.#a===0?void 0:this.#u.get(e);if(h===void 0)h=this.#a===0?this.#p:this.#$.length!==0?this.#$.pop():this.#a===this.#t?this.#W(!1):this.#a,this.#l[h]=e,this.#i[h]=s,this.#u.set(e,h),this.#f[this.#p]=h,this.#S[h]=this.#p,this.#p=h,this.#a++,this.#D(h,d,l),l&&(l.set="add"),c=!1,this.#F&&this.#n?.(s,e,"add");else{this.#O(h);let f=this.#i[h];if(s!==f){if(this.#E&&this.#c(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:y}=f;y!==void 0&&!o&&(this.#v&&this.#r?.(y,e,"set"),this.#e&&this.#m?.push([y,e,"set"]))}else o||(this.#v&&this.#r?.(f,e,"set"),this.#e&&this.#m?.push([f,e,"set"]));if(this.#L(h),this.#D(h,d,l),this.#i[h]=s,l){l.set="replace";let y=f&&this.#c(f)?f.__staleWhileFetching:f;y!==void 0&&(l.oldValue=y)}}else l&&(l.set="update");this.#F&&this.onInsert?.(s,e,s===f?"update":"replace")}if(n!==0&&!this.#g&&this.#R(),this.#g&&(c||this.#M(h,n,r),l&&this.#N(l,h)),!o&&this.#e&&this.#m){let f=this.#m,y;for(;y=f?.shift();)this.#o?.(...y)}return this}pop(){try{for(;this.#a;){let e=this.#i[this.#b];if(this.#W(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#o?.(...s)}}}#W(e){let s=this.#b,i=this.#l[s],n=this.#i[s];return this.#E&&this.#c(n)?n.__abortController.abort(new Error("evicted")):(this.#v||this.#e)&&(this.#v&&this.#r?.(n,i,"evict"),this.#e&&this.#m?.push([n,i,"evict"])),this.#L(s),this.#w?.[s]&&(clearTimeout(this.#w[s]),this.#w[s]=void 0),e&&(this.#l[s]=void 0,this.#i[s]=void 0,this.#$.push(s)),this.#a===1?(this.#b=this.#p=0,this.#$.length=0):this.#b=this.#f[s],this.#u.delete(i),this.#a--,s}has(e,s={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:n}=s,r=this.#u.get(e);if(r!==void 0){let o=this.#i[r];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#k(r))n&&(n.has="stale",this.#N(n,r));else return i&&this.#_(r),n&&(n.has="hit",this.#N(n,r)),!0}else n&&(n.has="miss");return!1}peek(e,s={}){let{allowStale:i=this.allowStale}=s,n=this.#u.get(e);if(n===void 0||!i&&this.#k(n))return;let r=this.#i[n];return this.#c(r)?r.__staleWhileFetching:r}#U(e,s,i,n){let r=s===void 0?void 0:this.#i[s];if(this.#c(r))return r;let o=new Ns,{signal:a}=i;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:i,context:n},c=(w,C=!1)=>{let{aborted:k}=o.signal,E=i.ignoreFetchAbort&&w!==void 0,N=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&w!==void 0);if(i.status&&(k&&!C?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),k&&!E&&!C)return h(o.signal.reason,N);let I=y,P=this.#i[s];return(P===y||E&&C&&P===void 0)&&(w===void 0?I.__staleWhileFetching!==void 0?this.#i[s]=I.__staleWhileFetching:this.#I(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(e,w,l.options))),w},d=w=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=w),h(w,!1)),h=(w,C)=>{let{aborted:k}=o.signal,E=k&&i.allowStaleOnFetchAbort,N=E||i.allowStaleOnFetchRejection,I=N||i.noDeleteOnFetchRejection,P=y;if(this.#i[s]===y&&(!I||!C&&P.__staleWhileFetching===void 0?this.#I(e,"fetch"):E||(this.#i[s]=P.__staleWhileFetching)),N)return i.status&&P.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),P.__staleWhileFetching;if(P.__returned===P)throw w},f=(w,C)=>{let k=this.#x?.(e,r,l);k&&k instanceof Promise&&k.then(E=>w(E===void 0?void 0:E),C),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(w(void 0),i.allowStaleOnFetchAbort&&(w=E=>c(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let y=new Promise(f).then(c,d),g=Object.assign(y,{__abortController:o,__staleWhileFetching:r,__returned:void 0});return s===void 0?(this.set(e,g,{...l.options,status:void 0}),s=this.#u.get(e)):this.#i[s]=g,g}#c(e){if(!this.#E)return!1;let s=e;return!!s&&s instanceof Promise&&s.hasOwnProperty("__staleWhileFetching")&&s.__abortController instanceof Ns}async fetch(e,s={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:y=this.ignoreFetchAbort,allowStaleOnFetchAbort:g=this.allowStaleOnFetchAbort,context:w,forceRefresh:C=!1,status:k,signal:E}=s;if(!this.#E)return k&&(k.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,status:k});let N={allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:r,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:g,ignoreFetchAbort:y,status:k,signal:E},I=this.#u.get(e);if(I===void 0){k&&(k.fetch="miss");let P=this.#U(e,I,N,w);return P.__returned=P}else{let P=this.#i[I];if(this.#c(P)){let F=i&&P.__staleWhileFetching!==void 0;return k&&(k.fetch="inflight",F&&(k.returnedStale=!0)),F?P.__staleWhileFetching:P.__returned=P}let tt=this.#k(I);if(!C&&!tt)return k&&(k.fetch="hit"),this.#O(I),n&&this.#_(I),k&&this.#N(k,I),P;let m=this.#U(e,I,N,w),S=m.__staleWhileFetching!==void 0&&i;return k&&(k.fetch=tt?"stale":"refresh",S&&tt&&(k.returnedStale=!0)),S?m.__staleWhileFetching:m.__returned=m}}async forceFetch(e,s={}){let i=await this.fetch(e,s);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(e,s={}){let i=this.#y;if(!i)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:r,...o}=s,a=this.get(e,o);if(!r&&a!==void 0)return a;let l=i(e,a,{options:o,context:n});return this.set(e,l,o),l}get(e,s={}){let{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:o}=s,a=this.#u.get(e);if(a!==void 0){let l=this.#i[a],c=this.#c(l);return o&&this.#N(o,a),this.#k(a)?(o&&(o.get="stale"),c?(o&&i&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),i?l.__staleWhileFetching:void 0):(r||this.#I(e,"expire"),o&&i&&(o.returnedStale=!0),i?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#O(a),n&&this.#_(a),l))}else o&&(o.get="miss")}#z(e,s){this.#S[s]=e,this.#f[e]=s}#O(e){e!==this.#p&&(e===this.#b?this.#b=this.#f[e]:this.#z(this.#S[e],this.#f[e]),this.#z(this.#p,e),this.#p=e)}delete(e){return this.#I(e,"delete")}#I(e,s){let i=!1;if(this.#a!==0){let n=this.#u.get(e);if(n!==void 0)if(this.#w?.[n]&&(clearTimeout(this.#w?.[n]),this.#w[n]=void 0),i=!0,this.#a===1)this.#H(s);else{this.#L(n);let r=this.#i[n];if(this.#c(r)?r.__abortController.abort(new Error("deleted")):(this.#v||this.#e)&&(this.#v&&this.#r?.(r,e,s),this.#e&&this.#m?.push([r,e,s])),this.#u.delete(e),this.#l[n]=void 0,this.#i[n]=void 0,n===this.#p)this.#p=this.#S[n];else if(n===this.#b)this.#b=this.#f[n];else{let o=this.#S[n];this.#f[o]=this.#f[n];let a=this.#f[n];this.#S[a]=this.#S[n]}this.#a--,this.#$.push(n)}}if(this.#e&&this.#m?.length){let n=this.#m,r;for(;r=n?.shift();)this.#o?.(...r)}return i}clear(){return this.#H("delete")}#H(e){for(let s of this.#P({allowStale:!0})){let i=this.#i[s];if(this.#c(i))i.__abortController.abort(new Error("deleted"));else{let n=this.#l[s];this.#v&&this.#r?.(i,n,e),this.#e&&this.#m?.push([i,n,e])}}if(this.#u.clear(),this.#i.fill(void 0),this.#l.fill(void 0),this.#g&&this.#C){this.#g.fill(0),this.#C.fill(0);for(let s of this.#w??[])s!==void 0&&clearTimeout(s);this.#w?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#b=0,this.#p=0,this.#$.length=0,this.#d=0,this.#a=0,this.#e&&this.#m){let s=this.#m,i;for(;i=s?.shift();)this.#o?.(...i)}}},Un=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ql=t=>!!t&&typeof t=="object"&&(t instanceof Fs||t instanceof wr||tc(t)||ec(t)),tc=t=>!!t&&typeof t=="object"&&t instanceof $i&&typeof t.pipe=="function"&&t.pipe!==wr.Writable.prototype.pipe,ec=t=>!!t&&typeof t=="object"&&t instanceof $i&&typeof t.write=="function"&&typeof t.end=="function",re=Symbol("EOF"),oe=Symbol("maybeEmitEnd"),de=Symbol("emittedEnd"),ks=Symbol("emittingEnd"),Ye=Symbol("emittedError"),Ts=Symbol("closed"),zn=Symbol("read"),Cs=Symbol("flush"),Gn=Symbol("flushChunk"),qt=Symbol("encoding"),Fe=Symbol("decoder"),yt=Symbol("flowing"),Je=Symbol("paused"),De=Symbol("resume"),wt=Symbol("buffer"),_t=Symbol("pipes"),bt=Symbol("bufferLength"),yi=Symbol("bufferPush"),Es=Symbol("bufferShift"),Ct=Symbol("objectMode"),ft=Symbol("destroyed"),wi=Symbol("error"),bi=Symbol("emitData"),Hn=Symbol("emitEnd"),xi=Symbol("emitEnd2"),Zt=Symbol("async"),Si=Symbol("abort"),_s=Symbol("aborted"),Ve=Symbol("signal"),xe=Symbol("dataListeners"),Ot=Symbol("discarded"),Ke=t=>Promise.resolve().then(t),sc=t=>t(),ic=t=>t==="end"||t==="finish"||t==="prefinish",nc=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,rc=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),br=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[De](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},oc=class extends br{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},ac=t=>!!t.objectMode,lc=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Fs=class extends $i{[yt]=!1;[Je]=!1;[_t]=[];[wt]=[];[Ct];[qt];[Zt];[Fe];[re]=!1;[de]=!1;[ks]=!1;[Ts]=!1;[Ye]=null;[bt]=0;[ft]=!1;[Ve];[_s]=!1;[xe]=0;[Ot]=!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");ac(e)?(this[Ct]=!0,this[qt]=null):lc(e)?(this[qt]=e.encoding,this[Ct]=!1):(this[Ct]=!1,this[qt]=null),this[Zt]=!!e.async,this[Fe]=this[qt]?new Zl(this[qt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[wt]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[_t]});let{signal:s}=e;s&&(this[Ve]=s,s.aborted?this[Si]():s.addEventListener("abort",()=>this[Si]()))}get bufferLength(){return this[bt]}get encoding(){return this[qt]}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[Ct]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Zt]}set async(t){this[Zt]=this[Zt]||!!t}[Si](){this[_s]=!0,this.emit("abort",this[Ve]?.reason),this.destroy(this[Ve]?.reason)}get aborted(){return this[_s]}set aborted(t){}write(t,e,s){if(this[_s])return!1;if(this[re])throw new Error("write after end");if(this[ft])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 i=this[Zt]?Ke:sc;if(!this[Ct]&&!Buffer.isBuffer(t)){if(rc(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(nc(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ct]?(this[yt]&&this[bt]!==0&&this[Cs](!0),this[yt]?this.emit("data",t):this[yi](t),this[bt]!==0&&this.emit("readable"),s&&i(s),this[yt]):t.length?(typeof t=="string"&&!(e===this[qt]&&!this[Fe]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[qt]&&(t=this[Fe].write(t)),this[yt]&&this[bt]!==0&&this[Cs](!0),this[yt]?this.emit("data",t):this[yi](t),this[bt]!==0&&this.emit("readable"),s&&i(s),this[yt]):(this[bt]!==0&&this.emit("readable"),s&&i(s),this[yt])}read(t){if(this[ft])return null;if(this[Ot]=!1,this[bt]===0||t===0||t&&t>this[bt])return this[oe](),null;this[Ct]&&(t=null),this[wt].length>1&&!this[Ct]&&(this[wt]=[this[qt]?this[wt].join(""):Buffer.concat(this[wt],this[bt])]);let e=this[zn](t||null,this[wt][0]);return this[oe](),e}[zn](t,e){if(this[Ct])this[Es]();else{let s=e;t===s.length||t===null?this[Es]():typeof s=="string"?(this[wt][0]=s.slice(t),e=s.slice(0,t),this[bt]-=t):(this[wt][0]=s.subarray(t),e=s.subarray(0,t),this[bt]-=t)}return this.emit("data",e),!this[wt].length&&!this[re]&&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[re]=!0,this.writable=!1,(this[yt]||!this[Je])&&this[oe](),this}[De](){this[ft]||(!this[xe]&&!this[_t].length&&(this[Ot]=!0),this[Je]=!1,this[yt]=!0,this.emit("resume"),this[wt].length?this[Cs]():this[re]?this[oe]():this.emit("drain"))}resume(){return this[De]()}pause(){this[yt]=!1,this[Je]=!0,this[Ot]=!1}get destroyed(){return this[ft]}get flowing(){return this[yt]}get paused(){return this[Je]}[yi](t){this[Ct]?this[bt]+=1:this[bt]+=t.length,this[wt].push(t)}[Es](){return this[Ct]?this[bt]-=1:this[bt]-=this[wt][0].length,this[wt].shift()}[Cs](t=!1){do;while(this[Gn](this[Es]())&&this[wt].length);!t&&!this[wt].length&&!this[re]&&this.emit("drain")}[Gn](t){return this.emit("data",t),this[yt]}pipe(t,e){if(this[ft])return t;this[Ot]=!1;let s=this[de];return e=e||{},t===Un.stdout||t===Un.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[_t].push(e.proxyErrors?new oc(this,t,e):new br(this,t,e)),this[Zt]?Ke(()=>this[De]()):this[De]()),t}unpipe(t){let e=this[_t].find(s=>s.dest===t);e&&(this[_t].length===1?(this[yt]&&this[xe]===0&&(this[yt]=!1),this[_t]=[]):this[_t].splice(this[_t].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[Ot]=!1,this[xe]++,!this[_t].length&&!this[yt]&&this[De]();else if(t==="readable"&&this[bt]!==0)super.emit("readable");else if(ic(t)&&this[de])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ye]){let i=e;this[Zt]?Ke(()=>i.call(this,this[Ye])):i.call(this,this[Ye])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[xe]=this.listeners("data").length,this[xe]===0&&!this[Ot]&&!this[_t].length&&(this[yt]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[xe]=0,!this[Ot]&&!this[_t].length&&(this[yt]=!1)),e}get emittedEnd(){return this[de]}[oe](){!this[ks]&&!this[de]&&!this[ft]&&this[wt].length===0&&this[re]&&(this[ks]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ts]&&this.emit("close"),this[ks]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==ft&&this[ft])return!1;if(t==="data")return!this[Ct]&&!s?!1:this[Zt]?(Ke(()=>this[bi](s)),!0):this[bi](s);if(t==="end")return this[Hn]();if(t==="close"){if(this[Ts]=!0,!this[de]&&!this[ft])return!1;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Ye]=s,super.emit(wi,s);let n=!this[Ve]||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 i=super.emit(t,...e);return this[oe](),i}[bi](t){for(let s of this[_t])s.dest.write(t)===!1&&this.pause();let e=this[Ot]?!1:super.emit("data",t);return this[oe](),e}[Hn](){return this[de]?!1:(this[de]=!0,this.readable=!1,this[Zt]?(Ke(()=>this[xi]()),!0):this[xi]())}[xi](){if(this[Fe]){let e=this[Fe].end();if(e){for(let s of this[_t])s.dest.write(e);this[Ot]||super.emit("data",e)}}for(let e of this[_t])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ct]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[Ct]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[Ct])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[qt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ft,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[Ot]=!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[re])return e();let i,n,r=c=>{this.off("data",o),this.off("end",a),this.off(ft,l),e(),n(c)},o=c=>{this.off("error",r),this.off("end",a),this.off(ft,l),this.pause(),i({value:c,done:!!this[re]})},a=()=>{this.off("error",r),this.off("data",o),this.off(ft,l),e(),i({done:!0,value:void 0})},l=()=>r(new Error("stream destroyed"));return new Promise((c,d)=>{n=d,i=c,this.once(ft,l),this.once("error",r),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[Ot]=!1;let t=!1,e=()=>(this.pause(),this.off(wi,e),this.off(ft,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(wi,e),this.once(ft,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ft])return t?this.emit("error",t):this.emit(ft),this;this[ft]=!0,this[Ot]=!0,this[wt].length=0,this[bt]=0;let e=this;return typeof e.close=="function"&&!this[Ts]&&e.close(),t?this.emit("error",t):this.emit(ft),this}static get isStream(){return Ql}},cc=ql.native,es={lstatSync:Ul,readdir:zl,readdirSync:Gl,readlinkSync:Hl,realpathSync:cc,promises:{lstat:Yl,readdir:Jl,readlink:Vl,realpath:Kl}},xr=t=>!t||t===es||t===Xl?es:{...es,...t,promises:{...es.promises,...t.promises||{}}},Sr=/^\\\\\?\\([a-z]:)\\?$/i,hc=t=>t.replace(/\//g,"\\").replace(Sr,"$1\\"),uc=/[\\\/]/,Wt=0,vr=1,kr=2,Qt=4,Tr=6,Cr=8,Se=10,Er=12,jt=15,Ze=~jt,vi=16,qn=32,ss=64,Xt=128,$s=256,Ps=512,Xn=ss|Xt|Ps,dc=1023,ki=t=>t.isFile()?Cr:t.isDirectory()?Qt:t.isSymbolicLink()?Se:t.isCharacterDevice()?kr:t.isBlockDevice()?Tr:t.isSocket()?Er:t.isFIFO()?vr:Wt,Yn=new Ds({max:2**12}),is=t=>{let e=Yn.get(t);if(e)return e;let s=t.normalize("NFKD");return Yn.set(t,s),s},Jn=new Ds({max:2**12}),Is=t=>{let e=Jn.get(t);if(e)return e;let s=is(t.toLowerCase());return Jn.set(t,s),s},Vn=class extends Ds{constructor(){super({max:256})}},fc=class extends Ds{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},_r=Symbol("PathScurry setAsCwd"),Rt=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#r;get mode(){return this.#r}#n;get nlink(){return this.#n}#o;get uid(){return this.#o}#x;get gid(){return this.#x}#y;get rdev(){return this.#y}#h;get blksize(){return this.#h}#a;get ino(){return this.#a}#d;get size(){return this.#d}#u;get blocks(){return this.#u}#l;get atimeMs(){return this.#l}#i;get mtimeMs(){return this.#i}#f;get ctimeMs(){return this.#f}#S;get birthtimeMs(){return this.#S}#b;get atime(){return this.#b}#p;get mtime(){return this.#p}#$;get ctime(){return this.#$}#m;get birthtime(){return this.#m}#T;#C;#g;#w;#v;#E;#e;#F;#R;#_;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=Wt,s,i,n,r,o){this.name=t,this.#T=n?Is(t):is(t),this.#e=e&dc,this.nocase=n,this.roots=i,this.root=s||this,this.#F=r,this.#g=o.fullpath,this.#v=o.relative,this.#E=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=xr(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).#N(s):this.#N(s)}#N(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&=~vi,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?Is(t):is(t);for(let a of s)if(a.#T===i)return a;let n=this.parent?this.sep:"",r=this.#g?this.#g+n+t:void 0,o=this.newChild(t,Wt,{...e,parent:this,fullpath:r});return this.canReaddir()||(o.#e|=Xt),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#v!==void 0)return this.#v;let t=this.name,e=this.parent;if(!e)return this.#v=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.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let s=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=s}fullpathPosix(){if(this.#w!==void 0)return this.#w;if(this.sep==="/")return this.#w=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#w=`//?/${i}`:this.#w=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#w=s}isUnknown(){return(this.#e&jt)===Wt}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&jt)===Cr}isDirectory(){return(this.#e&jt)===Qt}isCharacterDevice(){return(this.#e&jt)===kr}isBlockDevice(){return(this.#e&jt)===Tr}isFIFO(){return(this.#e&jt)===vr}isSocket(){return(this.#e&jt)===Er}isSymbolicLink(){return(this.#e&Se)===Se}lstatCached(){return this.#e&qn?this:void 0}readlinkCached(){return this.#R}realpathCached(){return this.#_}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#R)return!0;if(!this.parent)return!1;let t=this.#e&jt;return!(t!==Wt&&t!==Se||this.#e&$s||this.#e&Xt)}calledReaddir(){return!!(this.#e&vi)}isENOENT(){return!!(this.#e&Xt)}isNamed(t){return this.nocase?this.#T===Is(t):this.#T===is(t)}async readlink(){let t=this.#R;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.#R=s}catch(e){this.#P(e.code);return}}readlinkSync(){let t=this.#R;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.#R=s}catch(e){this.#P(e.code);return}}#M(t){this.#e|=vi;for(let e=t.provisional;e<t.length;e++){let s=t[e];s&&s.#k()}}#k(){this.#e&Xt||(this.#e=(this.#e|Xt)&Ze,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#k()}#L(){this.#e|=Ps,this.#D()}#D(){if(this.#e&ss)return;let t=this.#e;(t&jt)===Qt&&(t&=Ze),this.#e=t|ss,this.#G()}#B(t=""){t==="ENOTDIR"||t==="EPERM"?this.#D():t==="ENOENT"?this.#k():this.children().provisional=0}#A(t=""){t==="ENOTDIR"?this.parent.#D():t==="ENOENT"&&this.#k()}#P(t=""){let e=this.#e;e|=$s,t==="ENOENT"&&(e|=Xt),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Ze),this.#e=e,t==="ENOTDIR"&&this.parent&&this.parent.#D()}#j(t,e){return this.#U(t,e)||this.#W(t,e)}#W(t,e){let s=ki(t),i=this.newChild(t.name,s,{parent:this}),n=i.#e&jt;return n!==Qt&&n!==Se&&n!==Wt&&(i.#e|=ss),e.unshift(i),e.provisional++,i}#U(t,e){for(let s=e.provisional;s<e.length;s++){let i=e[s];if((this.nocase?Is(t.name):is(t.name))===i.#T)return this.#c(t,i,s,e)}}#c(t,e,s,i){let n=e.name;return e.#e=e.#e&Ze|ki(t),n!==t.name&&(e.name=t.name),s!==i.provisional&&(s===i.length-1?i.pop():i.splice(s,1),i.unshift(e)),i.provisional++,e}async lstat(){if((this.#e&Xt)===0)try{return this.#z(await this.#t.promises.lstat(this.fullpath())),this}catch(t){this.#A(t.code)}}lstatSync(){if((this.#e&Xt)===0)try{return this.#z(this.#t.lstatSync(this.fullpath())),this}catch(t){this.#A(t.code)}}#z(t){let{atime:e,atimeMs:s,birthtime:i,birthtimeMs:n,blksize:r,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:d,ino:h,mode:f,mtime:y,mtimeMs:g,nlink:w,rdev:C,size:k,uid:E}=t;this.#b=e,this.#l=s,this.#m=i,this.#S=n,this.#h=r,this.#u=o,this.#$=a,this.#f=l,this.#s=c,this.#x=d,this.#a=h,this.#r=f,this.#p=y,this.#i=g,this.#n=w,this.#y=C,this.#d=k,this.#o=E;let N=ki(t);this.#e=this.#e&Ze|N|qn,N!==Wt&&N!==Qt&&N!==Se&&(this.#e|=ss)}#O=[];#I=!1;#H(t){this.#I=!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.#I)return;this.#I=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(n,r)=>{if(n)this.#B(n.code),s.provisional=0;else{for(let o of r)this.#j(o,s);this.#M(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(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#j(i,t);this.#M(t)}catch(i){this.#B(i.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.#j(s,t);this.#M(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Xn)return!1;let t=jt&this.#e;return t===Wt||t===Qt||t===Se}shouldWalk(t,e){return(this.#e&Qt)===Qt&&!(this.#e&Xn)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#_)return this.#_;if(!((Ps|$s|Xt)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#_=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#_)return this.#_;if(!((Ps|$s|Xt)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#_=this.resolve(t)}catch{this.#L()}}[_r](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#v=s.join(this.sep),i.#E=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#v=void 0,i.#E=void 0,i=i.parent}},$r=class Ir extends Rt{sep="\\";splitSep=uc;constructor(e,s=Wt,i,n,r,o,a){super(e,s,i,n,r,o,a)}newChild(e,s=Wt,i={}){return new Ir(e,s,this.root,this.roots,this.nocase,this.childrenCache(),i)}getRootString(e){return Ci.parse(e).root}getRoot(e){if(e=hc(e.toUpperCase()),e===this.root.name)return this.root;for(let[s,i]of Object.entries(this.roots))if(this.sameRoot(e,s))return this.roots[e]=i;return this.roots[e]=new Ii(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Sr,"$1\\"),e===s}},Ar=class Pr extends Rt{splitSep="/";sep="/";constructor(e,s=Wt,i,n,r,o,a){super(e,s,i,n,r,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,s=Wt,i={}){return new Pr(e,s,this.root,this.roots,this.nocase,this.childrenCache(),i)}},Rr=class{root;rootPath;roots;cwd;#t;#s;#r;nocase;#n;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:n=16*1024,fs:r=es}={}){this.#n=xr(r),(t instanceof URL||t.startsWith("file://"))&&(t=Wl(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new Vn,this.#s=new Vn,this.#r=new fc(n);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,d=e.sep,h=this.rootPath,f=!1;for(let y of a){let g=c--;l=l.child(y,{relative:new Array(g).fill("..").join(d),relativePosix:new Array(g).fill("..").join("/"),fullpath:h+=(f?"":d)+y}),f=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#r}resolve(...t){let e="";for(let n=t.length-1;n>=0;n--){let r=t[n];if(!(!r||r===".")&&(e=e?`${r}/${e}`:r,this.isAbsolute(r)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let n=t.length-1;n>=0;n--){let r=t[n];if(!(!r||r===".")&&(e=e?`${r}/${e}`:r,this.isAbsolute(r)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}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 Rt||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(n=>n.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.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 Rt||(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 Rt||(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 Rt||(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 Rt||(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 Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:r}=e,o=[];(!n||n(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(d,h)=>{a.add(d),d.readdirCB((f,y)=>{if(f)return h(f);let g=y.length;if(!g)return h();let w=()=>{--g===0&&h()};for(let C of y)(!n||n(C))&&o.push(s?C:C.fullpath()),i&&C.isSymbolicLink()?C.realpath().then(k=>k?.isUnknown()?k.lstat():k).then(k=>k?.shouldWalk(a,r)?l(k,w):w()):C.shouldWalk(a,r)?l(C,w):w()},!0)},c=t;return new Promise((d,h)=>{l(c,f=>{if(f)return h(f);d(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:r}=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 d of c){(!n||n(d))&&o.push(s?d:d.fullpath());let h=d;if(d.isSymbolicLink()){if(!(i&&(h=d.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,r)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof Rt||(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 Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:r}=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 d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(o,r)&&o.add(d)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:r}=e,o=new Fs({objectMode:!0});(!n||n(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],c=0,d=()=>{let h=!1;for(;!h;){let f=l.shift();if(!f){c===0&&o.end();return}c++,a.add(f);let y=(w,C,k=!1)=>{if(w)return o.emit("error",w);if(i&&!k){let E=[];for(let N of C)N.isSymbolicLink()&&E.push(N.realpath().then(I=>I?.isUnknown()?I.lstat():I));if(E.length){Promise.all(E).then(()=>y(null,C,!0));return}}for(let E of C)E&&(!n||n(E))&&(o.write(s?E:E.fullpath())||(h=!0));c--;for(let E of C){let N=E.realpathCached()||E;N.shouldWalk(a,r)&&l.push(N)}h&&!o.flowing?o.once("drain",d):g||d()},g=!0;f.readdirCB(y,!0),g=!1}};return d(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof Rt||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:n,walkFilter:r}=e,o=new Fs({objectMode:!0}),a=new Set;(!n||n(t))&&o.write(s?t:t.fullpath());let l=[t],c=0,d=()=>{let h=!1;for(;!h;){let f=l.shift();if(!f){c===0&&o.end();return}c++,a.add(f);let y=f.readdirSync();for(let g of y)(!n||n(g))&&(o.write(s?g:g.fullpath())||(h=!0));c--;for(let g of y){let w=g;if(g.isSymbolicLink()){if(!(i&&(w=g.realpathSync())))continue;w.isUnknown()&&w.lstatSync()}w.shouldWalk(a,r)&&l.push(w)}}h&&!o.flowing&&o.once("drain",d)};return d(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[_r](e)}},Ii=class extends Rr{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,Ci,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Ci.parse(t).root.toUpperCase()}newRoot(t){return new $r(this.rootPath,Qt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Ai=class extends Rr{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,jl,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new Ar(this.rootPath,Qt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Nr=class extends Ai{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}},Su=process.platform==="win32"?$r:Ar,pc=process.platform==="win32"?Ii:process.platform==="darwin"?Nr:Ai,mc=t=>t.length>=1,gc=t=>t.length>=1,yc=Symbol.for("nodejs.util.inspect.custom"),Fr=class Dr{#t;#s;#r;length;#n;#o;#x;#y;#h;#a;#d=!0;constructor(e,s,i,n){if(!mc(e))throw new TypeError("empty pattern list");if(!gc(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,i<0||i>=this.length)throw new TypeError("index out of range");if(this.#t=e,this.#s=s,this.#r=i,this.#n=n,this.#r===0){if(this.isUNC()){let[r,o,a,l,...c]=this.#t,[d,h,f,y,...g]=this.#s;c[0]===""&&(c.shift(),g.shift());let w=[r,o,a,l,""].join("/"),C=[d,h,f,y,""].join("/");this.#t=[w,...c],this.#s=[C,...g],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...o]=this.#t,[a,...l]=this.#s;o[0]===""&&(o.shift(),l.shift());let c=r+"/",d=a+"/";this.#t=[c,...o],this.#s=[d,...l],this.length=this.#t.length}}}[yc](){return"Pattern <"+this.#s.slice(this.#r).join("/")+">"}pattern(){return this.#t[this.#r]}isString(){return typeof this.#t[this.#r]=="string"}isGlobstar(){return this.#t[this.#r]===$t}isRegExp(){return this.#t[this.#r]instanceof RegExp}globString(){return this.#x=this.#x||(this.#r===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#r).join("/"))}hasMore(){return this.length>this.#r+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new Dr(this.#t,this.#s,this.#r+1,this.#n),this.#o.#a=this.#a,this.#o.#h=this.#h,this.#o.#y=this.#y,this.#o):this.#o=null}isUNC(){let e=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#n==="win32"&&this.#r===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#t;return this.#y!==void 0?this.#y:this.#y=this.#n==="win32"&&this.#r===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.#r===0?e:""}checkFollowGlobstar(){return!(this.#r===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#r===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},wc=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Kn=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:n,platform:r=wc}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=r,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:n,optimizationLevel:2,platform:r,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new pe(t,this.mmopts);for(let s=0;s<e.set.length;s++){let i=e.set[s],n=e.globParts[s];if(!i||!n)throw new Error("invalid pattern object");for(;i[0]==="."&&n[0]===".";)i.shift(),n.shift();let r=new Fr(i,n,0,this.platform),o=new pe(r.globString(),this.mmopts),a=n[n.length-1]==="**",l=r.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}/`,i=t.relative()||".",n=`${i}/`;for(let r of this.relative)if(r.match(i)||r.match(n))return!0;for(let r of this.absolute)if(r.match(e)||r.match(s))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",s=(t.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(s))return!0;for(let i of this.absoluteChildren)if(i.match(e))return!0;return!1}},bc=class Or{store;constructor(e=new Map){this.store=e}copy(){return new Or(new Map(this.store))}hasWalked(e,s){return this.store.get(e.fullpath())?.has(s.globString())}storeWalked(e,s){let i=e.fullpath(),n=this.store.get(i);n?n.add(s.globString()):this.store.set(i,new Set([s.globString()]))}},xc=class{store=new Map;add(t,e,s){let i=(e?2:0)|(s?1:0),n=this.store.get(t);this.store.set(t,n===void 0?i:i&n)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},Sc=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.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())}},Zn=class Lr{hasWalkedCache;matches=new xc;subwalks=new Sc;patterns;follow;dot;opts;constructor(e,s){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=s?s.copy():new bc}processPatterns(e,s){this.patterns=s;let i=s.map(n=>[e,n]);for(let[n,r]of i){this.hasWalkedCache.storeWalked(n,r);let o=r.root(),a=r.isAbsolute()&&this.opts.absolute!==!1;if(o){n=n.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=r.rest();if(h)r=h;else{this.matches.add(n,!0,!1);continue}}if(n.isENOENT())continue;let l,c,d=!1;for(;typeof(l=r.pattern())=="string"&&(c=r.rest());)n=n.resolve(l),r=c,d=!0;if(l=r.pattern(),c=r.rest(),d){if(this.hasWalkedCache.hasWalked(n,r))continue;this.hasWalkedCache.storeWalked(n,r)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(n.resolve(l),a,h);continue}else if(l===$t){(!n.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(n,r);let h=c?.pattern(),f=c?.rest();if(!c||(h===""||h===".")&&!f)this.matches.add(n,a,h===""||h===".");else if(h===".."){let y=n.parent||n;f?this.hasWalkedCache.hasWalked(y,f)||this.subwalks.add(y,f):this.matches.add(y,a,!0)}}else l instanceof RegExp&&this.subwalks.add(n,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Lr(this.opts,this.hasWalkedCache)}filterEntries(e,s){let i=this.subwalks.get(e),n=this.child();for(let r of s)for(let o of i){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===$t?n.testGlobstar(r,o,c,a):l instanceof RegExp?n.testRegExp(r,l,c,a):n.testString(r,l,c,a)}return n}testGlobstar(e,s,i,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()&&(i&&s.checkFollowGlobstar()?this.subwalks.add(e,i):s.markFollowGlobstar()&&this.subwalks.add(e,s)))),i){let r=i.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(e,r,i.rest(),n);else if(r===".."){let o=e.parent||e;this.subwalks.add(o,i)}else r instanceof RegExp&&this.testRegExp(e,r,i.rest(),n)}}testRegExp(e,s,i,n){s.test(e.name)&&(i?this.subwalks.add(e,i):this.matches.add(e,n,!1))}testString(e,s,i,n){e.isNamed(s)&&(i?this.subwalks.add(e,i):this.matches.add(e,n,!1))}},vc=(t,e)=>typeof t=="string"?new Kn([t],e):Array.isArray(t)?new Kn(t,e):t,Mr=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#r;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#r=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=vc(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}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 i=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let n=await i.realpath();n&&(n.isUnknown()||this.opts.stat)&&await n.lstat()}return this.matchCheckTest(i,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 i=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let n=i.realpathSync();n&&(n?.isUnknown()||this.opts.stat)&&n.lstatSync()}return this.matchCheckTest(i,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 i=this.opts.mark&&t.isDirectory()?this.#r:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let n=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(n+i)}else{let n=this.opts.posix?t.relativePosix():t.relative(),r=this.opts.dotRelative&&!n.startsWith(".."+this.#r)?"."+this.#r:"";this.matchEmit(n?r+n+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Zn(this.opts),s)}walkCB2(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let n=1,r=()=>{--n===0&&i()};for(let[o,a,l]of s.matches.entries())this.#n(o)||(n++,this.match(o,a,l).then(()=>r()));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,r):o.readdirCB((l,c)=>this.walkCB3(o,c,s,r),!0)}r()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let n=1,r=()=>{--n===0&&i()};for(let[o,a,l]of s.matches.entries())this.#n(o)||(n++,this.match(o,a,l).then(()=>r()));for(let[o,a]of s.subwalks.entries())n++,this.walkCB2(o,a,s.child(),r);r()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Zn(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#o(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let n=1,r=()=>{--n===0&&i()};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,r)}r()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let n=1,r=()=>{--n===0&&i()};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(),r);r()}},Qn=class extends Mr{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}},tr=class extends Mr{results;constructor(t,e,s){super(t,e,s),this.results=new Fs({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}},kc=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ve=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=Ol(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||kc,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"?Ii:e.platform==="darwin"?Nr:e.platform?Ai:pc;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",i={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 pe(a,i)),[r,o]=n.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=r.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Fr(a,c,0,this.platform)})}async walk(){return[...await new Qn(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 Qn(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 tr(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 tr(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()}},Tc=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let s of t)if(new pe(s,e).hasMagic())return!0;return!1};function Os(t,e={}){return new ve(t,e).streamSync()}function Br(t,e={}){return new ve(t,e).stream()}function jr(t,e={}){return new ve(t,e).walkSync()}async function er(t,e={}){return new ve(t,e).walk()}function Ls(t,e={}){return new ve(t,e).iterateSync()}function Wr(t,e={}){return new ve(t,e).iterate()}var Cc=Os,Ec=Object.assign(Br,{sync:Os}),_c=Ls,$c=Object.assign(Wr,{sync:Ls}),Ic=Object.assign(jr,{stream:Os,iterate:Ls}),Le=Object.assign(er,{glob:er,globSync:jr,sync:Ic,globStream:Br,stream:Ec,globStreamSync:Os,streamSync:Cc,globIterate:Wr,iterate:$c,globIterateSync:Ls,iterateSync:_c,Glob:ve,hasMagic:Tc,escape:cr,unescape:Oe});Le.glob=Le;var Ms=Rc(Ac);async function Nc(t){try{return await Ms(t,["--version"],{timeout:5e3}),!0}catch{return!1}}async function Fc(t){try{return await Ms("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3}),!0}catch{return!1}}function Dc(t,e){let s=[],i=t.split(`
27
- `).filter(Boolean);for(let n of i){let r=n.match(/^(.+?)[:-](\d+)[:-](.*)$/),[,o,a,l]=r??[];o&&a&&l!==void 0&&s.push({file:Ur.isAbsolute(o)?o:Ur.join(e,o),line:Number.parseInt(a,10),content:l.slice(0,500)})}return s}var zr=async t=>{let e=t.path?Dt(t.path):process.cwd(),s=Math.min(t.limit??100,500),i=t.context_lines??0;try{let n="",r="native";if(await Nc("rg")){r="ripgrep";let a=["--line-number","--no-heading","--color=never",`--max-count=${s}`];i>0&&a.push(`-C${i}`),t.include&&a.push(`--glob=${t.include}`),a.push("--",t.pattern,e);try{n=(await Ms("rg",a,{timeout:qe,maxBuffer:He})).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 Fc(e)){r="git-grep";let a=["grep","-n","--no-color",`-m${s}`];i>0&&a.push(`-C${i}`),a.push("-e",t.pattern);try{n=(await Ms("git",a,{cwd:e,timeout:qe,maxBuffer:He})).stdout}catch(l){if(l.code===1)n="";else throw l}}else{r="native";let a=[],l=new RegExp(t.pattern,"gi"),c=t.include||"**/*",d=await Le(c,{cwd:e,nodir:!0,absolute:!0}),h=await xs(e);d=Ss(d,e,h);for(let f of d){if(a.length>=s)break;try{let g=(await Pc.readFile(f,"utf-8")).split(`
28
- `);for(let[w,C]of g.entries()){if(a.length>=s)break;l.test(C)&&(a.push({file:f,line:w+1,content:C.slice(0,500)}),l.lastIndex=0)}}catch{}}return{success:!0,matches:a,tool:r,total:a.length}}let o=Dc(n,e).slice(0,s);return{success:!0,matches:o,tool:r,total:o.length}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to search file contents"}}};import Oc from"fs/promises";var Gr=async t=>{try{let e=await Mt(t.path);return{success:!0,entries:(await Oc.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 Bs from"fs/promises";import Lc from"path";var Hr=async t=>{try{let e=await Mt(t.source),s=Dt(t.destination);await Bs.mkdir(Lc.dirname(s),{recursive:!0});try{await Bs.rename(e,s)}catch(i){if(i.code!=="EXDEV")throw i;await Bs.cp(e,s,{recursive:!0}),await Bs.rm(e,{recursive:!0})}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to move file"}}};import Pi from"fs/promises";var qr=async t=>{try{let e=await Mt(t.path),s=await bs(e);if(s.type==="binary"){let d=await Pi.stat(e);if(d.size>Ne){let y=Math.round(d.size/1024/1024),g=Math.round(Ne/1024/1024);return{success:!1,error:`Binary file too large (${y}MB). Maximum size is ${g}MB.`}}let f=(await Pi.readFile(e)).toString("base64");return{success:!0,type:"binary",mimeType:s.mimeType,content:f,size:d.size,encoding:"base64"}}let n=(await Pi.readFile(e,"utf-8")).split(`
29
- `),r=n.length,o=Math.max(1,t.start_line??1),a=Math.min(r,t.end_line??o+499),c=n.slice(o-1,a).join(`
30
- `);return{success:!0,type:"text",content:ne(c),lines:{total:r,start:o,end:Math.min(a,r)},truncated:c.length>pi}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to read file"}}};import Ni from"fs/promises";function Xr(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 Mc(t){let e=Xr(t);return e==="EPERM"||e==="EACCES"}function Ri(t){let e=t instanceof Error?t.message:String(t);switch(Xr(t)){case"EACCES":case"EPERM":return`${e}
31
- 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}
32
- The path does not exist.`;case"ENOTDIR":return`${e}
33
- A component of the path is not a directory.`;case"EISDIR":return`${e}
34
- The path is a directory, not a file.`;default:return e}}function Yr(t,e){return async s=>{let i=await t(s);return!i.success&&typeof i.error=="string"?(Mc(i.error)&&e?.(i.error),{...i,error:Ri(i.error)}):i}}async function Bc(t){let e=await Mt(t),s=await bs(e);if(s.type!=="binary")return ne(await Ni.readFile(e,"utf-8"),Tn);let i=await Ni.stat(e);if(i.size>Ne){let r=Math.round(i.size/1024/1024),o=Math.round(Ne/1024/1024);return{error:`Binary file too large (${r}MB). Maximum size is ${o}MB.`}}let n=await Ni.readFile(e);return{type:"binary",mimeType:s.mimeType,content:n.toString("base64"),size:i.size,encoding:"base64"}}var Jr=async t=>{try{let e=t.paths.slice(0,En),s={};return await Promise.all(e.map(async i=>{try{s[i]=await Bc(i)}catch(n){let r=n instanceof Error?n.message:"Failed to read file";s[i]={error:Ri(r)}}})),{success:!0,files:s}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to read files"}}};var Vr=async t=>{try{let e=t.path?Dt(t.path):process.cwd(),s=t.respect_gitignore??!0,i=await Le(t.pattern,{cwd:e,nodir:!0,absolute:!0,maxDepth:Cn});if(s){let n=await xs(e);i=Ss(i,e,n)}return{success:!0,files:i.slice(0,mi),total:i.length,truncated:i.length>mi}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to search files"}}};import Fi from"fs/promises";import jc from"path";var Kr=async t=>{try{let e=Dt(t.path),s=jc.dirname(e);if(await Fi.mkdir(s,{recursive:!0}),t.encoding==="base64"){let i=Buffer.from(t.content,"base64");await Fi.writeFile(e,i)}else if(!t.encoding||t.encoding==="utf-8")await Fi.writeFile(e,t.content,"utf-8");else{let i=t.encoding;throw new Error(`Unsupported encoding: ${String(i)}`)}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Failed to write file"}}};var Zr={filesystem__read_file:qr,filesystem__read_multiple_files:Jr,filesystem__write_file:Kr,filesystem__edit_file:Pn,filesystem__create_directory:In,filesystem__list_directory:Gr,filesystem__search_files:Vr,filesystem__grep_files:zr,filesystem__get_file_info:Nn,filesystem__move_file:Hr,filesystem__execute_command:Rn};function to(){return{name:"filesystem",systemPrompt:an({toolNames:ai.map(t=>t.name),env:{home:Uc.homedir(),cwd:process.cwd()}}),tools:[...ai]}}var Qr=!1;function zc(){process.platform==="darwin"&&(Qr||process.stdout.isTTY&&(Qr=!0,Wc('open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"',()=>{})))}async function eo(t,e){let s=Zr[t];if(!s)return{success:!1,error:`Unknown tool: ${t}`};let i=t==="filesystem__execute_command"&&!e.cwd?{...e,cwd:process.cwd()}:e,n=await Yr(s,zc)(i);if(!n.success){let{success:a,error:l,...c}=n,d=Object.keys(c).length>0;return{success:!1,error:l,result:d?c:void 0}}let{success:r,...o}=n;return{success:!0,result:o}}function Di(t){return t.startsWith("filesystem__")}function so(){return[to()]}function js(){return so().flatMap(t=>t.tools)}function Ws(){return so().map(t=>t.systemPrompt).filter(Boolean).join(`
35
-
36
- `)}function ae(t){return Di(t)}async function Us(t,e){return Di(t)?eo(t,e):{success:!1,error:`Unknown client tool: ${t}`}}function zs(t){if(!t.success){let r=[{type:"text",text:t.error||"Unknown error"}];return t.result&&r.push({type:"text",text:JSON.stringify(t.result)}),r}let{payload:e,images:s,notes:i}=hn(t.result),n=[{type:"text",text:JSON.stringify(e)},...i.map(r=>({type:"text",text:r}))];for(let r of s)r.path&&n.push({type:"text",text:`File: ${r.path}`}),n.push({type:"image",data:r.data,mimeType:r.mimeType});return n}import{Box as St,Text as q,useInput as Ki}from"ink";import Zi from"ink-spinner";import{useCallback as Qi,useEffect as Qs,useRef as tn,useState as $h}from"react";import{Box as Gs,Text as ns}from"ink";import{jsx as Hs,jsxs as rs}from"react/jsx-runtime";function io(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:i=!1,visible:n,title:r,pageSize:o=10}){if(!n||t.length===0)return null;let a=process.stdout.columns??80,l=i?4:0,c=Math.max(20,a-2-2-l),d=Math.max(1,o),h=Math.floor(e/d)*d,f=Math.min(t.length,h+d),y=t.slice(h,f);return rs(Gs,{flexDirection:"column",marginBottom:1,children:[Hs(ns,{bold:!0,color:"cyan",children:r}),Hs(Gs,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:y.map((g,w)=>{let k=h+w===e,E=s?.has(g.id),N=io(g.name,c),I=g.description?io(g.description,Math.max(0,c-l)):"",P=i?" ".repeat(l):"";return rs(Gs,{paddingX:1,flexDirection:"column",children:[rs(Gs,{children:[i&&Hs(ns,{color:E?"green":"gray",children:E?"[\u2713] ":"[ ] "}),Hs(ns,{backgroundColor:k?"cyan":void 0,color:k?"black":E?"green":"white",bold:!0,children:N})]}),I&&rs(ns,{dimColor:!0,children:[P,"\xB7 ",I]})]},g.id)})}),rs(ns,{dimColor:!0,children:[i?"\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>d?` \xB7 Showing ${h+1}-${f} of ${t.length}`:""]})]})}import{Box as Oi,Text as os}from"ink";import{jsx as as,jsxs as Li}from"react/jsx-runtime";function ro({suggestions:t,activeIndex:e,visible:s}){return!s||t.length===0?null:Li(Oi,{flexDirection:"column",marginBottom:1,children:[as(Oi,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:t.map((i,n)=>{let r=n===e,o=i.aliases.length>0?` (${i.aliases.join(", ")})`:"";return Li(Oi,{paddingX:1,children:[Li(os,{backgroundColor:r?"cyan":void 0,color:r?"black":"cyan",bold:r,children:["/",i.name]}),as(os,{dimColor:!0,children:o}),as(os,{children:" - "}),as(os,{color:r?"white":"gray",children:i.description})]},i.name)})}),as(os,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as Gc,Text as oo,useInput as Hc,useStdout as qc}from"ink";import{useCallback as ao,useEffect as lo,useMemo as Mi,useRef as co,useState as ho}from"react";import{jsx as Wi}from"react/jsx-runtime";function qs(t,e){return t<0?0:t>e?e:t}function Bi(t){return[...t]}function Xs(t){return/\s/.test(t)}function ji(t,e){let s=e;for(;s>0&&Xs(t[s-1]??"");)s-=1;for(;s>0&&!Xs(t[s-1]??"");)s-=1;return s}function uo(t,e){let s=e;for(;s<t.length&&Xs(t[s]??"");)s+=1;for(;s<t.length&&!Xs(t[s]??"");)s+=1;return s}function Xc(t){let e=[],s=[],i=[],n=0;s.push(0),t.forEach((o,a)=>{if(o===`
37
- `){e.push(i),i=[],n=a+1,s.push(n);return}i.push(o)}),e.push(i);let r=e.map(o=>o.length);return{lines:e,lineStarts:s,lineLengths:r}}function fo(t,e,s){for(let n=0;n<e.length;n+=1){let r=e[n]??0,o=s[n]??0,a=r+o;if(t<=a)return{row:n,col:t-r}}let i=Math.max(0,e.length-1);return{row:i,col:s[i]??0}}var Yc=2;function po({value:t,onChange:e,onSubmit:s,onPaste:i,focus:n=!0,leadingOffset:r=0,multiline:o=!1}){let[a,l]=ho(()=>Bi(t).length),c=co(null),[d,h]=ho(0),f=co(null),{stdout:y}=qc(),g=Mi(()=>Bi(t),[t]),{lines:w,lineStarts:C,lineLengths:k}=Mi(()=>Xc(g),[g]),{row:E,col:N}=Mi(()=>fo(a,C,k),[a,C,k]),I=Math.max(1,(y?.columns??80)-r);lo(()=>{c.current===t?l(m=>qs(m,g.length)):(l(g.length),f.current=null),c.current=t},[t,g.length]),lo(()=>{h(m=>{let S=m;N<S?S=N:N>=S+I&&(S=N-I+1);let F=k[E]??0,W=N===F?F+1:F,R=Math.max(0,W-I);return S>R&&(S=R),S<0&&(S=0),S})},[I,N,E,k]);let P=ao((m,S)=>{c.current=m,e(m),l(S),f.current=null},[e]),tt=ao(async(m,S)=>{if(!n)return;let{row:F,col:W}=fo(a,C,k),R=w[F]??[],pt=k[F]??0,st=w.length>1;if(o&&(S.meta&&S.return||S.ctrl&&m==="j"||S.shift&&S.return)){let A=[...g.slice(0,a),`
38
- `,...g.slice(a)].join("");P(A,a+1);return}if(S.return){s(t);return}if(S.leftArrow){S.ctrl||S.meta?(W===0&&F>0?l(C[F]-1):l(C[F]+ji(R,W)),f.current=null):(W===0&&F>0?l(C[F]-1):l(A=>qs(A-1,g.length)),f.current=null);return}if(S.rightArrow){S.ctrl||S.meta?(W>=pt&&F<w.length-1?l(C[F+1]):l(C[F]+uo(R,W)),f.current=null):(W>=pt&&F<w.length-1?l(C[F+1]):l(A=>qs(A+1,g.length)),f.current=null);return}if(o&&st&&S.upArrow){let A=f.current??W,z=Math.max(0,F-1),nt=Math.min(A,k[z]??0);l((C[z]??0)+nt),f.current=A;return}if(o&&st&&S.downArrow){let A=f.current??W,z=Math.min(w.length-1,F+1),nt=Math.min(A,k[z]??0);l((C[z]??0)+nt),f.current=A;return}if(S.ctrl){if(m==="a"){l(C[F]??0),f.current=null;return}if(m==="e"){l((C[F]??0)+pt),f.current=null;return}if(m==="u"){if(W>0){let A=C[F]??0,z=[...g.slice(0,A),...g.slice(a)].join("");P(z,A)}return}if(m==="k"){if(W<pt){let A=(C[F]??0)+pt,z=[...g.slice(0,a),...g.slice(A)].join("");P(z,a)}return}if(m==="w"){if(W===0&&F>0){let z=[...g.slice(0,a-1),...g.slice(a)].join("");P(z,a-1);return}let A=ji(R,W);if(A!==W){let z=(C[F]??0)+A,nt=[...g.slice(0,z),...g.slice(a)].join("");P(nt,z)}return}if(m==="d"){if(a<g.length){let A=[...g.slice(0,a),...g.slice(a+1)].join("");P(A,a)}return}return}if(S.meta){m==="b"?(W===0&&F>0?l(C[F]-1):l(C[F]+ji(R,W)),f.current=null):m==="f"&&(W>=pt&&F<w.length-1?l(C[F+1]):l(C[F]+uo(R,W)),f.current=null);return}if(S.backspace||S.delete){if(a<=0)return;let A=[...g.slice(0,a-1),...g.slice(a)].join("");P(A,a-1);return}if(!(S.tab||S.escape)&&m.length>0){let A=o?m.replace(/\r\n/g,`
39
- `).replace(/\r/g,`
40
- `):m.replace(/\r?\n/g,"");if(!A||(A=A.replace(/^\u001B?\[200~/,"").replace(/\u001B?\[201~$/,""),!A))return;if((A.length>=Yc||A.includes(`
41
- `))&&i){let M=!1,V={text:A,preventDefault:()=>{M=!0}};if(await Promise.resolve(i(V)),M)return}let nt=Bi(A),rt=[...g.slice(0,a),...nt,...g.slice(a)].join("");P(rt,a+nt.length)}},[g,a,n,k,C,w,o,i,s,P,t]);return Hc(tt,{isActive:n}),Wi(Gc,{flexDirection:"column",children:w.map((m,S)=>{let F=S===E,R=(F&&N===m.length?[...m," "]:m).slice(d,d+I),pt=R.join("");if(!F)return Wi(oo,{children:pt||" "},S);let st=qs(N-d,Math.max(0,R.length-1)),A=R.slice(0,st).join(""),z=R[st]??" ",nt=R.slice(st+1).join(""),V=`${A}\x1B[7m${z}\x1B[27m${nt}`;return Wi(oo,{children:V},S)})})}import{Box as te,Text as me}from"ink";import Hi from"react";import{Text as Ut}from"ink";import Jc from"react";import{Fragment as Zc,jsx as Yt,jsxs as yo}from"react/jsx-runtime";var Ui=2,zi=1,Gi=2,Vc=1,mo=3,go=4,Kc=({text:t,defaultColor:e,linkColor:s,codeColor:i})=>{let n=e;if(!/[*_~`<[https?:]/.test(t))return Yt(Ut,{color:n,children:t});let r=[],o=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(t))!==null;){l.index>o&&r.push(Yt(Ut,{color:n,children:t.slice(o,l.index)},`t-${o}`));let c=l[0],d=null,h=`m-${l.index}`;try{if(c.startsWith("**")&&c.endsWith("**")&&c.length>Ui*2)d=Yt(Ut,{bold:!0,color:n,children:c.slice(Ui,-Ui)},h);else if(c.length>zi*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)))d=Yt(Ut,{italic:!0,color:n,children:c.slice(zi,-zi)},h);else if(c.startsWith("~~")&&c.endsWith("~~")&&c.length>Gi*2)d=Yt(Ut,{strikethrough:!0,color:n,children:c.slice(Gi,-Gi)},h);else if(c.startsWith("`")&&c.endsWith("`")&&c.length>Vc){let f=c.match(/^(`+)(.+?)\1$/s);f&&f[2]&&(d=Yt(Ut,{color:i,children:f[2]},h))}else if(c.startsWith("[")&&c.includes("](")&&c.endsWith(")")){let f=c.match(/\[(.*?)\]\((.*?)\)/);if(f){let y=f[1],g=f[2];d=yo(Ut,{color:n,children:[y,yo(Ut,{color:s,children:[" (",g,")"]})]},h)}}else c.startsWith("<u>")&&c.endsWith("</u>")&&c.length>mo+go-1?d=Yt(Ut,{underline:!0,color:n,children:c.slice(mo,-go)},h):/^https?:\/\//.test(c)&&(d=Yt(Ut,{color:s,children:c},h))}catch{d=null}r.push(d??Yt(Ut,{color:n,children:c},h)),o=a.lastIndex}return o<t.length&&r.push(Yt(Ut,{color:n,children:t.slice(o)},`t-${o}`)),Yt(Zc,{children:r.filter(c=>c!==null)})},ls=Jc.memo(Kc);import{Fragment as rh,jsx as ct,jsxs as So}from"react/jsx-runtime";var Qc=1,xo=1,th=1,eh=1,sh=({content:t})=>{let e=t.join(`
42
- `);return ct(te,{paddingLeft:xo,flexDirection:"column",children:ct(me,{color:"yellow",children:e})})},wo=Hi.memo(sh),ih=({itemText:t,type:e,marker:s,leadingWhitespace:i=""})=>{let n=e==="ol"?`${s}. `:`${s} `,r=n.length,o=i.length;return So(te,{paddingLeft:o+th,flexDirection:"row",children:[ct(te,{width:r,children:ct(me,{children:n})}),ct(te,{flexGrow:eh,children:ct(me,{wrap:"wrap",children:ct(ls,{text:t,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},bo=Hi.memo(ih),nh=({text:t,renderMarkdown:e=!0})=>{if(!t)return null;if(!e)return ct(te,{paddingLeft:xo,flexDirection:"column",children:ct(me,{wrap:"wrap",children:t})});let s=t.split(/\r?\n/),i=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,r=/^([ \t]*)([-*+]) +(.*)/,o=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,c=[],d=!1,h=!0,f=[],y="";function g(w){w&&(c.push(w),h=!1)}return s.forEach((w,C)=>{let k=`line-${C}`;if(d){let S=w.match(n);S&&S[1].startsWith(y[0])&&S[1].length>=y.length?(g(ct(wo,{content:f},k)),d=!1,f=[],y=""):f.push(w);return}let E=w.match(n),N=w.match(i),I=w.match(r),P=w.match(o),tt=w.match(a),m=w.match(l);if(E)d=!0,y=E[1];else if(tt)g(ct(te,{children:ct(me,{dimColor:!0,children:"---"})},k));else if(N){let S=N[1].length,F=N[2],W=S<=2?"cyan":"blue";g(ct(te,{children:ct(me,{color:W,...(S===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ct(ls,{text:F,defaultColor:W,linkColor:"cyan",codeColor:"yellow"})})},k))}else if(m){let S=m[1];g(ct(te,{paddingLeft:1,children:So(me,{dimColor:!0,children:["> ",ct(ls,{text:S,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},k))}else if(I){let S=I[1],F=I[2],W=I[3];g(ct(bo,{itemText:W,type:"ul",marker:F,leadingWhitespace:S},k))}else if(P){let S=P[1],F=P[2],W=P[3];g(ct(bo,{itemText:W,type:"ol",marker:F,leadingWhitespace:S},k))}else w.trim().length===0?h||(c.push(ct(te,{height:Qc},`spacer-${C}`)),h=!0):g(ct(te,{children:ct(me,{wrap:"wrap",children:ct(ls,{text:w,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},k))}),d&&g(ct(wo,{content:f},"line-eof")),ct(rh,{children:c})},qi=Hi.memo(nh);import{execFile as oh}from"child_process";import ah from"fs";import Me from"fs/promises";import vo from"os";import Js from"path";import{promisify as lh}from"util";var Ys=lh(oh);async function ch(){let t=Js.join(vo.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let e=`
43
- set imageData to the clipboard as "PNGf"
44
- set fileRef to open for access POSIX file "${t}" with write permission
45
- set eof fileRef to 0
46
- write imageData to fileRef
47
- close access fileRef
48
- `;return await Ys("osascript",["-e",e]),(await Me.stat(t)).size===0?void 0:{buffer:await Me.readFile(t),mime:"image/png"}}catch{return}finally{try{ah.existsSync(t)&&await Me.unlink(t)}catch{}}}async function hh(){try{let t=`
49
- Add-Type -AssemblyName System.Windows.Forms
50
- $img = [System.Windows.Forms.Clipboard]::GetImage()
51
- if ($img) {
52
- $ms = New-Object System.IO.MemoryStream
53
- $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
54
- [System.Convert]::ToBase64String($ms.ToArray())
55
- }
56
- `,{stdout:e}=await Ys("powershell.exe",["-command",t]),s=e.trim();if(!s)return;let i=Buffer.from(s,"base64");return i.length===0?void 0:{buffer:i,mime:"image/png"}}catch{return}}async function uh(){try{let{stdout:t}=await Ys("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 Ys("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 ko(){let t=vo.platform();if(t==="darwin")return ch();if(t==="win32")return hh();if(t==="linux")return uh()}var dh=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 To(t){let e=Js.extname(t).toLowerCase();return dh.has(e)}function fh(t){let e=Js.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 Vs(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 Co(t){let e=Vs(t);if(/^https?:\/\//.test(e))return!1;try{return await Me.access(e),!0}catch{return!1}}async function Eo(t){let e=Vs(t);try{if(!(await Me.stat(e)).isFile())return;let i=await Me.readFile(e),n=fh(e),r=Js.basename(e);return{buffer:i,mimeType:n,filename:r}}catch{return}}var zt="\x1B[2m",Q="\x1B[0m",xt="\x1B[36m",Be="\x1B[32m",_o="\x1B[31m",ke="\x1B[38;2;59;91;204m",Xi="\x1B[38;2;126;200;248m",Yi="\x1B[38;2;244;196;78m";import{useState as le}from"react";import{v4 as $o}from"uuid";function Io(t,e){let[s,i]=le({status:"loading"}),[n,r]=le([]),[o,a]=le(""),[l,c]=le(()=>t||$o()),[d,h]=le(e),[f,y]=le(!!t),[g,w]=le(null),[C,k]=le(""),[E,N]=le(!1),I=tt=>{r(m=>[...m,{role:"system",content:tt}])};return{state:s,setState:i,messages:n,setMessages:r,input:o,setInput:a,taskId:l,setTaskId:c,currentTaskTitle:d,setCurrentTaskTitle:h,hasPersistedTask:f,setHasPersistedTask:y,credentials:g,setCredentials:w,currentResponse:C,setCurrentResponse:k,fullOutput:E,setFullOutput:N,addSystemMessage:I,startNewTask:tt=>{let m=$o();c(m),h(void 0),y(!1),r([]),tt&&I(tt)}}}import{useEffect as ph,useState as Ao}from"react";function Po(t){let[e,s]=Ao(null),[i,n]=Ao(!0);return ph(()=>{let r=!1;async function o(){try{let a=await ue();if(r)return;s({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(r)return;if(a instanceof be){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:"Failed to authenticate";t({status:"error",message:l}),n(!1)}}return o(),()=>{r=!0}},[t]),{credentials:e,loading:i}}import{useEffect as mh,useState as cs}from"react";function Ro(t){let[e,s]=cs([]),[i,n]=cs([]),[r,o]=cs([]),[a,l]=cs([]),[c,d]=cs(!1);return mh(()=>{if(!t)return;let h=!1;d(!0);async function f(){if(t)try{let y=new mt,[g,w,C,k]=await Promise.all([y.getConnectors(t.accessToken,t.workspaceId),y.listSelectableModels(t.accessToken,t.workspaceId),y.getAgents(t.accessToken,t.workspaceId),y.getModelProviders(t.accessToken,t.workspaceId)]);if(h)return;s(g.connectors),n(w.models),o(C.agents),l(k.providers??[])}catch{}finally{h||d(!1)}}return f(),()=>{h=!0}},[t]),{availableConnectors:e,availableModels:i,availableAgents:r,modelProviders:a,loading:c}}import je from"fs";import Fo from"path";import{useCallback as gh}from"react";import{v4 as yh}from"uuid";function No(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)+"..."}let s=t;if("structuredContent"in s&&s.structuredContent){let n=s.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let r=n.stdout.trim();return e||r.length<=200?r:r.slice(0,200)+"..."}}if("content"in s&&Array.isArray(s.content)){let n=s.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
57
- `);return n?e||n.length<=200?n:n.slice(0,200)+"...":"(result)"}if(s.type==="text"&&typeof s.content=="string"){let n=s.content;return e||n.length<=200?n:n.slice(0,200)+"..."}let i=JSON.stringify(t,null,e?2:void 0);return e||i.length<=200?i:i.slice(0,200)+"..."}function Te(t,e=!1){let s=[];for(let i of t)if(i.type==="text"&&i.text)s.push(i.text);else if(i.type==="reasoning"&&i.text)e?s.push(`${zt}[Thinking]
58
- ${i.text}${Q}`):s.push(`${zt}[Thinking...]${Q}`);else if(i.type==="tool-call"&&i.toolName){let n=[`${xt}\u250C\u2500 Tool: ${i.toolName}${Q}`];if(i.args){let r=JSON.stringify(i.args,null,e?2:void 0),o=e||r.length<=100?r:r.slice(0,100)+"...";n.push(`${zt}\u2502 Args: ${o}${Q}`)}i.result===void 0?n.push(`${xt}\u2514\u2500${Q}`):(n.push(`${Be}\u2502 Result: ${No(i.result,e)}${Q}`),n.push(`${xt}\u2514\u2500 completed${Q}`)),s.push(n.join(`
59
- `))}else if(i.type.startsWith("tool-")&&i.type!=="tool-call"){let n=i.title||i.type.slice(5).replace(/__/g," "),r=[`${xt}\u250C\u2500 Tool: ${n}${Q}`];if(i.input){let o=JSON.stringify(i.input,null,e?2:void 0),a=e||o.length<=100?o:o.slice(0,100)+"...";r.push(`${zt}\u2502 Input: ${a}${Q}`)}i.output!==void 0&&i.state==="output-available"?(r.push(`${Be}\u2502 Output: ${No(i.output,e)}${Q}`),r.push(`${xt}\u2514\u2500 completed${Q}`)):i.state==="error"?r.push(`${xt}\u2514\u2500 failed${Q}`):r.push(`${xt}\u2514\u2500${Q}`),s.push(r.join(`
60
- `))}return s.join(`
61
-
62
- `).trim()}var Ks=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let e of this.pendingToolCalls.values())if(e.status==="executing")return!0;return!1}clear(e){this.pendingToolCalls.delete(e)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let e=[];for(let[,s]of this.pendingToolCalls){let i=s.toolName.replace(/__/g," "),n=`
63
-
64
- ${xt}\u250C\u2500 Tool: ${i}${Q}`;if(s.args){let r=s.args.length>100?s.args.slice(0,100)+"...":s.args;n+=`
65
- ${zt}\u2502 Input: ${r}${Q}`}if(s.output){let r=s.output.length>150?s.output.slice(0,150)+"...":s.output;n+=`
66
- ${Be}\u2502 Output: ${r}${Q}`}else if(s.status==="executing"){let r=s.startedAt??Date.now(),o=Math.floor((Date.now()-r)/1e3);n+=`
67
- ${xt}\u2502${Q} (executing... ${o}s)`}else s.status==="preparing"&&(n+=`
68
- ${xt}\u2502${Q} (preparing...)`);e.push(n)}return e.join("")}flushPending(e){if(this.pendingToolCalls.size===0)return e;for(let[s,i]of this.pendingToolCalls){let n=i.toolName.replace(/__/g," "),r=typeof i.args=="string"&&i.args.length>100?i.args.slice(0,100)+"...":i.args||"";e+=`
69
-
70
- ${xt}\u250C\u2500 Tool: ${n}${Q}`,r&&(e+=`
71
- ${zt}\u2502 Input: ${r}${Q}`),e+=`
72
- ${xt}\u2514\u2500 completed${Q}
73
- `,this.pendingToolCalls.delete(s)}return e}handleToolInputStart(e){return e.toolCallId&&e.toolName?(this.pendingToolCalls.set(e.toolCallId,{toolName:e.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(e){if(e.toolCallId&&e.inputTextDelta){let s=this.pendingToolCalls.get(e.toolCallId);if(s)return s.args=(s.args||"")+e.inputTextDelta,s.status="executing",s.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(e){if(e.toolCallId){let s=this.pendingToolCalls.get(e.toolCallId);if(s)return s.output="",s.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(e){if(e.toolCallId&&e.outputTextDelta){let s=this.pendingToolCalls.get(e.toolCallId);if(s)return s.output=(s.output||"")+e.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(e,s){if(!e.toolCallId)return null;let i=this.pendingToolCalls.get(e.toolCallId);if(!i)return null;let n=i.toolName.replace(/__/g," "),r=typeof i.args=="string"&&i.args.length>100?i.args.slice(0,100)+"...":i.args||"",o=(i.output||"").length>200?(i.output||"").slice(0,200)+"...":i.output||"";return s+=`
74
-
75
- ${xt}\u250C\u2500 Tool: ${n}${Q}`,r&&(s+=`
76
- ${zt}\u2502 Input: ${r}${Q}`),s+=`
77
- ${Be}\u2502 Output: ${o}${Q}`,s+=`
78
- ${xt}\u2514\u2500 completed${Q}
79
- `,this.pendingToolCalls.delete(e.toolCallId),{fullResponse:s,toolDisplay:this.buildToolDisplay()}}handleToolError(e,s){if(!e.toolCallId)return null;let n=(this.pendingToolCalls.get(e.toolCallId)?.toolName||e.toolName||"Tool").replace(/__/g," "),r=e.errorText||"Unknown error",o=r.length>200?r.slice(0,200)+"...":r;return s+=`
80
-
81
- ${xt}\u250C\u2500 Tool: ${n}${Q}`,s+=`
82
- ${_o}\u2502 Error: ${o}${Q}`,s+=`
83
- ${xt}\u2514\u2500 failed${Q}
84
- `,this.pendingToolCalls.delete(e.toolCallId),{fullResponse:s,toolDisplay:this.buildToolDisplay()}}};var hs=Fo.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function it(t,e){if(!process.env.DEBUG)return;let i=`[${new Date().toISOString()}] ${t}`;e!==void 0&&(i+=`
85
- DATA: ${JSON.stringify(e,null,2)}`),i+=`
86
- `;try{je.appendFileSync(hs,i)}catch{}}function wh(){try{if(je.existsSync(hs)&&je.unlinkSync(hs),process.env.DEBUG){let t=Fo.dirname(hs);je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),je.writeFileSync(hs,`=== Debug session started at ${new Date().toISOString()} ===
87
- `)}}catch{}}function Zs(t){if(!t)return{};if(typeof t=="string")try{return JSON.parse(t)}catch{return{}}return typeof t=="object"?t:{}}function Do({taskId:t,credentials:e,currentAgentId:s,currentModel:i,activeConnectorIds:n,localTools:r,fullOutput:o,setMessages:a,setState:l,setCurrentResponse:c,setCredentials:d,setHasPersistedTask:h,getFileIds:f,clearFiles:y}){let g=r?js():void 0,w=r?Ws():void 0;return{sendMessage:gh(async(k,E,N)=>{wh(),it("=== sendMessage called ===",{text:k,localTools:r,clientToolsCount:g?.length});let I=E||e?.accessToken,P=N||e?.workspaceId;if(!I||!P)try{let S=await ue();I=S.accessToken,P=S.workspaceId,d(S)}catch(S){if(S instanceof be){if(S.code==="not-logged-in"){l({status:"not-logged-in"});return}if(S.code==="no-workspace"){l({status:"no-workspace"});return}}let F=S instanceof Error?S.message:"Authentication failed";l({status:"error",message:F});return}else try{let S=await nn();S!==I&&(I=S,d({accessToken:S,workspaceId:P}))}catch(S){if(S instanceof be&&S.code==="not-logged-in"){l({status:"not-logged-in"});return}let F=S instanceof Error?S.message:"Authentication failed";l({status:"error",message:F});return}a(S=>[...S,{role:"user",content:k}]),l({status:"sending"}),c("");let tt=null,m=null;try{let S=new mt,F=f?.()??[],W={id:t,message:{id:yh(),createdAt:new Date,role:"user",parts:[{type:"text",text:k}]}};F.length>0&&(W.fileIds=F),s?W.agentId=s:(i&&(W.model=i),W.connectorIds=n??[]),g&&(W.clientTools=g),w&&(W.clientToolSystemPrompt=w);let R=await S.task(I,P,W);if(!R.ok){let D=await R.text();throw new Error(`API error ${R.status}: ${D}`)}if(!R.body)throw new Error("No response body from server");tt=R.body.getReader();let pt=new TextDecoder,st="",A="",z="",nt="",rt="",M="",V="",K=new Ks,Z=[],X=[],at=[],U=()=>{let D=K.hasExecuting();D&&!m?m=setInterval(()=>{if(!K.hasExecuting()){m&&(clearInterval(m),m=null);return}c(A+K.buildToolDisplay())},1e3):!D&&m&&(clearInterval(m),m=null)};for(;;){let{done:D,value:G}=await tt.read();if(D)break;st+=pt.decode(G,{stream:!0});let O=st.split(`
88
- `);st=O.pop()||"";for(let Y of O)if(Y.trim()!=="data: [DONE]"&&Y.startsWith("data: "))try{let T=JSON.parse(Y.slice(6));switch(it(`SSE event received: ${T.type}`,T),T.type){case"reasoning-start":nt=T.id||"0",z="";break;case"reasoning-delta":T.delta&&(z+=T.delta,c(`${zt}[Thinking...]${Q}
89
- ${z}`)),T.providerMetadata?.anthropic?.signature&&(rt=T.providerMetadata.anthropic.signature);break;case"reasoning-end":if(z){let L={type:"reasoning",id:nt,text:z,state:"done"};rt&&(L.providerMetadata={anthropic:{signature:rt}}),X.push(L),it("Added reasoning to messageParts",{reasoningLength:z.length,hasSignature:!!rt,messagePartsCount:X.length})}z="",rt="",c("");break;case"text-delta":T.delta&&(K.hasPending()&&(A=K.flushPending(A)),A+=T.delta,M+=T.delta,c(A));break;case"tool-input-start":{let L=K.handleToolInputStart(T);L&&c(A+L),U();break}case"tool-input-delta":{let L=K.handleToolInputDelta(T);L&&c(A+L),U();break}case"tool-call":case"tool-input-available":if(it(`=== Tool event: ${T.type} ===`,{toolCallId:T.toolCallId,toolName:T.toolName,localTools:r,isClientToolResult:T.toolName?ae(T.toolName):"no toolName",args:T.args,input:T.input}),T.toolCallId&&T.toolName){let L=Zs(T.args??T.input);X.push({type:T.type,toolCallId:T.toolCallId,toolName:T.toolName,args:L}),it("Added tool to messageParts",{messagePartsCount:X.length})}if(r&&T.toolCallId&&T.toolName&&ae(T.toolName)){let L=Zs(T.args??T.input);Z.push({toolCallId:T.toolCallId,toolName:T.toolName,args:L}),it("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),c(A+K.buildToolDisplay()+`
90
- [Executing ${T.toolName} locally...]`)}else it("NOT added to pendingClientTools - conditions not met",{localTools:r,hasToolCallId:!!T.toolCallId,hasToolName:!!T.toolName,isClientTool:T.toolName?ae(T.toolName):!1});break;case"tool-output-start":{let L=K.handleToolOutputStart(T);L&&c(A+L),U();break}case"tool-output-delta":{let L=K.handleToolOutputDelta(T);L&&c(A+L),U();break}case"tool-output-end":{let L=K.handleToolOutputEnd(T,A);L&&(A=L.fullResponse,c(A+L.toolDisplay)),U();break}case"tool-input-error":case"tool-output-error":{let L=K.handleToolError(T,A);L&&(A=L.fullResponse,c(A+L.toolDisplay)),U();break}case"start":T.messageId&&(V=T.messageId,it("Captured messageId from start event",{messageId:V}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":T.errorText&&console.error("Stream error:",T.errorText);break}}catch{}}if(M){let D=X.findIndex(O=>O.type!=="reasoning"),G=D===-1?X.length:D;X.splice(G,0,{type:"text",text:M}),it("Added accumulated text to messageParts",{textLength:M.length,insertIndex:G})}for(it("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:X.length,messageParts:X.map(D=>({type:D.type,toolCallId:D.toolCallId,toolName:D.toolName}))});Z.length>0;){it("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let D=[];for(let T of Z){it(`Executing tool: ${T.toolName}`,{toolCallId:T.toolCallId,args:T.args}),K.handleToolInputStart({toolCallId:T.toolCallId,toolName:T.toolName}),K.handleToolInputDelta({toolCallId:T.toolCallId,inputTextDelta:JSON.stringify(T.args)}),c(A+K.buildToolDisplay()),U();let L=await Us(T.toolName,T.args);if(it(`Tool execution result: ${T.toolName}`,{success:L.success,resultPreview:L.success?JSON.stringify(L.result).slice(0,200):L.error}),D.push({toolCallId:T.toolCallId,toolName:T.toolName,content:zs(L),isError:!L.success}),L.success){K.handleToolOutputStart({toolCallId:T.toolCallId}),K.handleToolOutputDelta({toolCallId:T.toolCallId,outputTextDelta:JSON.stringify(L.result).slice(0,200)});let _=K.handleToolOutputEnd({toolCallId:T.toolCallId},A);_&&(A=_.fullResponse)}else{let _=K.handleToolError({toolCallId:T.toolCallId,errorText:L.error},A);_&&(A=_.fullResponse)}c(A+K.buildToolDisplay()),U()}Z.length=0;for(let T of D){let L=X.find(_=>(_.type==="tool-input-available"||_.type==="tool-call")&&_.toolCallId===T.toolCallId);if(L){let _=[];for(let j of T.content)j.type==="text"?_.push(j.text):j.type==="image"?_.push("[Image]"):j.type==="audio"?_.push("[Audio]"):(j.type==="resource"||j.type==="resource_link")&&_.push("[Resource]");let ht=_.join(`
91
- `);at.push({type:`tool-${L.toolName}`,toolName:L.toolName,toolCallId:L.toolCallId,input:L.args,output:ht,isError:T.isError})}}if(it("=== Sending clientToolResults for continuation ===",{toolResultsCount:D.length,toolResults:D.map(T=>({toolCallId:T.toolCallId,toolName:T.toolName,isError:T.isError}))}),tt)try{tt.releaseLock()}catch{}let G=D.map(T=>({type:`tool-${T.toolName}`,toolCallId:T.toolCallId,state:"output-available",output:{content:T.content,isError:T.isError}}));if(!V)throw new Error("Cannot continue: missing assistant message id for tool results.");let O={id:t,message:{id:V,role:"assistant",parts:G}};s?O.agentId=s:(i&&(O.model=i),O.connectorIds=n??[]),g&&(O.clientTools=g),w&&(O.clientToolSystemPrompt=w),it("=== Sending continuation request ===",{taskId:t,hasAgentId:!!O.agentId,hasModel:!!O.model,clientToolResultsCount:D.length});let Y=await S.task(I,P,O);if(it("=== Continuation response received ===",{ok:Y.ok,status:Y.status}),!Y.ok){let T=await Y.text();throw new Error(`Continuation failed: ${Y.status}: ${T}`)}if(!Y.body)break;for(it("=== Processing continuation stream ==="),tt=Y.body.getReader(),X.length=0,M="",z="",nt="",rt="";;){let{done:T,value:L}=await tt.read();if(T){it("=== Continuation stream done ===");break}st+=pt.decode(L,{stream:!0});let _=st.split(`
92
- `);st=_.pop()||"";for(let ht of _)if(ht.trim()!=="data: [DONE]"&&ht.startsWith("data: "))try{let j=JSON.parse(ht.slice(6));switch(it(`Continuation SSE: ${j.type}`,j),j.type){case"start":j.messageId&&(V=j.messageId);break;case"reasoning-start":nt=j.id||"0",z="";break;case"reasoning-delta":j.delta&&(z+=j.delta,c(`${zt}[Thinking...]${Q}
93
- ${z}`)),j.providerMetadata?.anthropic?.signature&&(rt=j.providerMetadata.anthropic.signature);break;case"reasoning-end":if(z){let Nt={type:"reasoning",id:nt,text:z,state:"done"};rt&&(Nt.providerMetadata={anthropic:{signature:rt}}),X.push(Nt),it("Continuation: Added reasoning to messageParts",{reasoningLength:z.length,hasSignature:!!rt,messagePartsCount:X.length})}z="",rt="",c(A);break;case"text-delta":j.delta&&(A+=j.delta,M+=j.delta,c(A));break;case"tool-call":case"tool-input-available":if(j.toolCallId&&j.toolName){let Nt=Zs(j.args??j.input);X.push({type:j.type,toolCallId:j.toolCallId,toolName:j.toolName,args:Nt})}if(r&&j.toolCallId&&j.toolName&&ae(j.toolName)){let Nt=Zs(j.args??j.input);Z.push({toolCallId:j.toolCallId,toolName:j.toolName,args:Nt}),it("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":it("Continuation finish event",j);break}}catch{}}if(M){let T=X.findIndex(_=>_.type!=="reasoning"),L=T===-1?X.length:T;X.splice(L,0,{type:"text",text:M})}it("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:X.length,fullResponseLength:A.length})}if(r&&g&&g.length>0){let D=[];for(let O of at)D.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of X)O.type==="text"&&O.text&&D.push({type:"text",text:O.text});let G=Te(D,o);it("=== Using formatted parts for local tools ===",{executedToolsCount:at.length,textPartsCount:X.filter(O=>O.type==="text").length,contentLength:G.length}),a(O=>[...O,{role:"assistant",content:G,parts:D}])}else{it("=== Fetching message from API ===",{fullResponseLength:A.length,fullResponsePreview:A.slice(0,200)});try{let{messages:D}=await S.getMessages(I,P,t,10);it("=== API messages received ===",{count:D.length,roles:D.map(O=>O.role)});let G=D.find(O=>O.role==="assistant");if(G){let O=G.parts,Y=Te(O,o);it("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(T=>T.type),contentLength:Y.length,contentPreview:Y.slice(0,200)}),a(T=>[...T,{role:"assistant",content:Y,parts:O}])}else it("=== No assistant message found, using fallback ==="),a(O=>[...O,{role:"assistant",content:A}])}catch(D){it("=== API fetch failed, using fallback ===",{error:D instanceof Error?D.message:String(D)}),a(G=>[...G,{role:"assistant",content:A}])}}it("=== Message handling complete ==="),c(""),l({status:"ready"}),h(!0),F.length>0&&y?.()}catch(S){it("=== ERROR ===",{message:S instanceof Error?S.message:String(S),stack:S instanceof Error?S.stack:void 0});let F=S instanceof Error?S.message:"Failed to send message";l({status:"error",message:F})}finally{if(m&&(clearInterval(m),m=null),tt)try{tt.releaseLock()}catch{}}},[e,t,s,i,n,r,g,w,o,a,l,c,d,h,f,y])}}import{useState as bh}from"react";var Oo=new Map([["sandbox","Sandbox"],["web_search","Web Search"],["image_generation","Image Generation"],["chart","Chart"],["file_system","FileSystem"]]);function Lo(t){let[e,s]=bh(t);return{fileSystem:e,setFileSystem:s,capabilityLabelMap:Oo}}import{useEffect as xh,useState as Sh}from"react";function Mo(t,e){let[s,i]=Sh(null);return xh(()=>{let n=!1;async function r(){if(!t||!e){i(null);return}try{let a=await new mt().getAgent(e.accessToken,e.workspaceId,t);n||i(a)}catch{n||i(null)}}return r(),()=>{n=!0}},[t,e]),{currentAgentDetails:s}}import{useState as Ji}from"react";function Bo(t,e,s){let[i,n]=Ji(t),[r,o]=Ji(e),[a,l]=Ji(s);return{currentModel:i,setCurrentModel:n,currentAgentId:r,setCurrentAgentId:o,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as kh,useInput as Th}from"ink";import{useCallback as ce,useRef as Ch,useState as At}from"react";import{spawn as vh}from"child_process";function jo(t){return new Promise((e,s)=>{let i,n;process.platform==="darwin"?(i="open",n=[t]):process.platform==="win32"?(i="cmd",n=["/c","start","",t]):(i="xdg-open",n=[t]);let r=vh(i,n,{stdio:"ignore",detached:!0});r.once("error",o=>{s(o)}),r.once("spawn",()=>{r.unref(),e()})})}var Wo=[{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:"tasks",aliases:["c"],description:"Switch to another task"},{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 Uo(t){if(!t.startsWith("/"))return[];let e=t.slice(1).toLowerCase();return e?Wo.filter(s=>s.name.startsWith(e)||s.aliases.some(i=>i.startsWith(e))):Wo}function zo(t){let e=t.trim();if(!e.startsWith("/"))return null;let s=e.slice(1).split(/\s+/),i=s[0]?.toLowerCase(),n=s.slice(1).join(" ");switch(i){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"tasks":case"c":return{type:"tasks"};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 Go=`Available commands:
94
- /help, /h, /? Show this help message
95
- /clear, /cls, /new Start a new task
96
- /model [name], /m Show current model or switch to [name]
97
- /agent [name], /a Show current agent or switch to [name]
98
- /skills [name], /sk List skills or show details for [name]
99
- /schedules [id], /sch List schedules or show details for [id]
100
- /connectors, /conn Select active connectors
101
- /capabilities, /cap Toggle client capabilities (FileSystem)
102
- /tasks, /c Switch to another task
103
- /workspace [id], /ws List or switch workspace
104
- /budget [amount], /bg View or set workspace budget
105
- /usage, /u View current month usage (top 10 by cost)
106
- /status, /s Show current session status
107
- /profile [args], /p Manage profiles (list/show/use/create/delete/rename/clone)
108
- /open-in-browser Open current task in browser
109
- /share Get share link for current task
110
- /delete, /del Delete current task
111
- /quit, /exit, /q Exit interactive mode
112
-
113
- Note: For detailed usage with sorting/limits, use: entrydesk usage --help
114
-
115
- Keyboard shortcuts:
116
- Ctrl+O Toggle full output mode
117
- Ctrl+C Exit`;function Vi(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 Ho({input:t,setInput:e,taskId:s,setTaskId:i,currentTaskTitle:n,setCurrentTaskTitle:r,currentModel:o,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:c,currentAgentDetails:d,setCurrentAgentDetails:h,activeConnectorIds:f,setActiveConnectorIds:y,fileSystem:g,setFileSystem:w,availableModels:C,availableAgents:k,availableConnectors:E,messages:N,hasPersistedTask:I,setHasPersistedTask:P,setMessages:tt,addSystemMessage:m,startNewTask:S,sendMessage:F,setFullOutput:W,credentials:R,setCredentials:pt,setState:st,defaultCapabilities:A,capabilityLabelMap:z,hasUploadingFiles:nt=!1}){let{exit:rt}=kh(),[M,V]=At([]),[K,Z]=At(0),[X,at]=At(!1),[U,D]=At(null),[G,O]=At([]),[Y,T]=At(0),[L,_]=At(new Set),[ht,j]=At(new Set),[Nt,fs]=At([]),[Jt,ii]=At([]),[Gt,We]=At([]),[ee,ps]=At([]),[Vt,he]=At(null),[ni,Ue]=At(""),Ee=Ch(!1),[se,kt]=At(!1),_e=ce(async()=>{if(!R)return[];let $=new mt,v=[],u;do{let p=await $.listAvailableSkills(R.accessToken,R.workspaceId,{limit:100,nextKey:u});v.push(...p.skills),u=p.nextKey}while(u);return ii(v),v},[R]),$e=ce(async()=>{if(!R)return[];let $=new mt,v=[],u;do{let p=await $.getSchedules(R.accessToken,R.workspaceId,{limit:100,nextKey:u});v.push(...p.schedules),u=p.nextKey}while(u);return We(v),v},[R]),Tt=ce(async $=>{if($==="model"){if(C.length===0){m("No models available.");return}let v=C.map(p=>({id:p.id,name:p.name,description:p.description}));O(v);let u=o?v.findIndex(p=>p.id===o):-1;T(Math.max(u,0)),D("model")}else if($==="agent"){if(k.length===0){m("No agents available.");return}let v=k.map(p=>({id:p.id,name:p.name,description:p.description}));O(v);let u=l?v.findIndex(p=>p.id===l):-1;T(Math.max(u,0)),D("agent")}else if($==="skills"){let v=Jt;if(v.length===0)try{v=await _e()}catch{m("Failed to load skills.");return}if(v.length===0){m("No skills available.");return}let u=v.map(p=>({id:p.id,name:p.name,description:p.description}));O(u),T(0),D("skills")}else if($==="schedules"){let v=Gt;if(v.length===0)try{v=await $e()}catch{m("Failed to load schedules.");return}if(v.length===0){m("No schedules found.");return}let u=v.map(p=>({id:p.id,name:p.name,description:`${p.agent.name} - ${p.isActive?"Active":"Paused"}`}));O(u),T(0),D("schedules")}else if($==="connectors"){if(E.length===0){m("No connectors available.");return}let v=E.map(u=>({id:u.id,name:u.name}));O(v),T(0),_(new Set(f)),D("connectors")}else if($==="capabilities"){O([{id:"fileSystem",name:"FileSystem",description:"Local file operations"}]),T(0);let u=new Set;g&&u.add("fileSystem"),j(u),D("capabilities")}else if($==="tasks"){if(!R){m("Not authenticated.");return}try{let v=new mt,{tasks:u}=await v.getTasks(R.accessToken,R.workspaceId,20);if(u.length===0){m("No tasks available.");return}fs(u);let p=u.map(b=>({id:b.id,name:b.title||"Untitled",description:new Date(b.createdAt).toLocaleDateString()}));O(p);let x=p.findIndex(b=>b.id===s);T(Math.max(x,0)),D("tasks")}catch{m("Failed to load tasks.")}}else if($==="profile"){let v=lt.getProfileNames(),u=lt.getCurrentProfileName(),p=v.map(b=>({id:b,name:b,description:b===u?"(current)":void 0}));O(p);let x=p.findIndex(b=>b.id===u);T(Math.max(x,0)),D("profile")}at(!1),V([])},[C,k,Jt,Gt,E,f,o,l,g,_e,$e,R,s,m]),Ht=ce($=>{let v=dt.getAll($);a(v.model?.default),c(void 0),h(null);let u=v.connectors?.defaults;y(u&&u.length>0?u:void 0);let p=v.localTools;w(p?.fileSystem??A.fileSystem)},[a,c,h,y,w,A]),Kt=ce(async()=>{try{let $=await ue();pt({accessToken:$.accessToken,workspaceId:$.workspaceId}),st({status:"ready"})}catch($){if(pt(null),$ instanceof be){if($.code==="not-logged-in"){st({status:"not-logged-in"});return}if($.code==="no-workspace"){st({status:"no-workspace"});return}}let v=$ instanceof Error?$.message:"Failed to authenticate";st({status:"error",message:v})}},[pt,st]),ge=ce(async $=>{switch($.type){case"help":return m(Go),!0;case"clear":return S("Started a new task."),!0;case"model":if($.value){let v=$.value.toLowerCase(),u=C.find(p=>p.id.toLowerCase()===v||p.name.toLowerCase().includes(v));if(u)l?S(`Switched to model: ${u.name} (new task)`):m(`Switched to model: ${u.name}`),a(u.id),c(void 0),h(null),dt.setDefaultModel(u.id);else{let p=C.map(x=>x.name).join(", ");m(`Model "${$.value}" not found.
118
- Available: ${p||"none"}`)}}else{let v=C.find(u=>u.id===o)?.name||o;m(o?`Current model: ${v}`:"No model selected. Using agent mode.")}return!0;case"agent":{if(!$.value)return k.length===0?(m("No agents available."),!0):(Tt("agent"),!0);let v=$.value.toLowerCase(),u=k.find(p=>p.id.toLowerCase()===v||p.name.toLowerCase().includes(v));if(u)u.id===l?m(`Switched to agent: ${u.name}`):S(`Switched to agent: ${u.name} (new task)`),c(u.id),a(void 0);else{let p=k.map(x=>x.name).join(", ");m(`Agent "${$.value}" not found.
119
- Available: ${p||"none"}`)}return!0}case"skills":{if(!$.value)return Tt("skills"),!0;let v=$.value.toLowerCase();return(Jt.length>0?Promise.resolve(Jt):_e().catch(()=>[])).then(p=>{let x=p.find(b=>b.id.toLowerCase()===v||b.name.toLowerCase().includes(v));m(x?`Skill: ${x.name}
120
- ${x.description}
121
- Provider: ${x.provider}
122
- Author: ${x.author.name}
123
- ID: ${x.id}`:`Skill "${$.value}" not found.`)}),!0}case"schedules":{if(!$.value)return Tt("schedules"),!0;let v=$.value.toLowerCase();return(Gt.length>0?Promise.resolve(Gt):$e().catch(()=>[])).then(p=>{let x=p.find(b=>b.id.toLowerCase()===v||b.name.toLowerCase().includes(v));if(x){let b=x.nextRunAt?new Date(x.nextRunAt).toLocaleString():"-";m(`Schedule: ${x.name}
124
- Agent: ${x.agent.name}
125
- Status: ${x.isActive?"Active":"Paused"}
126
- Repeat: ${Vi(x.config)}
127
- Next Run: ${b}
128
- ID: ${x.id}`)}else m(`Schedule "${$.value}" not found.`)}),!0}case"connectors":{if(l){let u=d?.connectors??[];if(u.length===0)m("No agent connectors.");else{let p=u.map(x=>` - ${x.name}`).join(`
129
- `);m(`Agent connectors:
130
- ${p}`)}return!0}let v=E.filter(u=>f?.includes(u.id));if(v.length===0)m("No active connectors.");else{let u=v.map(p=>` - ${p.name}`).join(`
131
- `);m(`Active connectors:
132
- ${u}`)}return!0}case"capabilities":{if(l){let p=(d?.capabilities??[]).map(x=>z.get(x)??x);return m(p.length>0?`Agent capabilities:
133
- ${p.map(x=>` - ${x}`).join(`
134
- `)}`:"No agent capabilities."),!0}let v=[];return g&&v.push("FileSystem"),m(v.length>0?`Active capabilities:
135
- ${v.map(u=>` - ${u}`).join(`
136
- `)}`:"No capabilities enabled."),!0}case"tasks":return m(n?`Current task: ${n}`:`Current task: ${s.slice(0,8)}...`),!0;case"workspace":{if(!R)return m("Not authenticated."),!0;let v=new mt;if(!$.value){try{let{workspaces:p}=await v.getWorkspaces(R.accessToken);if(p.length===0)m("No workspaces found.");else{let x=p.map(b=>` ${b.id===R.workspaceId?"* ":" "}${b.name}
137
- ID: ${b.id}`);m(`Workspaces:
138
- ${x.join(`
139
- `)}`)}}catch(p){m(`Failed to load workspaces: ${p instanceof Error?p.message:"Unknown error"}`)}return!0}let u=$.value;try{let{workspaces:p}=await v.getWorkspaces(R.accessToken),x=p.find(b=>b.id===u);if(!x)return m(`Workspace not found: ${u}`),!0;await we.saveWorkspaceId(u),m(`Switched to workspace: ${x.name}`),m("Please restart the task to apply changes.")}catch(p){m(`Failed to switch workspace: ${p instanceof Error?p.message:"Unknown error"}`)}return!0}case"budget":{if(!R)return m("Not authenticated."),!0;let v=new mt;if(!$.value){try{let x=await v.getBudget(R.accessToken,R.workspaceId);x.budget===null?m("No budget set for this workspace."):m(`Current budget: $${x.budget}`)}catch(x){m(`Failed to get budget: ${x instanceof Error?x.message:"Unknown error"}`)}return!0}let u=$.value.toLowerCase();if(u==="clear"||u==="null"){try{await v.updateBudget(R.accessToken,R.workspaceId,null),m("Budget cleared.")}catch(x){m(`Failed to clear budget: ${x instanceof Error?x.message:"Unknown error"}`)}return!0}let p=Number.parseFloat(u);if(Number.isNaN(p)||p<0)return m("Invalid budget amount. Must be a positive number."),!0;try{await v.updateBudget(R.accessToken,R.workspaceId,u),m(`Budget set to: $${u}`)}catch(x){m(`Failed to set budget: ${x instanceof Error?x.message:"Unknown error"}`)}return!0}case"usage":{if(!R)return m("Not authenticated."),!0;let v=new mt;try{let u=[],p,x=0,b=10;do{let gt=await v.getMonthlyUsages(R.accessToken,R.workspaceId,{nextKey:p,limit:20});if(u.push(...gt.monthlyUsages),p=gt.nextKey,x++,x>=b){m(`Warning: Showing first ${u.length} entries (pagination limit reached)`);break}}while(p);if(u.length===0)return m("No usage data found for this workspace."),!0;let B=0,et=0;for(let gt of u)B+=Number.parseFloat(gt.totalCost),et+=gt.operationCount;let Et=[...u].toSorted((gt,ye)=>Number.parseFloat(ye.totalCost)-Number.parseFloat(gt.totalCost)),H=10,ut=Et.slice(0,H),Pt=[`Total Cost: $${B.toFixed(2)}`,`Total Operations: ${et.toLocaleString()}`,`Users: ${u.length}`,"",`Top ${ut.length} Users by Cost:`,...ut.map(gt=>` ${gt.user.name}: $${Number.parseFloat(gt.totalCost).toFixed(2)} (${gt.operationCount.toLocaleString()} ops)`)];u.length>H&&(Pt.push("",`... and ${u.length-H} more users`),Pt.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),m(Pt.join(`
140
- `))}catch(u){m(`Failed to get usage: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"status":{let v=lt.getCurrentProfileName(),u=o?C.find(B=>B.id===o)?.name||o:null,p=l?k.find(B=>B.id===l)?.name||l:null,x=f?E.filter(B=>f.includes(B.id)).map(B=>B.name):[],b=[];return g&&b.push("FileSystem"),we.getEmail().then(B=>{let et=[`Profile: ${v}${v==="default"?"":" (non-default)"}`,B?`Logged in as: ${B}`:"Not logged in",R?.workspaceId?`Workspace: ${R.workspaceId}`:null,I?`Task ID: ${s}`:null,u?`Model: ${u}`:null,p?`Agent: ${p}`:null,`Connectors: ${x.length>0?x.join(", "):"none"}`,`Capabilities: ${b.length>0?b.join(", "):"none"}`].filter(Boolean);m(et.join(`
141
- `))}).catch(()=>{let B=[`Profile: ${v}`,"Not logged in",I?`Task ID: ${s}`:null,u?`Model: ${u}`:null,p?`Agent: ${p}`:null,`Connectors: ${x.length>0?x.join(", "):"none"}`,`Capabilities: ${b.length>0?b.join(", "):"none"}`].filter(Boolean);m(B.join(`
142
- `))}),!0}case"profile":{let v=$.value?$.value.split(/\s+/).filter(Boolean):[];if(v.length===0)return Tt("profile"),!0;let u=v[0]?.toLowerCase()||"list",p=v[1],x=v[2],b=lt.getProfileNames(),B=lt.getCurrentProfileName(),et=lt.getOverrideProfile(),Et=(H,ut=!1)=>{if(H)return H;if(ut&&b.length===1)return b[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(u==="list"){let H=[`Profiles (${b.length}):`];for(let ut of b){let Pt=ut===B?" (current)":"";H.push(` ${ut}${Pt}`)}return m(H.join(`
143
- `)),!0}if(u==="current")return m(`Current profile: ${B}`),!0;if(u==="show"){let H=Et(p,!0),ut=dt.getAll(H),Pt=await we.getAll(H),gt=!!Pt?.accessToken,ye=ut.connectors?.defaults&&ut.connectors.defaults.length>0?ut.connectors.defaults.join(", "):"unset",Qo=[`Profile: ${H}${H===B?" (current)":""}`,`API URL: ${ut.apiUrl??"default"}`,`Hub URL: ${ut.hubUrl??"default"}`,`Model: ${ut.model?.default??"unset"}`,`Connectors: ${ye}`,gt?`Logged in as: ${Pt?.email??"unknown"}`:"Not logged in",gt&&Pt?.workspaceId?`Workspace ID: ${Pt.workspaceId}`:null].filter(Boolean);return m(Qo.join(`
144
- `)),!0}if(u==="create"){let H=p||lt.DEFAULT_PROFILE;return lt.createProfile(H),m(`Profile created: ${H}`),!0}if(u==="use"||u==="switch"){let H=Et(p,!0);return lt.setOverrideProfile(H),lt.setCurrentProfile(H),Ht(H),await Kt(),S(`Switched to profile: ${H} (new task)`),!0}if(u==="delete"||u==="remove"||u==="rm"){let H=Et(p,!0),ut=H===B,Pt=lt.deleteProfile(H);await we.deleteProfileCredentials(H);let gt=`Profile deleted: ${H}`;if(ut)lt.setOverrideProfile(Pt.currentProfile),Ht(Pt.currentProfile),await Kt(),S(`${gt}
145
- Switched to profile: ${Pt.currentProfile} (new task)`);else if(et===H){let ye=lt.getCurrentProfileName();lt.setOverrideProfile(ye),Ht(ye),await Kt(),S(`${gt}
146
- Switched to profile: ${ye} (new task)`)}else m(gt);return!0}if(u==="rename"||u==="move"||u==="mv"){let H=Et(p,!0);if(!x)throw new Error("New profile name is required.");let ut=lt.renameProfile(H,x);return await we.moveProfileCredentials(H,x),m(`Profile renamed: ${H} -> ${x}`),et===H?(lt.setOverrideProfile(x),Ht(x)):ut.currentProfile===x&&Ht(x),!0}if(u==="clone"||u==="copy"){let H=Et(p,!0);if(!x)throw new Error("Target profile name is required.");let ut=dt.getAll(H);return lt.createProfile(x),dt.setAll(ut,x),await we.clear(x),m(`Profile cloned: ${H} -> ${x}`),!0}m(`Unknown profile command: ${u}`)}catch(H){let ut=H instanceof Error?H.message:"Unknown error";m(`Profile error: ${ut}`)}return!0}case"open-in-browser":{let v=oi().hubUrl.replace(/\/$/,""),u=I||N.some(et=>et.role!=="system"),p=R?`/${R.workspaceId}`:"",x=u?`${p}/task/${s}`:`${p}/task/new`,b=l?`?agentId=${encodeURIComponent(l)}`:"",B=`${v}${x}${b}`;try{await jo(B),m(`Opened in browser: ${B}`)}catch(et){m(`Failed to open browser: ${et instanceof Error?et.message:"Unknown error"}
147
- URL: ${B}`)}return!0}case"share":{if(!R)return m("Not authenticated."),!0;if(!(I||N.some(u=>u.role!=="system")))return m("No conversation to share. Start a task first."),!0;try{let p=await new mt().createTaskShare(R.accessToken,R.workspaceId,s,"public"),b=`${oi().hubUrl.replace(/\/$/,"")}/share/${p.id}`;m(`Share link: ${b}`)}catch(u){m(`Failed to create share link: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"delete":return R?I?(kt(!0),m("Delete this task? (y/N)"),!0):(m("No task to delete."),!0):(m("Not authenticated."),!0);case"quit":return rt(),!0;case"unknown":return m(`Unknown command: ${$.input}
148
- Type /help for available commands.`),!0;default:return!1}},[m,C,k,E,Jt,Gt,o,l,f,g,s,n,rt,Tt,S,z,d,I,N,_e,$e,tt,a,c,h,a,Ht,Kt]),ms=ce($=>{if(Ee.current=!1,se){($===""||$.startsWith("/"))&&(e($),$.startsWith("/")&&kt(!1));return}if(e($),Ue($),Vt!==null&&he(null),U&&(D(null),O([])),$.startsWith("/")&&!$.includes(" ")){let v=Uo($);V(v),Z(0),at(v.length>0)}else at(!1),V([])},[U,Vt,se,e]),Ie=ce(($,v=!1)=>{if($>=0&&$<M.length){let u=M[$];at(!1),V([]),u.name==="model"?(e("/model "),Tt("model")):u.name==="agent"?(e("/agent "),Tt("agent")):u.name==="skills"?(e("/skills "),Tt("skills")):u.name==="schedules"?(e("/schedules "),Tt("schedules")):u.name==="connectors"?(e("/connectors "),Tt("connectors")):u.name==="capabilities"?(e("/capabilities "),Tt("capabilities")):u.name==="tasks"?(e("/tasks "),Tt("tasks")):u.name==="profile"?(e("/profile "),Tt("profile")):v?(e(""),ge({type:u.name})):e(`/${u.name}`)}},[M,Tt,e,ge]),ri=ce(async $=>{Ee.current=!1;let v=$.trim();if(!v||se)return;if(U==="model"&&G.length>0){let p=G[Y];p&&(l?S(`Switched to model: ${p.name} (new task)`):m(`Switched to model: ${p.name}`),a(p.id),c(void 0),h(null)),D(null),O([]),e("");return}if(U==="agent"&&G.length>0){let p=G[Y];p&&(p.id===l?m(`Switched to agent: ${p.name}`):S(`Switched to agent: ${p.name} (new task)`),c(p.id),a(void 0)),D(null),O([]),e("");return}if(U==="skills"&&G.length>0){let p=G[Y];if(p){let x=Jt.find(b=>b.id===p.id);x&&m(`Skill: ${x.name}
149
- ${x.description}
150
- Provider: ${x.provider}
151
- Author: ${x.author.name}
152
- ID: ${x.id}`)}D(null),O([]),e("");return}if(U==="schedules"&&G.length>0){let p=G[Y];if(p){let x=Gt.find(b=>b.id===p.id);if(x){let b=x.nextRunAt?new Date(x.nextRunAt).toLocaleString():"-";m(`Schedule: ${x.name}
153
- Agent: ${x.agent.name}
154
- Status: ${x.isActive?"Active":"Paused"}
155
- Repeat: ${Vi(x.config)}
156
- Next Run: ${b}
157
- ID: ${x.id}`)}}D(null),O([]),e("");return}if(U==="connectors"){let p=[...L];y(p.length>0?p:void 0),dt.setDefaultConnectorIds(p);let x=E.filter(b=>L.has(b.id)).map(b=>b.name);m(x.length>0?`Active connectors: ${x.join(", ")}`:"All connectors disabled."),D(null),O([]),e("");return}if(U==="capabilities"){let p=ht.has("fileSystem");w(p),dt.setLocalTools({fileSystem:p});let x=[];p&&x.push("FileSystem"),m(x.length>0?`Active capabilities: ${x.join(", ")}`:"All capabilities disabled."),D(null),O([]),e("");return}if(U==="profile"&&G.length>0){let p=G[Y];if(p){let x=lt.getCurrentProfileName();p.id===x?m(`Already using profile: ${p.name}`):(lt.setOverrideProfile(p.id),lt.setCurrentProfile(p.id),Ht(p.id),Kt(),S(`Switched to profile: ${p.name}`))}D(null),O([]),e("");return}if(X&&M.length>0){Ie(K,!0);return}he(null),Ue(""),ps(p=>p.length>0&&p.at(-1)===v?p:[...p,v]);let u=zo(v);if(u){await ge(u),e(""),at(!1);return}if(nt){m("Please wait for file uploads to complete.");return}e(""),at(!1),F(v)},[F,ge,X,M,K,Ie,U,G,Y,L,ht,E,Jt,Gt,m,e,l,S,a,c,h,y,w,nt,Ht,Kt,se,R,I,s]);return Th(($,v)=>{if(v.ctrl&&$==="c"){if(t.length>0){ms(""),Ee.current=!0,m("Press Ctrl+C again to exit.");return}if(Ee.current){rt();return}rt();return}if(v.ctrl&&$==="o"){W(u=>!u);return}if(se){if(v.escape||v.return||$==="n"||$==="N"){kt(!1),e(""),m("Task deletion cancelled.");return}if($==="y"||$==="Y"){kt(!1),e(""),R&&I&&new mt().deleteTask(R.accessToken,R.workspaceId,s).then(()=>{S("Task deleted. Started a new task.")}).catch(p=>{m(`Failed to delete task: ${p.message||"Unknown error"}`)});return}return}if(U&&G.length>0){if(v.upArrow){T(u=>u<=0?G.length-1:u-1);return}if(v.downArrow){T(u=>u>=G.length-1?0:u+1);return}if(v.escape){D(null),O([]),e("");return}if(v.return){if(U==="model"){let u=G[Y];u&&(l?S(`Switched to model: ${u.name} (new task)`):m(`Switched to model: ${u.name}`),a(u.id),c(void 0),h(null),dt.setDefaultModel(u.id))}else if(U==="agent"){let u=G[Y];u&&(u.id===l?m(`Switched to agent: ${u.name}`):S(`Switched to agent: ${u.name} (new task)`),c(u.id),a(void 0))}else if(U==="skills"){let u=G[Y];if(u){let p=Jt.find(x=>x.id===u.id);p&&m(`Skill: ${p.name}
158
- ${p.description}
159
- Provider: ${p.provider}
160
- Author: ${p.author.name}
161
- ID: ${p.id}`)}}else if(U==="schedules"){let u=G[Y];if(u){let p=Gt.find(x=>x.id===u.id);if(p){let x=p.nextRunAt?new Date(p.nextRunAt).toLocaleString():"-";m(`Schedule: ${p.name}
162
- Agent: ${p.agent.name}
163
- Status: ${p.isActive?"Active":"Paused"}
164
- Repeat: ${Vi(p.config)}
165
- Next Run: ${x}
166
- ID: ${p.id}`)}}}else if(U==="connectors"){let u=[...L];y(u.length>0?u:void 0),dt.setDefaultConnectorIds(u);let p=E.filter(x=>L.has(x.id)).map(x=>x.name);m(p.length>0?`Active connectors: ${p.join(", ")}`:"All connectors disabled.")}else if(U==="capabilities"){let u=ht.has("fileSystem");w(u),dt.setLocalTools({fileSystem:u});let p=[];u&&p.push("FileSystem"),m(p.length>0?`Active capabilities: ${p.join(", ")}`:"All capabilities disabled.")}else if(U==="tasks"){let u=G[Y];if(u){let p=Nt.find(x=>x.id===u.id);p&&R&&(i(p.id),r(p.title||void 0),P(!0),new mt().getMessages(R.accessToken,R.workspaceId,p.id,20).then(({messages:b})=>{let B=b.filter(et=>et.role==="user"||et.role==="assistant").map(et=>({role:et.role,content:Te(et.parts,!1),parts:et.parts})).filter(et=>et.content).toReversed();tt(B),m(`Switched to: ${p.title||"Untitled"}`)}).catch(()=>{m("Failed to load task messages.")}))}}else if(U==="profile"){let u=G[Y];if(u){let p=lt.getCurrentProfileName();u.id===p?m(`Already using profile: ${u.name}`):(lt.setOverrideProfile(u.id),lt.setCurrentProfile(u.id),Ht(u.id),Kt(),S(`Switched to profile: ${u.name}`))}}D(null),O([]),e("");return}if($===" "&&(U==="connectors"||U==="capabilities")){let u=G[Y];u&&(U==="connectors"?_:j)(x=>{let b=new Set(x);return b.has(u.id)?b.delete(u.id):b.add(u.id),b});return}if($==="a"&&(U==="connectors"||U==="capabilities")){(U==="connectors"?_:j)(new Set(G.map(p=>p.id)));return}if($==="n"&&(U==="connectors"||U==="capabilities")){(U==="connectors"?_:j)(new Set);return}return}if(X&&M.length>0){if(v.upArrow){Z(u=>u<=0?M.length-1:u-1);return}if(v.downArrow){Z(u=>u>=M.length-1?0:u+1);return}if(v.escape){at(!1),V([]);return}if(v.tab){Ie(K);return}}if(v.upArrow){if(t.includes(`
167
- `)||ee.length===0)return;if(Vt===null){Ue(t);let p=ee.length-1;he(p),e(ee[p]);return}let u=Math.max(0,Vt-1);he(u),e(ee[u]);return}if(v.downArrow){if(t.includes(`
168
- `)||Vt===null)return;if(Vt>=ee.length-1){he(null),e(ni);return}let u=Vt+1;he(u),e(ee[u])}}),{suggestions:M,suggestionIndex:K,showSuggestions:X,argMode:U,argItems:G,argIndex:Y,selectedConnectorIds:L,selectedCapabilities:ht,deleteConfirmMode:se,handleInputChange:ms,handleSubmit:ri}}import{useCallback as us,useRef as Eh,useState as _h}from"react";function qo({credentials:t,currentModel:e,modelProviders:s,onUploadSuccess:i,onUploadError:n}){let[r,o]=_h([]),a=Eh(0),l=us(w=>{if(!(!Array.isArray(s)||s.length===0)){for(let C of s)if(C.models.some(E=>E.id===w))return C.id;return s[0]?.id}},[s]),c=us(async w=>{if(!t){n?.(w.filename,"Not logged in");return}if(!Array.isArray(s)||s.length===0){n?.(w.filename,"Model providers not loaded yet. Please wait and try again.");return}let C=e?l(e):s[0]?.id;if(!C){n?.(w.filename,"No model provider available");return}let k=`file-${++a.current}`;o(E=>[...E,{id:k,filename:w.filename,mimeType:w.mimeType,status:"uploading"}]);try{let N=await new mt().uploadFile(t.accessToken,t.workspaceId,w,C);o(I=>I.map(P=>P.id===k?{...P,status:"uploaded",fileId:N.id}:P)),i?.(w.filename)}catch(E){let N=E instanceof Error?E.message:"Upload failed";o(I=>I.map(P=>P.id===k?{...P,status:"error",error:N}:P)),n?.(w.filename,N)}},[t,e,l,s,i,n]),d=us(w=>{o(C=>C.filter(k=>k.id!==w))},[]),h=us(()=>{o([])},[]),f=us(()=>r.filter(w=>w.status==="uploaded").map(w=>w.fileId).filter(sn),[r]),y=r.some(w=>w.status==="uploading"),g=r.length>0;return{pendingFiles:r,addFile:c,removeFile:d,clearFiles:h,getUploadedFileIds:f,hasUploadingFiles:y,hasFiles:g}}import{jsx as J,jsxs as ot}from"react/jsx-runtime";var Ih=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Ah=[Yi,Yi,Xi,Xi,ke,ke,ke,ke],Xo=Ih.map((t,e)=>`${Ah[e]??ke}${t}${Q}`).join(`
169
- `),Ph=`${ke}EntryDesk${Q}`,Rh=500;function Nh(t){let e="",s=0;for(;s<t.length;){if(t.charCodeAt(s)===27&&t[s+1]==="["){for(s+=2;s<t.length;){let i=t.charCodeAt(s);if(i>=64&&i<=126){s+=1;break}s+=1}continue}e+=t[s],s+=1}return e}function Fh(t){let e=Nh(t);return Math.max(...e.split(`
170
- `).map(s=>s.length))}function Dh(t){let e=Fh(Xo);return t>=e?Xo:Ph}function Yo({agentId:t,model:e,message:s,taskId:i,taskTitle:n,connectorIds:r,enableFileSystem:o=!0}){let a=process.stdout.columns??80,l=Dh(a),c=tn(null),d=Io(i,n),{state:h,setState:f,messages:y,setMessages:g,input:w,setInput:C,taskId:k,setTaskId:E,currentTaskTitle:N,setCurrentTaskTitle:I,hasPersistedTask:P,setHasPersistedTask:tt,credentials:m,setCredentials:S,currentResponse:F,setCurrentResponse:W,fullOutput:R,setFullOutput:pt,addSystemMessage:st,startNewTask:A}=d,{credentials:z}=Po(f);Qs(()=>{z&&!m&&S(z)},[z,m,S]);let{availableConnectors:nt,availableModels:rt,availableAgents:M,modelProviders:V,loading:K}=Ro(m),{currentModel:Z,setCurrentModel:X,currentAgentId:at,setCurrentAgentId:U,activeConnectorIds:D,setActiveConnectorIds:G}=Bo(e,t,r),O=tn(!1);Qs(()=>{if(!O.current){if(O.current=!0,!e&&!t){let b=dt.getDefaultModel();b&&X(b)}if(!r&&!t){let b=dt.getDefaultConnectorIds();b&&G(b.length>0?b:void 0)}}},[e,t,r,X,G]);let{currentAgentDetails:Y}=Mo(at,m),{fileSystem:T,setFileSystem:L,capabilityLabelMap:_}=Lo(o),{pendingFiles:ht,addFile:j,removeFile:Nt,clearFiles:fs,getUploadedFileIds:Jt,hasUploadingFiles:ii,hasFiles:Gt}=qo({credentials:m,currentModel:Z,modelProviders:V,onUploadSuccess:b=>{st(`\u2713 Attached: ${b}`)},onUploadError:(b,B)=>{st(`\u2717 Failed to upload ${b}: ${B}`)}}),{sendMessage:We}=Do({taskId:k,credentials:m,currentAgentId:at,currentModel:Z,activeConnectorIds:D,localTools:T,fullOutput:R,setMessages:g,setState:f,setCurrentResponse:W,setCredentials:S,setHasPersistedTask:tt,getFileIds:Jt,clearFiles:fs}),ee=Qi(b=>{A(b),W("")},[A]),[ps,Vt]=$h(!1),he=Qi(async b=>{let B=b.text.trim(),et=Vs(B);if(/^https?:\/\//.test(et))return;if(await Co(B)&&To(et)){let H=await Eo(B);H&&(b.preventDefault(),await j(H))}},[j]),ni=Qi(async()=>{if(!(ps||h.status!=="ready")){if(K||V.length===0){st("Please wait for resources to load before pasting images.");return}st("Reading clipboard..."),Vt(!0);try{let b=await ko();if(b){let B=`clipboard-${Date.now()}.png`;st(`Uploading: ${B} (${Math.round(b.buffer.length/1024)}KB)`),await j({buffer:b.buffer,filename:B,mimeType:b.mime})}else st("No image found in clipboard. Copy an image first.")}catch(b){let B=b instanceof Error?b.message:"Failed to read clipboard";st(`Clipboard error: ${B}`)}finally{Vt(!1)}}},[j,st,ps,h.status,K,V.length]),{suggestions:Ue,suggestionIndex:Ee,showSuggestions:se,argMode:kt,argItems:_e,argIndex:$e,selectedConnectorIds:Tt,selectedCapabilities:Ht,deleteConfirmMode:Kt,handleInputChange:ge,handleSubmit:ms}=Ho({input:w,setInput:C,taskId:k,setTaskId:E,currentTaskTitle:N,setCurrentTaskTitle:I,currentModel:Z,setCurrentModel:X,currentAgentId:at,setCurrentAgentId:U,currentAgentDetails:Y,setCurrentAgentDetails:()=>{},activeConnectorIds:D,setActiveConnectorIds:G,fileSystem:T,setFileSystem:L,availableModels:rt,availableAgents:M,availableConnectors:nt,messages:y,hasPersistedTask:P,setHasPersistedTask:tt,setMessages:g,addSystemMessage:st,startNewTask:ee,sendMessage:We,setFullOutput:pt,credentials:m,setCredentials:S,setState:f,defaultCapabilities:{fileSystem:o},capabilityLabelMap:_,hasUploadingFiles:ii});Ki((b,B)=>{(B.ctrl||B.meta)&&b==="v"&&ni()},{isActive:h.status==="ready"&&!kt}),Ki((b,B)=>{if(!B.escape)return;let et=Date.now(),Et=c.current;c.current=et,!(!Et||et-Et>Rh)&&(kt||se||(c.current=null,Gt&&fs(),w.length>0&&ge("")))},{isActive:h.status==="ready"}),Ki((b,B)=>{B.return&&(ee("Started a new task."),f({status:"ready"}))},{isActive:h.status==="error"}),Qs(()=>{if(m&&!K&&h.status==="loading")if(!Z&&!at){let b=dt.getDefaultModel(),B=b&&rt.some(Et=>Et.id===b),et=B?b:rt[0]?.id;et?(B||dt.setDefaultModel(et),X(et),f({status:"ready"})):M.length===0?f({status:"no-model"}):f({status:"ready"})}else f({status:"ready"})},[m,K,Z,at,rt,M,h.status,X,f]);let Ie=tn(!1);if(Qs(()=>{Ie.current||s&&m&&h.status==="ready"&&(Ie.current=!0,We(s))},[m,s,h.status,We]),h.status==="loading")return ot(St,{flexDirection:"column",children:[J(q,{children:l}),ot(St,{children:[J(q,{color:"cyan",children:J(Zi,{type:"dots"})}),J(q,{children:" Initializing task..."})]})]});if(h.status==="not-logged-in")return ot(St,{flexDirection:"column",children:[J(q,{children:l}),J(q,{color:"yellow",children:"Not logged in"}),J(q,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return ot(St,{flexDirection:"column",children:[J(q,{children:l}),J(q,{color:"yellow",children:"No workspace selected"}),J(q,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return ot(St,{flexDirection:"column",children:[J(q,{children:l}),J(q,{color:"yellow",children:"No model or agent specified"}),i&&J(q,{dimColor:!0,children:"Could not determine the model used in this task."}),J(q,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),J(q,{dimColor:!0,children:"Example: entrydesk task -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return ot(St,{flexDirection:"column",children:[J(q,{children:l}),ot(q,{color:"red",children:["Error: ",h.message]}),J(q,{dimColor:!0,children:"Press Enter to start a new task, or Ctrl+C to exit"})]});let ri=at?Y?Y.connectors&&Y.connectors.length>0?Y.connectors.map(b=>b.name).join(", "):"none":"loading...":D&&D.length>0?nt.filter(b=>D.includes(b.id)).map(b=>b.name).join(", ")||`${D.length} connector(s)`:"none",$=[];if(at)if(Y?.capabilities)for(let b of Y.capabilities)$.push(_.get(b)??b);else $.push("loading...");T&&$.push("FileSystem");let v=lt.getCurrentProfileName(),u=v!=="default",p=(()=>{switch(kt){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:";default:return"Select task:"}})(),x=(()=>{if(kt==="connectors")return Tt;if(kt==="capabilities")return Ht})();return ot(St,{flexDirection:"column",children:[ot(St,{marginBottom:1,flexDirection:"column",children:[J(q,{children:l}),ot(St,{children:[J(q,{bold:!0,color:"cyan",children:N?`Continuing: ${N}`:"EntryDesk CLI"}),ot(q,{dimColor:!0,children:[" v","1.29.0"]}),u&&ot(q,{color:"magenta",children:[" [",v,"]"]}),J(q,{dimColor:!0,children:" (type /help for commands)"})]})]}),y.map((b,B)=>{let et=b.parts&&R?Te(b.parts,!0):b.content,Et=b.role==="user"?"green":b.role==="system"?"yellow":"blue",H=b.role==="user"?"You":b.role==="system"?"System":"Assistant";return ot(St,{flexDirection:"column",marginBottom:1,children:[ot(q,{bold:!0,color:Et,children:[H,":"]}),J(qi,{text:et})]},B)}),F&&ot(St,{flexDirection:"column",marginBottom:1,children:[J(q,{bold:!0,color:"blue",children:"Assistant:"}),J(qi,{text:F})]}),h.status==="ready"&&J(ro,{suggestions:Ue,activeIndex:Ee,visible:se}),h.status==="ready"&&kt&&J(no,{items:_e,activeIndex:$e,pageSize:kt==="agent"||kt==="skills"||kt==="model"?5:10,selectedIds:x,multiSelect:kt==="connectors"||kt==="capabilities",visible:!0,title:p}),h.status==="sending"&&!F?ot(St,{children:[J(q,{color:"cyan",children:J(Zi,{type:"dots"})}),J(q,{children:" Thinking..."})]}):h.status==="ready"&&!kt?ot(St,{flexDirection:"column",children:[Kt&&J(St,{marginBottom:1,children:J(q,{color:"yellow",children:"\u26A0\uFE0F Delete this task? (y/N) "})}),Gt&&!Kt&&ot(St,{marginBottom:1,flexDirection:"row",gap:1,children:[J(q,{dimColor:!0,children:"Attachments:"}),ht.map((b,B)=>ot(q,{children:[b.status==="uploading"?ot(q,{color:"yellow",children:[J(Zi,{type:"dots"})," ",b.filename]}):b.status==="error"?ot(q,{color:"red",children:["\u2717 ",b.filename]}):ot(q,{color:"green",children:["\u2713 ",b.filename]}),B<ht.length-1&&J(q,{children:", "})]},b.id))]}),ot(St,{children:[J(q,{color:"green",children:"> "}),J(po,{value:w,onChange:ge,onSubmit:ms,onPaste:he,leadingOffset:2,multiline:!0})]})]}):null,ot(St,{marginTop:1,flexDirection:"column",children:[ot(St,{gap:2,children:[ot(q,{children:[J(q,{dimColor:!0,children:"Model: "}),J(q,{color:"magenta",children:at?Y?.model?.name||"loading...":rt.find(b=>b.id===Z)?.name||Z||"none"})]}),ot(q,{children:[J(q,{dimColor:!0,children:"Connectors: "}),J(q,{color:"cyan",children:ri})]}),ot(q,{children:[J(q,{dimColor:!0,children:"Capabilities: "}),J(q,{color:"green",children:$.length>0?$.join(", "):"none"})]})]}),ot(q,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",R?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Wh}from"react/jsx-runtime";function Yp(){console.log(`
171
- Usage: entrydesk task [options]
172
-
173
- Send a message to a model or agent, or start an interactive session.
174
-
175
- Options:
176
- -m, --message <text> Message to send (or pipe via stdin)
177
- --model <modelId> Model to use
178
- -a, --agent <agentId> Agent to use (instead of --model)
179
- -c, --continue <n> Continue recent task #n
180
- -i, --interactive Interactive mode (continuous chat)
181
- --connectors id1,id2 Use specific connectors
182
- --plain Plain text output
183
- --output stream-json Stream events as JSON
184
- --full-output Show full tool outputs
185
- --no-file-system Disable local file operations
186
- --json Output JSON
187
-
188
- Examples:
189
- entrydesk task -m "Hello" --model <model>
190
- entrydesk task -m "Hello" -a <agentId>
191
- entrydesk task -c 1 -m "Follow up" # Continue recent task
192
- entrydesk task -i # Interactive mode
193
- echo "Explain this" | entrydesk task --model <model> # Pipe stdin
194
- entrydesk task -m "Hi" --model <m> --output stream-json
195
- `)}async function Lh(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf8").trim()}async function Mh(t,e,s,i){if(i<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(i>n.length)return console.error(`Task number ${i} not found. You have ${n.length} recent tasks.`),console.error("Use `entrydesk tasks` to see available tasks."),null;let r=n[i-1],o;if(!r.agentId){let{messages:a}=await t.getMessages(e,s,r.id,10);o=a.find(c=>c.role==="assistant"&&c.modelId)?.modelId}return{task:r,modelId:o}}var Ce="\x1B[2m",vt="\x1B[0m",en="\x1B[36m",si="\x1B[33m",ti="\x1B[32m",Vo="stream-json";function Bh(t,e,s,i){t&&e&&(console.error(`Error: Cannot use both ${s} and ${i}`),process.exit(1))}function ei(t,e){let s=e===void 0?{event:t}:{event:t,data:e};process.stdout.write(`${JSON.stringify(s)}
196
- `)}function ds(t,e){if(e)return t;let s=t.split(`
197
- `);if(s.length<=20)return t;let i=s.slice(0,5),n=s.slice(-5),r=s.length-10;return[...i,`${Ce}... (${r} lines omitted, use --full-output to see all) ...${vt}`,...n].join(`
198
- `)}function jh(t){try{return JSON.stringify(t,null,2)}catch{return String(t)}}function Ko(t,e){if(!t)return"(no result)";if(typeof t!="object")return ds(String(t),e);let s=t;if("structuredContent"in s&&s.structuredContent){let i=s.structuredContent,n=[];if(i.stdout&&typeof i.stdout=="string"&&i.stdout.trim()&&n.push(i.stdout.trim()),i.stderr&&typeof i.stderr=="string"&&i.stderr.trim()&&n.push(`${si}[stderr]${vt} ${i.stderr.trim()}`),i.urls&&Array.isArray(i.urls)){let r=i.urls;for(let o of r)o.path&&o.url&&n.push(`${o.path}: ${o.url}`)}return n.length===0&&n.push(JSON.stringify(i,null,2)),ds(n.join(`
199
- `),e)}if("content"in s&&Array.isArray(s.content)){let n=s.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
200
- `);return ds(n||JSON.stringify(t,null,2),e)}return s.type==="text"&&typeof s.content=="string"?ds(s.content,e):ds(JSON.stringify(t,null,2),e)}function Zo(t){try{let s=(typeof t.data=="string"?JSON.parse(t.data):t.data)?.parts;return Array.isArray(s)?s.filter(i=>typeof i=="object"&&i!==null&&i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(""):""}catch{return""}}async function Jp(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 M=await ue();e=M.accessToken,s=M.workspaceId}catch(M){rn(M)}let i=t.output===Vo;t.output&&!i&&(console.error(`Invalid --output value. Supported: ${Vo}`),process.exit(1));let n=!i&&(t.plain||!process.stdout.isTTY),r=dt.getDefaultModel(),o=t.message;!o&&!process.stdin.isTTY&&(o=await Lh());let a=new mt,l,c=!1;async function d(){if(c)return l;c=!0;try{({models:l}=await a.listSelectableModels(e,s))}catch{l=void 0}return l}async function h(){let M=await d();if(!M||r&&M.some(K=>K.id===r))return;let V=M[0]?.id;V&&(dt.setDefaultModel(V),r=V)}let f,y,g,w;if(t.continue){let M=await Mh(a,e,s,t.continue);if(M||process.exit(1),f=M.task.id,y=M.task.title??void 0,g=M.task.agentId??void 0,w=M.modelId,w&&!g&&!t.model){let K=await d();K&&!K.some(Z=>Z.id===w)&&(w=void 0)}let V=t.agentId||t.model||g||w||r;!V&&!t.interactive&&(await h(),V=t.agentId||t.model||g||w||r),!V&&!t.interactive&&(n||console.log(`Continuing task: ${M.task.title||"Untitled"}`),console.error(`
201
- Could not determine model for this task. Please specify --model or -a.`),console.error('Example: entrydesk task -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!t.interactive&&console.log(`Continuing task: ${M.task.title||"Untitled"}
202
- `)}let C=t.agentId||g,k=t.model||w||void 0;!C&&!k&&(await h(),k=t.model||w||r||void 0),Bh(t.fileSystem,t.noFileSystem,"--file-system","--no-file-system");let E=dt.getDefaultConnectorIds(),N=t.connectors??E??void 0,I=dt.getLocalTools(),P=t.noFileSystem?!1:t.fileSystem?!0:I?.fileSystem??!0;if(t.interactive){Oh(Wh(Yo,{agentId:C,model:k,message:t.message,taskId:f,taskTitle:y??void 0,connectorIds:N,enableFileSystem:P}),{exitOnCtrlC:!1});return}let tt=!t.continue&&!k&&!C;(!o||tt)&&(console.error("Usage: 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("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent task by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(" --dangerously-auto-approve-tools"),console.error(" Auto-approve all server-side tool calls (required for"),console.error(" non-interactive use with connectors/MCP tools)"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent tasks: entrydesk tasks"),process.exit(1));let m=t.fullOutput??!1,S=t.dangerouslyAutoApproveTools??!1,F=f||Jo(),W=P?js():void 0,R=P?Ws():void 0,pt=M=>{let V={id:F,...S&&{toolApprovalMode:"always_allow"}};return M&&(V.message=M),C?V.agentId=C:(k&&(V.model=k),V.connectorIds=N??[]),W&&(V.clientTools=W),R&&(V.clientToolSystemPrompt=R),V},st=async M=>{if(!M.body)throw new Error("No response body");let V=M.body.getReader(),K=new TextDecoder,Z="",X=new Map,at=[],U=!1,D="";for(;;){let{done:G,value:O}=await V.read();if(G)break;Z+=K.decode(O,{stream:!0});let Y=Z.split(`
203
- `);Z=Y.pop()||"";for(let T of Y){let L=T.trimEnd();if(L==="data: [DONE]"){i&&ei("done");continue}if(L.startsWith("data: "))try{let _=JSON.parse(L.slice(6));if((_.type==="text-delta"||_.type==="reasoning-delta"||_.type==="tool-call"||_.type==="tool-input-available"||_.type==="tool-result"||_.type==="data-appendMessage")&&(U=!0),_.type==="start"&&typeof _.messageId=="string"&&(D=_.messageId),i){_.type==="text-delta"&&_.delta!==void 0?ei("text-delta",_.delta):_.type==="reasoning-delta"&&_.delta!==void 0?ei("reasoning-delta",_.delta):ei(_.type||"event",_);continue}if(n){if(_.type==="text-delta"&&_.delta&&process.stdout.write(_.delta),_.type==="data-appendMessage"&&process.stdout.write(Zo(_)),P&&(_.type==="tool-input-available"||_.type==="tool-call")&&_.toolCallId&&_.toolName&&ae(_.toolName)){let ht=_.args||_.input||{};at.push({toolCallId:_.toolCallId,toolName:_.toolName,args:ht})}continue}switch(_.type){case"reasoning-delta":_.delta&&process.stdout.write(`${Ce}${_.delta}${vt}`);break;case"reasoning-end":process.stdout.write(`
204
-
205
- `);break;case"text-delta":_.delta&&process.stdout.write(_.delta);break;case"data-appendMessage":process.stdout.write(Zo(_));break;case"tool-call-streaming-start":case"tool-input-start":if(_.toolCallId&&_.toolName){X.set(_.toolCallId,{toolName:_.toolName});let j=P&&ae(_.toolName)?`${ti}[LOCAL]${vt} `:"";console.log(`
206
- ${en}\u250C\u2500 ${j}Tool Call: ${_.toolName}${vt}`)}break;case"tool-call":case"tool-input-available":if(_.toolCallId&&_.toolName){let ht=_.args||_.input||{},j=jh(ht);console.log(`${si}\u2502 Arguments:${vt}`);for(let Nt of j.split(`
207
- `))console.log(`${Ce}\u2502 ${Nt}${vt}`);P&&ae(_.toolName)&&(X.set(_.toolCallId,{toolName:_.toolName,args:ht}),at.push({toolCallId:_.toolCallId,toolName:_.toolName,args:ht}))}break;case"tool-result":if(_.toolCallId){let ht=X.get(_.toolCallId),j=Ko(_.result,m);console.log(`${ti}\u2502 Result:${vt}`);for(let Nt of j.split(`
208
- `))console.log(`${Ce}\u2502 ${Nt}${vt}`);console.log(`${en}\u2514\u2500 ${ht?.toolName||"Tool"} completed${vt}
209
- `),X.delete(_.toolCallId)}break;case"error":_.errorText&&console.error(`${Ce}Error: ${_.errorText}${vt}`);break}}catch{}}}return{pendingClientTools:at,hadContent:U,messageId:D}},A=pt({id:Jo(),createdAt:new Date,role:"user",parts:[{type:"text",text:o}]}),z=await a.task(e,s,A),nt=await st(z),rt=nt.hadContent;for(;nt.pendingClientTools.length>0;){let M=nt.messageId,V=[];for(let Z of nt.pendingClientTools){!n&&!i&&console.log(`${ti}\u2502 Executing locally...${vt}`);let X=await Us(Z.toolName,Z.args);if(V.push({type:`tool-${Z.toolName}`,toolCallId:Z.toolCallId,state:"output-available",output:{content:zs(X),isError:!X.success}}),!n&&!i){let at=Ko(X.success?X.result:{error:X.error},m);console.log(`${ti}\u2502 Result:${vt}`);for(let U of at.split(`
210
- `))console.log(`${Ce}\u2502 ${U}${vt}`);console.log(`${en}\u2514\u2500 ${Z.toolName} completed${vt}
211
- `)}}M||(console.error(`${si}Cannot continue: missing assistant message id for tool results.${vt}`),process.exit(1));let K=pt({id:M,role:"assistant",parts:V});z=await a.task(e,s,K),nt=await st(z),rt=rt||nt.hadContent}rt||(console.error(`${si}No response received from the server (empty stream).${vt}`),console.error(`${Ce}The task may have failed server-side. Re-run with DEBUG=1 for details.${vt}`),process.exit(1)),i||console.log("")}export{Yp as printTaskHelp,Jp as runTask};