@entrydesk/cli 1.22.0 → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,210 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as ae,b as fe,c as Bt,g as rt,h as me,n as Je,q as an,r as We,t as cn}from"./chunk-YKH2UWFC.js";import"./chunk-KURQCTT3.js";import{render as ms}from"ink";import{v4 as uo}from"uuid";import{exec as pn}from"child_process";import ho from"fs";import Oe from"fs/promises";import mn from"os";import Ut from"path";import{promisify as yo}from"util";import{glob as wo}from"glob";var xo=yo(pn),ko=`## Filesystem Tool Instructions
3
-
4
- You have access to filesystem tools that allow you to interact with the user's local filesystem.
5
-
6
- ### Available Operations
7
-
8
- - **Read File**: Read the contents of a file
9
- - **Read Multiple Files**: Read multiple files at once (max 10)
10
- - **Write File**: Create or overwrite a file
11
- - **Create Directory**: Create a new directory (including parent directories)
12
- - **List Directory**: List files and subdirectories
13
- - **Search Files**: Search for files matching a glob pattern
14
- - **Get File Info**: Get metadata about a file or directory
15
- - **Move File**: Move or rename a file or directory
16
- - **Execute Command**: Run shell commands on the user's machine
17
-
18
- ### Important Notes
19
-
20
- - Always use absolute paths when possible
21
- - Be mindful of file permissions and access restrictions
22
- - Large files will be truncated in responses
23
- - Search results are limited to prevent overwhelming responses
24
- - Execute Command has a default timeout of 30 seconds (max 5 minutes)
25
- - The current working directory is: ${process.cwd()}
26
- - The user's home directory is: ${mn.homedir()}
27
- `,To=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{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"]}},{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."}},required:["path","content"]}},{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"]}},{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"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{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"]}},{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"]}},{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"]}}];function gn(){return{name:"filesystem",systemPrompt:ko,tools:To}}function De(e){return e.startsWith("~/")?Ut.join(mn.homedir(),e.slice(2)):e}function yt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
28
-
29
- ... (truncated, ${e.length-t} more characters)`}function hn(e){return e&&typeof e=="object"&&"code"in e?String(e.code):void 0}function un(e){let t=hn(e),n=e instanceof Error?e.message:String(e);switch(t){case"EACCES":case"EPERM":return`${n}
30
- 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`${n}
31
- The path does not exist.`;case"ENOTDIR":return`${n}
32
- A component of the path is not a directory.`;case"EISDIR":return`${n}
33
- The path is a directory, not a file.`;default:return n}}var dn=!1;function fn(e){if(process.platform!=="darwin"||dn||!process.stdout.isTTY)return;let t=hn(e);t!=="EPERM"&&t!=="EACCES"||(dn=!0,pn('open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"',()=>{}))}async function yn(e,t){try{switch(e){case"filesystem__read_file":{let n=De(t.path),s=await Oe.readFile(n,"utf-8");return{success:!0,result:yt(s)}}case"filesystem__read_multiple_files":{let n=t.paths.slice(0,10),s={};for(let l of n){let a=De(l);try{let m=await Oe.readFile(a,"utf-8");s[l]=yt(m,5e4)}catch(m){fn(m),s[l]={error:un(m)}}}return{success:!0,result:s}}case"filesystem__write_file":{let n=De(t.path),s=t.content;return await Oe.mkdir(Ut.dirname(n),{recursive:!0}),await Oe.writeFile(n,s,"utf-8"),{success:!0,result:{written:n}}}case"filesystem__create_directory":{let n=De(t.path);return await Oe.mkdir(n,{recursive:!0}),{success:!0,result:{created:n}}}case"filesystem__list_directory":{let n=De(t.path);return{success:!0,result:(await Oe.readdir(n,{withFileTypes:!0})).map(a=>({name:a.name,type:a.isDirectory()?"directory":a.isFile()?"file":a.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let n=t.pattern,s=t.cwd?De(t.cwd):process.cwd(),l=await wo(n,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:l.slice(0,100),total:l.length,truncated:l.length>100}}}case"filesystem__get_file_info":{let n=De(t.path),s=await Oe.stat(n);return{success:!0,result:{path:n,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let n=De(t.source),s=De(t.destination);return await Oe.mkdir(Ut.dirname(s),{recursive:!0}),await Oe.rename(n,s),{success:!0,result:{moved:{from:n,to:s}}}}case"filesystem__execute_command":{let n=t.command,s=t.cwd?De(t.cwd):process.cwd(),l=Math.min(t.timeout||3e4,3e5);if(!ho.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:a,stderr:m}=await xo(n,{cwd:s,timeout:l,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:yt(a,5e4),stderr:yt(m,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(n){return fn(n),{success:!1,error:un(n)}}}function jt(e){return e.startsWith("filesystem__")}function wn(){return[gn()]}function wt(){return wn().flatMap(e=>e.tools)}function xt(){return wn().map(e=>e.systemPrompt).filter(Boolean).join(`
34
-
35
- `)}function Be(e){return jt(e)}async function kt(e,t){return jt(e)?yn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as ye,Text as U,useInput as nn}from"ink";import on from"ink-spinner";import{useCallback as sn,useEffect as Et,useRef as rn,useState as is}from"react";import{Box as Tt,Text as it}from"ink";import{jsx as bt,jsxs as lt}from"react/jsx-runtime";function xn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function kn({items:e,activeIndex:t,selectedIds:n,multiSelect:s=!1,visible:l,title:a,pageSize:m=10}){if(!l||e.length===0)return null;let h=process.stdout.columns??80,y=s?4:0,g=Math.max(20,h-2-2-y),j=Math.max(1,m),$=Math.floor(t/j)*j,P=Math.min(e.length,$+j),Q=e.slice($,P);return lt(Tt,{flexDirection:"column",marginBottom:1,children:[bt(it,{bold:!0,color:"cyan",children:a}),bt(Tt,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:Q.map((b,k)=>{let N=$+k===t,V=n?.has(b.id),Z=xn(b.name,g),q=b.description?xn(b.description,Math.max(0,g-y)):"",M=s?" ".repeat(y):"";return lt(Tt,{paddingX:1,flexDirection:"column",children:[lt(Tt,{children:[s&&bt(it,{color:V?"green":"gray",children:V?"[\u2713] ":"[ ] "}),bt(it,{backgroundColor:N?"cyan":void 0,color:N?"black":V?"green":"white",bold:!0,children:Z})]}),q&&lt(it,{dimColor:!0,children:[M,"\xB7 ",q]})]},b.id)})}),lt(it,{dimColor:!0,children:[s?"\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",e.length>j?` \xB7 Showing ${$+1}-${P} of ${e.length}`:""]})]})}import{Box as Mt,Text as at}from"ink";import{jsx as ct,jsxs as Wt}from"react/jsx-runtime";function Tn({suggestions:e,activeIndex:t,visible:n}){return!n||e.length===0?null:Wt(Mt,{flexDirection:"column",marginBottom:1,children:[ct(Mt,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,l)=>{let a=l===t,m=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Wt(Mt,{paddingX:1,children:[Wt(at,{backgroundColor:a?"cyan":void 0,color:a?"black":"cyan",bold:a,children:["/",s.name]}),ct(at,{dimColor:!0,children:m}),ct(at,{children:" - "}),ct(at,{color:a?"white":"gray",children:s.description})]},s.name)})}),ct(at,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as bo,Text as bn,useInput as Co,useStdout as $o}from"ink";import{useCallback as Cn,useEffect as $n,useMemo as Gt,useRef as In,useState as vn}from"react";import{jsx as Jt}from"react/jsx-runtime";function Ct(e,t){return e<0?0:e>t?t:e}function Ht(e){return Array.from(e)}function $t(e){return/\s/.test(e)}function qt(e,t){let n=t;for(;n>0&&$t(e[n-1]??"");)n-=1;for(;n>0&&!$t(e[n-1]??"");)n-=1;return n}function Sn(e,t){let n=t;for(;n<e.length&&$t(e[n]??"");)n+=1;for(;n<e.length&&!$t(e[n]??"");)n+=1;return n}function Io(e){let t=[],n=[],s=[],l=0;n.push(0),e.forEach((m,h)=>{if(m===`
36
- `){t.push(s),s=[],l=h+1,n.push(l);return}s.push(m)}),t.push(s);let a=t.map(m=>m.length);return{lines:t,lineStarts:n,lineLengths:a}}function Pn(e,t,n){for(let l=0;l<t.length;l+=1){let a=t[l]??0,m=n[l]??0,h=a+m;if(e<=h)return{row:l,col:e-a}}let s=Math.max(0,t.length-1);return{row:s,col:n[s]??0}}var vo=2;function _n({value:e,onChange:t,onSubmit:n,onPaste:s,focus:l=!0,leadingOffset:a=0,multiline:m=!1}){let[h,y]=vn(()=>Ht(e).length),g=In(null),[j,$]=vn(0),P=In(null),{stdout:Q}=$o(),b=Gt(()=>Ht(e),[e]),{lines:k,lineStarts:E,lineLengths:N}=Gt(()=>Io(b),[b]),{row:V,col:Z}=Gt(()=>Pn(h,E,N),[h,E,N]),q=Math.max(1,(Q?.columns??80)-a);$n(()=>{g.current!==e?(y(b.length),P.current=null):y(i=>Ct(i,b.length)),g.current=e},[e,b.length]),$n(()=>{$(i=>{let f=i;Z<f?f=Z:Z>=f+q&&(f=Z-q+1);let _=N[V]??0,W=Z===_?_+1:_,C=Math.max(0,W-q);return f>C&&(f=C),f<0&&(f=0),f})},[q,Z,V,N]);let M=Cn((i,f)=>{g.current=i,t(i),y(f),P.current=null},[t]),ce=Cn(async(i,f)=>{if(!l)return;let{row:_,col:W}=Pn(h,E,N),C=k[_]??[],pe=N[_]??0,te=k.length>1;if(m&&(f.meta&&f.return||f.ctrl&&i==="j"||f.shift&&f.return)){let T=[...b.slice(0,h),`
37
- `,...b.slice(h)].join("");M(T,h+1);return}if(f.return){n(e);return}if(f.leftArrow){f.ctrl||f.meta?(W===0&&_>0?y(E[_]-1):y(E[_]+qt(C,W)),P.current=null):(W===0&&_>0?y(E[_]-1):y(T=>Ct(T-1,b.length)),P.current=null);return}if(f.rightArrow){f.ctrl||f.meta?(W>=pe&&_<k.length-1?y(E[_+1]):y(E[_]+Sn(C,W)),P.current=null):(W>=pe&&_<k.length-1?y(E[_+1]):y(T=>Ct(T+1,b.length)),P.current=null);return}if(m&&te&&f.upArrow){let T=P.current??W,F=Math.max(0,_-1),oe=Math.min(T,N[F]??0);y((E[F]??0)+oe),P.current=T;return}if(m&&te&&f.downArrow){let T=P.current??W,F=Math.min(k.length-1,_+1),oe=Math.min(T,N[F]??0);y((E[F]??0)+oe),P.current=T;return}if(f.ctrl){if(i==="a"){y(E[_]??0),P.current=null;return}if(i==="e"){y((E[_]??0)+pe),P.current=null;return}if(i==="u"){if(W>0){let T=E[_]??0,F=[...b.slice(0,T),...b.slice(h)].join("");M(F,T)}return}if(i==="k"){if(W<pe){let T=(E[_]??0)+pe,F=[...b.slice(0,h),...b.slice(T)].join("");M(F,h)}return}if(i==="w"){if(W===0&&_>0){let F=[...b.slice(0,h-1),...b.slice(h)].join("");M(F,h-1);return}let T=qt(C,W);if(T!==W){let F=(E[_]??0)+T,oe=[...b.slice(0,F),...b.slice(h)].join("");M(oe,F)}return}if(i==="d"){if(h<b.length){let T=[...b.slice(0,h),...b.slice(h+1)].join("");M(T,h)}return}return}if(f.meta){i==="b"?(W===0&&_>0?y(E[_]-1):y(E[_]+qt(C,W)),P.current=null):i==="f"&&(W>=pe&&_<k.length-1?y(E[_+1]):y(E[_]+Sn(C,W)),P.current=null);return}if(f.backspace||f.delete){if(h<=0)return;let T=[...b.slice(0,h-1),...b.slice(h)].join("");M(T,h-1);return}if(!(f.tab||f.escape)&&i.length>0){let T=m?i.replace(/\r\n/g,`
38
- `).replace(/\r/g,`
39
- `):i.replace(/\r?\n/g,"");if(!T||(T=T.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!T))return;if((T.length>=vo||T.includes(`
40
- `))&&s){let A=!1,Y={text:T,preventDefault:()=>{A=!0}};if(await Promise.resolve(s(Y)),A)return}let oe=Ht(T),se=[...b.slice(0,h),...oe,...b.slice(h)].join("");M(se,h+oe.length)}},[b,h,l,N,E,k,m,s,n,M,e]);return Co(ce,{isActive:l}),Jt(bo,{flexDirection:"column",children:k.map((i,f)=>{let _=f===V,C=(_&&Z===i.length?[...i," "]:i).slice(j,j+q),pe=C.join("");if(!_)return Jt(bn,{children:pe||" "},f);let te=Ct(Z-j,Math.max(0,C.length-1)),T=C.slice(0,te).join(""),F=C[te]??" ",oe=C.slice(te+1).join(""),Y=`${T}\x1B[7m${F}\x1B[27m${oe}`;return Jt(bn,{children:Y},f)})})}import{Box as Re,Text as Ge}from"ink";import zt from"react";import{Text as Ie}from"ink";import So from"react";import{Fragment as Eo,jsx as _e,jsxs as An}from"react/jsx-runtime";var Yt=2,Kt=1,Vt=2,Po=1,En=3,Nn=4,_o=({text:e,defaultColor:t,linkColor:n,codeColor:s})=>{let l=t;if(!/[*_~`<[https?:]/.test(e))return _e(Ie,{color:l,children:e});let a=[],m=0,h=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,y;for(;(y=h.exec(e))!==null;){y.index>m&&a.push(_e(Ie,{color:l,children:e.slice(m,y.index)},`t-${m}`));let g=y[0],j=null,$=`m-${y.index}`;try{if(g.startsWith("**")&&g.endsWith("**")&&g.length>Yt*2)j=_e(Ie,{bold:!0,color:l,children:g.slice(Yt,-Yt)},$);else if(g.length>Kt*2&&(g.startsWith("*")&&g.endsWith("*")||g.startsWith("_")&&g.endsWith("_"))&&!/\w/.test(e.substring(y.index-1,y.index))&&!/\w/.test(e.substring(h.lastIndex,h.lastIndex+1))&&!/\S[./\\]/.test(e.substring(y.index-2,y.index))&&!/[./\\]\S/.test(e.substring(h.lastIndex,h.lastIndex+2)))j=_e(Ie,{italic:!0,color:l,children:g.slice(Kt,-Kt)},$);else if(g.startsWith("~~")&&g.endsWith("~~")&&g.length>Vt*2)j=_e(Ie,{strikethrough:!0,color:l,children:g.slice(Vt,-Vt)},$);else if(g.startsWith("`")&&g.endsWith("`")&&g.length>Po){let P=g.match(/^(`+)(.+?)\1$/s);P&&P[2]&&(j=_e(Ie,{color:s,children:P[2]},$))}else if(g.startsWith("[")&&g.includes("](")&&g.endsWith(")")){let P=g.match(/\[(.*?)\]\((.*?)\)/);if(P){let Q=P[1],b=P[2];j=An(Ie,{color:l,children:[Q,An(Ie,{color:n,children:[" (",b,")"]})]},$)}}else g.startsWith("<u>")&&g.endsWith("</u>")&&g.length>En+Nn-1?j=_e(Ie,{underline:!0,color:l,children:g.slice(En,-Nn)},$):g.match(/^https?:\/\//)&&(j=_e(Ie,{color:n,children:g},$))}catch{j=null}a.push(j??_e(Ie,{color:l,children:g},$)),m=h.lastIndex}return m<e.length&&a.push(_e(Ie,{color:l,children:e.slice(m)},`t-${m}`)),_e(Eo,{children:a.filter(g=>g!==null)})},ut=So.memo(_o);import{Fragment as Oo,jsx as ue,jsxs as Fn}from"react/jsx-runtime";var No=1,Ln=1,Ao=1,Do=1,Ro=({content:e})=>{let t=e.join(`
41
- `);return ue(Re,{paddingLeft:Ln,flexDirection:"column",children:ue(Ge,{color:"yellow",children:t})})},Dn=zt.memo(Ro),Lo=({itemText:e,type:t,marker:n,leadingWhitespace:s=""})=>{let l=t==="ol"?`${n}. `:`${n} `,a=l.length,m=s.length;return Fn(Re,{paddingLeft:m+Ao,flexDirection:"row",children:[ue(Re,{width:a,children:ue(Ge,{children:l})}),ue(Re,{flexGrow:Do,children:ue(Ge,{wrap:"wrap",children:ue(ut,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Rn=zt.memo(Lo),Fo=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ue(Re,{paddingLeft:Ln,flexDirection:"column",children:ue(Ge,{wrap:"wrap",children:e})});let n=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,l=/^ *(`{3,}|~{3,}) *(\w*?) *$/,a=/^([ \t]*)([-*+]) +(.*)/,m=/^([ \t]*)(\d+)\. +(.*)/,h=/^ *([-*_] *){3,} *$/,y=/^ *> ?(.*)/,g=[],j=!1,$=!0,P=[],Q="";function b(k){k&&(g.push(k),$=!1)}return n.forEach((k,E)=>{let N=`line-${E}`;if(j){let f=k.match(l);f&&f[1].startsWith(Q[0])&&f[1].length>=Q.length?(b(ue(Dn,{content:P},N)),j=!1,P=[],Q=""):P.push(k);return}let V=k.match(l),Z=k.match(s),q=k.match(a),M=k.match(m),ce=k.match(h),i=k.match(y);if(V)j=!0,Q=V[1];else if(ce)b(ue(Re,{children:ue(Ge,{dimColor:!0,children:"---"})},N));else if(Z){let f=Z[1].length,_=Z[2],W=f<=2?"cyan":"blue";b(ue(Re,{children:ue(Ge,{color:W,...(f===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ue(ut,{text:_,defaultColor:W,linkColor:"cyan",codeColor:"yellow"})})},N))}else if(i){let f=i[1];b(ue(Re,{paddingLeft:1,children:Fn(Ge,{dimColor:!0,children:["> ",ue(ut,{text:f,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},N))}else if(q){let f=q[1],_=q[2],W=q[3];b(ue(Rn,{itemText:W,type:"ul",marker:_,leadingWhitespace:f},N))}else if(M){let f=M[1],_=M[2],W=M[3];b(ue(Rn,{itemText:W,type:"ol",marker:_,leadingWhitespace:f},N))}else k.trim().length===0?$||(g.push(ue(Re,{height:No},`spacer-${E}`)),$=!0):b(ue(Re,{children:ue(Ge,{wrap:"wrap",children:ue(ut,{text:k,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},N))}),j&&b(ue(Dn,{content:P},"line-eof")),ue(Oo,{children:g})},Xt=zt.memo(Fo);import{execFile as Bo}from"child_process";import Uo from"fs";import et from"fs/promises";import On from"os";import vt from"path";import{promisify as jo}from"util";var It=jo(Bo);async function Mo(){let e=vt.join(On.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
42
- set imageData to the clipboard as "PNGf"
43
- set fileRef to open for access POSIX file "${e}" with write permission
44
- set eof fileRef to 0
45
- write imageData to fileRef
46
- close access fileRef
47
- `;return await It("osascript",["-e",t]),(await et.stat(e)).size===0?void 0:{buffer:await et.readFile(e),mime:"image/png"}}catch{return}finally{try{Uo.existsSync(e)&&await et.unlink(e)}catch{}}}async function Wo(){try{let e=`
48
- Add-Type -AssemblyName System.Windows.Forms
49
- $img = [System.Windows.Forms.Clipboard]::GetImage()
50
- if ($img) {
51
- $ms = New-Object System.IO.MemoryStream
52
- $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
53
- [System.Convert]::ToBase64String($ms.ToArray())
54
- }
55
- `,{stdout:t}=await It("powershell.exe",["-command",e]),n=t.trim();if(!n)return;let s=Buffer.from(n,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function Go(){try{let{stdout:e}=await It("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await It("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function Bn(){let e=On.platform();if(e==="darwin")return Mo();if(e==="win32")return Wo();if(e==="linux")return Go()}var Ho=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 Un(e){let t=vt.extname(e).toLowerCase();return Ho.has(t)}function qo(e){let t=vt.extname(e).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"}[t]||"application/octet-stream"}function St(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function jn(e){let t=St(e);if(/^https?:\/\//.test(t))return!1;try{return await et.access(t),!0}catch{return!1}}async function Mn(e){let t=St(e);try{if(!(await et.stat(t)).isFile())return;let s=await et.readFile(t),l=qo(t),a=vt.basename(t);return{buffer:s,mimeType:l,filename:a}}catch{return}}var ve="\x1B[2m",X="\x1B[0m",he="\x1B[36m",tt="\x1B[32m",Wn="\x1B[31m",Ye="\x1B[38;2;59;91;204m",Qt="\x1B[38;2;126;200;248m",Zt="\x1B[38;2;244;196;78m";import{useState as Ue}from"react";import{v4 as Gn}from"uuid";function Hn(e,t){let[n,s]=Ue({status:"loading"}),[l,a]=Ue([]),[m,h]=Ue(""),[y,g]=Ue(()=>e||Gn()),[j,$]=Ue(t),[P,Q]=Ue(!!e),[b,k]=Ue(null),[E,N]=Ue(""),[V,Z]=Ue(!1),q=ce=>{a(i=>[...i,{role:"system",content:ce}])};return{state:n,setState:s,messages:l,setMessages:a,input:m,setInput:h,taskId:y,setTaskId:g,currentTaskTitle:j,setCurrentTaskTitle:$,hasPersistedTask:P,setHasPersistedTask:Q,credentials:b,setCredentials:k,currentResponse:E,setCurrentResponse:N,fullOutput:V,setFullOutput:Z,addSystemMessage:q,startNewTask:ce=>{let i=Gn();g(i),$(void 0),Q(!1),a([]),ce&&q(ce)}}}import{useEffect as Jo,useState as qn}from"react";function Jn(e){let[t,n]=qn(null),[s,l]=qn(!0);return Jo(()=>{let a=!1;async function m(){try{let h=await We();if(a)return;n({accessToken:h.accessToken,workspaceId:h.workspaceId}),l(!1)}catch(h){if(a)return;if(h instanceof Je){if(h.code==="not-logged-in"){e({status:"not-logged-in"}),l(!1);return}if(h.code==="no-workspace"){e({status:"no-workspace"}),l(!1);return}}let y=h instanceof Error?h.message:"Failed to authenticate";e({status:"error",message:y}),l(!1)}}return m(),()=>{a=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Yo,useState as dt}from"react";function Yn(e){let[t,n]=dt([]),[s,l]=dt([]),[a,m]=dt([]),[h,y]=dt([]),[g,j]=dt(!1);return Yo(()=>{if(!e)return;let $=!1;j(!0);async function P(){if(e)try{let Q=new me,[b,k,E,N]=await Promise.all([Q.getConnectors(e.accessToken,e.workspaceId),Q.listSelectableModels(e.accessToken,e.workspaceId),Q.getAgents(e.accessToken,e.workspaceId),Q.getModelProviders(e.accessToken,e.workspaceId)]);if($)return;n(b.connectors),l(k.models),m(E.agents),y(N.providers??[])}catch{}finally{$||j(!1)}}return P(),()=>{$=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:a,modelProviders:h,loading:g}}import nt from"fs";import Vn from"path";import{useCallback as Ko}from"react";import{v4 as Vo}from"uuid";function Kn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let l=String(e);return t||l.length<=200?l:l.slice(0,200)+"..."}let n=e;if("structuredContent"in n&&n.structuredContent){let l=n.structuredContent;if(l.stdout&&typeof l.stdout=="string"){let a=l.stdout.trim();return t||a.length<=200?a:a.slice(0,200)+"..."}}if("content"in n&&Array.isArray(n.content)){let l=n.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
56
- `);return l?t||l.length<=200?l:l.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function Ke(e,t=!1){let n=[];for(let s of e)if(s.type==="text"&&s.text)n.push(s.text);else if(s.type==="reasoning"&&s.text)t?n.push(`${ve}[Thinking]
57
- ${s.text}${X}`):n.push(`${ve}[Thinking...]${X}`);else if(s.type==="tool-call"&&s.toolName){let l=[];if(l.push(`${he}\u250C\u2500 Tool: ${s.toolName}${X}`),s.args){let a=JSON.stringify(s.args,null,t?2:void 0),m=t||a.length<=100?a:a.slice(0,100)+"...";l.push(`${ve}\u2502 Args: ${m}${X}`)}s.result!==void 0?(l.push(`${tt}\u2502 Result: ${Kn(s.result,t)}${X}`),l.push(`${he}\u2514\u2500 completed${X}`)):l.push(`${he}\u2514\u2500${X}`),n.push(l.join(`
58
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let l=s.title||s.type.slice(5).replace(/__/g," "),a=[];if(a.push(`${he}\u250C\u2500 Tool: ${l}${X}`),s.input){let m=JSON.stringify(s.input,null,t?2:void 0),h=t||m.length<=100?m:m.slice(0,100)+"...";a.push(`${ve}\u2502 Input: ${h}${X}`)}s.output!==void 0&&s.state==="output-available"?(a.push(`${tt}\u2502 Output: ${Kn(s.output,t)}${X}`),a.push(`${he}\u2514\u2500 completed${X}`)):s.state==="error"?a.push(`${he}\u2514\u2500 failed${X}`):a.push(`${he}\u2514\u2500${X}`),n.push(a.join(`
59
- `))}return n.join(`
60
-
61
- `).trim()}var Pt=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,n]of this.pendingToolCalls){let s=n.toolName.replace(/__/g," "),l=`
62
-
63
- ${he}\u250C\u2500 Tool: ${s}${X}`;if(n.args){let a=n.args.length>100?n.args.slice(0,100)+"...":n.args;l+=`
64
- ${ve}\u2502 Input: ${a}${X}`}if(n.output){let a=n.output.length>150?n.output.slice(0,150)+"...":n.output;l+=`
65
- ${tt}\u2502 Output: ${a}${X}`}else if(n.status==="executing"){let a=n.startedAt??Date.now(),m=Math.floor((Date.now()-a)/1e3);l+=`
66
- ${he}\u2502${X} (executing... ${m}s)`}else n.status==="preparing"&&(l+=`
67
- ${he}\u2502${X} (preparing...)`);t.push(l)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[n,s]of this.pendingToolCalls){let l=s.toolName.replace(/__/g," "),a=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
68
-
69
- ${he}\u250C\u2500 Tool: ${l}${X}`,a&&(t+=`
70
- ${ve}\u2502 Input: ${a}${X}`),t+=`
71
- ${he}\u2514\u2500 completed${X}
72
- `,this.pendingToolCalls.delete(n)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.args=(n.args||"")+t.inputTextDelta,n.status="executing",n.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.output="",n.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.output=(n.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,n){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let l=s.toolName.replace(/__/g," "),a=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"",m=(s.output||"").length>200?(s.output||"").slice(0,200)+"...":s.output||"";return n+=`
73
-
74
- ${he}\u250C\u2500 Tool: ${l}${X}`,a&&(n+=`
75
- ${ve}\u2502 Input: ${a}${X}`),n+=`
76
- ${tt}\u2502 Output: ${m}${X}`,n+=`
77
- ${he}\u2514\u2500 completed${X}
78
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:n,toolDisplay:this.buildToolDisplay()}}handleToolError(t,n){if(!t.toolCallId)return null;let l=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),a=t.errorText||"Unknown error",m=a.length>200?a.slice(0,200)+"...":a;return n+=`
79
-
80
- ${he}\u250C\u2500 Tool: ${l}${X}`,n+=`
81
- ${Wn}\u2502 Error: ${m}${X}`,n+=`
82
- ${he}\u2514\u2500 failed${X}
83
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:n,toolDisplay:this.buildToolDisplay()}}};var ft=Vn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ne(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
84
- DATA: ${JSON.stringify(t,null,2)}`),s+=`
85
- `;try{nt.appendFileSync(ft,s)}catch{}}function zo(){try{if(nt.existsSync(ft)&&nt.unlinkSync(ft),process.env.DEBUG){let e=Vn.dirname(ft);nt.existsSync(e)||nt.mkdirSync(e,{recursive:!0}),nt.writeFileSync(ft,`=== Debug session started at ${new Date().toISOString()} ===
86
- `)}}catch{}}function _t(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function zn({taskId:e,credentials:t,currentAgentId:n,currentModel:s,activeConnectorIds:l,localTools:a,fullOutput:m,setMessages:h,setState:y,setCurrentResponse:g,setCredentials:j,setHasPersistedTask:$,getFileIds:P,clearFiles:Q}){let b=a?wt():void 0,k=a?xt():void 0;return{sendMessage:Ko(async(N,V,Z)=>{zo(),ne("=== sendMessage called ===",{text:N,localTools:a,clientToolsCount:b?.length});let q=V||t?.accessToken,M=Z||t?.workspaceId;if(!q||!M)try{let f=await We();q=f.accessToken,M=f.workspaceId,j(f)}catch(f){if(f instanceof Je){if(f.code==="not-logged-in"){y({status:"not-logged-in"});return}if(f.code==="no-workspace"){y({status:"no-workspace"});return}}let _=f instanceof Error?f.message:"Authentication failed";y({status:"error",message:_});return}else try{let f=await an();f!==q&&(q=f,j({accessToken:f,workspaceId:M}))}catch(f){if(f instanceof Je&&f.code==="not-logged-in"){y({status:"not-logged-in"});return}let _=f instanceof Error?f.message:"Authentication failed";y({status:"error",message:_});return}h(f=>[...f,{role:"user",content:N}]),y({status:"sending"}),g("");let ce=null,i=null;try{let f=new me,_=P?.()??[],W={id:e,message:{id:Vo(),createdAt:new Date,role:"user",parts:[{type:"text",text:N}]}};_.length>0&&(W.fileIds=_),n?W.agentId=n:(s&&(W.model=s),W.connectorIds=l??[]),b&&(W.clientTools=b),k&&(W.clientToolSystemPrompt=k);let C=await f.task(q,M,W);if(!C.ok){let I=await C.text();throw new Error(`API error ${C.status}: ${I}`)}if(!C.body)throw new Error("No response body from server");ce=C.body.getReader();let pe=new TextDecoder,te="",T="",F="",oe="",se="",A="",Y="",K=new Pt,z=[],O=[],le=[],L=()=>{let I=K.hasExecuting();I&&!i?i=setInterval(()=>{if(!K.hasExecuting()){i&&(clearInterval(i),i=null);return}g(T+K.buildToolDisplay())},1e3):!I&&i&&(clearInterval(i),i=null)};for(;;){let{done:I,value:B}=await ce.read();if(I)break;te+=pe.decode(B,{stream:!0});let v=te.split(`
87
- `);te=v.pop()||"";for(let G of v)if(G.trim()!=="data: [DONE]"&&G.startsWith("data: "))try{let p=JSON.parse(G.slice(6));switch(ne(`SSE event received: ${p.type}`,p),p.type){case"reasoning-start":oe=p.id||"0",F="";break;case"reasoning-delta":p.delta&&(F+=p.delta,g(`${ve}[Thinking...]${X}
88
- ${F}`)),p.providerMetadata?.anthropic?.signature&&(se=p.providerMetadata.anthropic.signature);break;case"reasoning-end":if(F){let S={type:"reasoning",id:oe,text:F,state:"done"};se&&(S.providerMetadata={anthropic:{signature:se}}),O.push(S),ne("Added reasoning to messageParts",{reasoningLength:F.length,hasSignature:!!se,messagePartsCount:O.length})}F="",se="",g("");break;case"text-delta":p.delta&&(K.hasPending()&&(T=K.flushPending(T)),T+=p.delta,A+=p.delta,g(T));break;case"tool-input-start":{let S=K.handleToolInputStart(p);S&&g(T+S),L();break}case"tool-input-delta":{let S=K.handleToolInputDelta(p);S&&g(T+S),L();break}case"tool-call":case"tool-input-available":{if(ne(`=== Tool event: ${p.type} ===`,{toolCallId:p.toolCallId,toolName:p.toolName,localTools:a,isClientToolResult:p.toolName?Be(p.toolName):"no toolName",args:p.args,input:p.input}),p.toolCallId&&p.toolName){let S=_t(p.args??p.input);O.push({type:p.type,toolCallId:p.toolCallId,toolName:p.toolName,args:S}),ne("Added tool to messageParts",{messagePartsCount:O.length})}if(a&&p.toolCallId&&p.toolName&&Be(p.toolName)){let S=_t(p.args??p.input);z.push({toolCallId:p.toolCallId,toolName:p.toolName,args:S}),ne("Added to pendingClientTools",{pendingCount:z.length,pendingClientTools:z}),g(T+K.buildToolDisplay()+`
89
- [Executing ${p.toolName} locally...]`)}else ne("NOT added to pendingClientTools - conditions not met",{localTools:a,hasToolCallId:!!p.toolCallId,hasToolName:!!p.toolName,isClientTool:p.toolName?Be(p.toolName):!1});break}case"tool-output-start":{let S=K.handleToolOutputStart(p);S&&g(T+S),L();break}case"tool-output-delta":{let S=K.handleToolOutputDelta(p);S&&g(T+S),L();break}case"tool-output-end":{let S=K.handleToolOutputEnd(p,T);S&&(T=S.fullResponse,g(T+S.toolDisplay)),L();break}case"tool-input-error":case"tool-output-error":{let S=K.handleToolError(p,T);S&&(T=S.fullResponse,g(T+S.toolDisplay)),L();break}case"start":p.messageId&&(Y=p.messageId,ne("Captured messageId from start event",{messageId:Y}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":p.errorText&&console.error("Stream error:",p.errorText);break}}catch{}}if(A){let I=O.findIndex(v=>v.type!=="reasoning"),B=I===-1?O.length:I;O.splice(B,0,{type:"text",text:A}),ne("Added accumulated text to messageParts",{textLength:A.length,insertIndex:B})}for(ne("=== Initial stream ended ===",{pendingClientToolsCount:z.length,pendingClientTools:z,messagePartsCount:O.length,messageParts:O.map(I=>({type:I.type,toolCallId:I.toolCallId,toolName:I.toolName}))});z.length>0;){ne("=== Starting pending tools execution loop ===",{pendingCount:z.length});let I=[];for(let p of z){ne(`Executing tool: ${p.toolName}`,{toolCallId:p.toolCallId,args:p.args}),K.handleToolInputStart({toolCallId:p.toolCallId,toolName:p.toolName}),K.handleToolInputDelta({toolCallId:p.toolCallId,inputTextDelta:JSON.stringify(p.args)}),g(T+K.buildToolDisplay()),L();let S=await kt(p.toolName,p.args);ne(`Tool execution result: ${p.toolName}`,{success:S.success,resultPreview:S.success?JSON.stringify(S.result).slice(0,200):S.error});let w=S.success?JSON.stringify(S.result):S.error||"Unknown error";if(I.push({toolCallId:p.toolCallId,toolName:p.toolName,content:[{type:"text",text:w}],isError:!S.success}),S.success){K.handleToolOutputStart({toolCallId:p.toolCallId}),K.handleToolOutputDelta({toolCallId:p.toolCallId,outputTextDelta:JSON.stringify(S.result).slice(0,200)});let ie=K.handleToolOutputEnd({toolCallId:p.toolCallId},T);ie&&(T=ie.fullResponse)}else{let ie=K.handleToolError({toolCallId:p.toolCallId,errorText:S.error},T);ie&&(T=ie.fullResponse)}g(T+K.buildToolDisplay()),L()}z.length=0;for(let p of I){let S=O.find(w=>(w.type==="tool-input-available"||w.type==="tool-call")&&w.toolCallId===p.toolCallId);if(S){let w=[];for(let R of p.content)R.type==="text"?w.push(R.text):R.type==="image"?w.push("[Image]"):R.type==="audio"?w.push("[Audio]"):(R.type==="resource"||R.type==="resource_link")&&w.push("[Resource]");let ie=w.join(`
90
- `);le.push({type:`tool-${S.toolName}`,toolName:S.toolName,toolCallId:S.toolCallId,input:S.args,output:ie,isError:p.isError})}}if(ne("=== Sending clientToolResults for continuation ===",{toolResultsCount:I.length,toolResults:I.map(p=>({toolCallId:p.toolCallId,toolName:p.toolName,isError:p.isError}))}),ce)try{ce.releaseLock()}catch{}let B=I.map(p=>({type:`tool-${p.toolName}`,toolCallId:p.toolCallId,state:"output-available",output:{content:p.content,isError:p.isError}}));if(!Y)throw new Error("Cannot continue: missing assistant message id for tool results.");let v={id:e,message:{id:Y,role:"assistant",parts:B}};n?v.agentId=n:(s&&(v.model=s),v.connectorIds=l??[]),b&&(v.clientTools=b),k&&(v.clientToolSystemPrompt=k),ne("=== Sending continuation request ===",{taskId:e,hasAgentId:!!v.agentId,hasModel:!!v.model,clientToolResultsCount:I.length});let G=await f.task(q,M,v);if(ne("=== Continuation response received ===",{ok:G.ok,status:G.status}),!G.ok){let p=await G.text();throw new Error(`Continuation failed: ${G.status}: ${p}`)}if(!G.body)break;for(ne("=== Processing continuation stream ==="),ce=G.body.getReader(),O.length=0,A="",F="",oe="",se="";;){let{done:p,value:S}=await ce.read();if(p){ne("=== Continuation stream done ===");break}te+=pe.decode(S,{stream:!0});let w=te.split(`
91
- `);te=w.pop()||"";for(let ie of w)if(ie.trim()!=="data: [DONE]"&&ie.startsWith("data: "))try{let R=JSON.parse(ie.slice(6));switch(ne(`Continuation SSE: ${R.type}`,R),R.type){case"start":R.messageId&&(Y=R.messageId);break;case"reasoning-start":oe=R.id||"0",F="";break;case"reasoning-delta":R.delta&&(F+=R.delta,g(`${ve}[Thinking...]${X}
92
- ${F}`)),R.providerMetadata?.anthropic?.signature&&(se=R.providerMetadata.anthropic.signature);break;case"reasoning-end":if(F){let $e={type:"reasoning",id:oe,text:F,state:"done"};se&&($e.providerMetadata={anthropic:{signature:se}}),O.push($e),ne("Continuation: Added reasoning to messageParts",{reasoningLength:F.length,hasSignature:!!se,messagePartsCount:O.length})}F="",se="",g(T);break;case"text-delta":R.delta&&(T+=R.delta,A+=R.delta,g(T));break;case"tool-call":case"tool-input-available":if(R.toolCallId&&R.toolName){let $e=_t(R.args??R.input);O.push({type:R.type,toolCallId:R.toolCallId,toolName:R.toolName,args:$e})}if(a&&R.toolCallId&&R.toolName&&Be(R.toolName)){let $e=_t(R.args??R.input);z.push({toolCallId:R.toolCallId,toolName:R.toolName,args:$e}),ne("Continuation: Added to pendingClientTools",{pendingCount:z.length})}break;case"finish":ne("Continuation finish event",R);break}}catch{}}if(A){let p=O.findIndex(w=>w.type!=="reasoning"),S=p===-1?O.length:p;O.splice(S,0,{type:"text",text:A})}ne("=== Continuation stream processing complete ===",{pendingClientToolsCount:z.length,messagePartsCount:O.length,fullResponseLength:T.length})}if(a&&b&&b.length>0){let I=[];for(let v of le)I.push({type:String(v.type),title:String(v.toolName).replace(/__/g," "),input:v.input,output:v.output,state:v.isError?"error":"output-available"});for(let v of O)v.type==="text"&&v.text&&I.push({type:"text",text:v.text});let B=Ke(I,m);ne("=== Using formatted parts for local tools ===",{executedToolsCount:le.length,textPartsCount:O.filter(v=>v.type==="text").length,contentLength:B.length}),h(v=>[...v,{role:"assistant",content:B,parts:I}])}else{ne("=== Fetching message from API ===",{fullResponseLength:T.length,fullResponsePreview:T.slice(0,200)});try{let{messages:I}=await f.getMessages(q,M,e,10);ne("=== API messages received ===",{count:I.length,roles:I.map(v=>v.role)});let B=I.find(v=>v.role==="assistant");if(B){let v=B.parts,G=Ke(v,m);ne("=== Setting message from API ===",{partsCount:v.length,partTypes:v.map(p=>p.type),contentLength:G.length,contentPreview:G.slice(0,200)}),h(p=>[...p,{role:"assistant",content:G,parts:v}])}else ne("=== No assistant message found, using fallback ==="),h(v=>[...v,{role:"assistant",content:T}])}catch(I){ne("=== API fetch failed, using fallback ===",{error:I instanceof Error?I.message:String(I)}),h(B=>[...B,{role:"assistant",content:T}])}}ne("=== Message handling complete ==="),g(""),y({status:"ready"}),$(!0),_.length>0&&Q?.()}catch(f){ne("=== ERROR ===",{message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0});let _=f instanceof Error?f.message:"Failed to send message";y({status:"error",message:_})}finally{if(i&&(clearInterval(i),i=null),ce)try{ce.releaseLock()}catch{}}},[t,e,n,s,l,a,b,k,m,h,y,g,j,$,P,Q])}}import{useState as Xo}from"react";var Xn=new Map([["sandbox","Sandbox"],["web_search","Web Search"],["image_generation","Image Generation"],["chart","Chart"],["file_system","FileSystem"]]);function Qn(e){let[t,n]=Xo(e);return{fileSystem:t,setFileSystem:n,capabilityLabelMap:Xn}}import{useEffect as Qo,useState as Zo}from"react";function Zn(e,t){let[n,s]=Zo(null);return Qo(()=>{let l=!1;async function a(){if(!e||!t){s(null);return}try{let h=await new me().getAgent(t.accessToken,t.workspaceId,e);l||s(h)}catch{l||s(null)}}return a(),()=>{l=!0}},[e,t]),{currentAgentDetails:n}}import{useState as en}from"react";function eo(e,t,n){let[s,l]=en(e),[a,m]=en(t),[h,y]=en(n);return{currentModel:s,setCurrentModel:l,currentAgentId:a,setCurrentAgentId:m,activeConnectorIds:h,setActiveConnectorIds:y}}import{useApp as ts,useInput as ns}from"ink";import{useCallback as je,useRef as os,useState as be}from"react";import{spawn as es}from"child_process";function to(e){return new Promise((t,n)=>{let s,l;process.platform==="darwin"?(s="open",l=[e]):process.platform==="win32"?(s="cmd",l=["/c","start","",e]):(s="xdg-open",l=[e]);let a=es(s,l,{stdio:"ignore",detached:!0});a.once("error",m=>{n(m)}),a.once("spawn",()=>{a.unref(),t()})})}var no=[{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 oo(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?no.filter(n=>n.name.startsWith(t)||n.aliases.some(s=>s.startsWith(t))):no}function so(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),s=n[0]?.toLowerCase(),l=n.slice(1).join(" ");switch(s){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:l||void 0};case"agent":case"a":return{type:"agent",value:l||void 0};case"skills":case"sk":return{type:"skills",value:l||void 0};case"schedules":case"sch":return{type:"schedules",value:l||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:l||void 0};case"budget":case"bg":return{type:"budget",value:l||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:l||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:t}}}var ro=`Available commands:
93
- /help, /h, /? Show this help message
94
- /clear, /cls, /new Start a new task
95
- /model [name], /m Show current model or switch to [name]
96
- /agent [name], /a Show current agent or switch to [name]
97
- /skills [name], /sk List skills or show details for [name]
98
- /schedules [id], /sch List schedules or show details for [id]
99
- /connectors, /conn Select active connectors
100
- /capabilities, /cap Toggle client capabilities (FileSystem)
101
- /tasks, /c Switch to another task
102
- /workspace [id], /ws List or switch workspace
103
- /budget [amount], /bg View or set workspace budget
104
- /usage, /u View current month usage (top 10 by cost)
105
- /status, /s Show current session status
106
- /profile [args], /p Manage profiles (list/show/use/create/delete/rename/clone)
107
- /open-in-browser Open current task in browser
108
- /share Get share link for current task
109
- /delete, /del Delete current task
110
- /quit, /exit, /q Exit interactive mode
111
-
112
- Note: For detailed usage with sorting/limits, use: entrydesk usage --help
113
-
114
- Keyboard shortcuts:
115
- Ctrl+O Toggle full output mode
116
- Ctrl+C Exit`;function tn(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function io({input:e,setInput:t,taskId:n,setTaskId:s,currentTaskTitle:l,setCurrentTaskTitle:a,currentModel:m,setCurrentModel:h,currentAgentId:y,setCurrentAgentId:g,currentAgentDetails:j,setCurrentAgentDetails:$,activeConnectorIds:P,setActiveConnectorIds:Q,fileSystem:b,setFileSystem:k,availableModels:E,availableAgents:N,availableConnectors:V,messages:Z,hasPersistedTask:q,setHasPersistedTask:M,setMessages:ce,addSystemMessage:i,startNewTask:f,sendMessage:_,setFullOutput:W,credentials:C,setCredentials:pe,setState:te,defaultCapabilities:T,capabilityLabelMap:F,hasUploadingFiles:oe=!1}){let{exit:se}=ts(),[A,Y]=be([]),[K,z]=be(0),[O,le]=be(!1),[L,I]=be(null),[B,v]=be([]),[G,p]=be(0),[S,w]=be(new Set),[ie,R]=be(new Set),[$e,mt]=be([]),[Ee,Lt]=be([]),[Se,ot]=be([]),[Le,gt]=be([]),[Ne,Me]=be(null),[Ft,st]=be(""),ze=os(!1),[Fe,xe]=be(!1),Xe=je(async()=>{if(!C)return[];let x=new me,d=[],o;do{let r=await x.listAvailableSkills(C.accessToken,C.workspaceId,{limit:100,nextKey:o});d.push(...r.skills),o=r.nextKey}while(o);return Lt(d),d},[C]),Qe=je(async()=>{if(!C)return[];let x=new me,d=[],o;do{let r=await x.getSchedules(C.accessToken,C.workspaceId,{limit:100,nextKey:o});d.push(...r.schedules),o=r.nextKey}while(o);return ot(d),d},[C]),ke=je(async x=>{if(x==="model"){if(E.length===0){i("No models available.");return}let d=E.map(r=>({id:r.id,name:r.name,description:r.description}));v(d);let o=m?d.findIndex(r=>r.id===m):-1;p(Math.max(o,0)),I("model")}else if(x==="agent"){if(N.length===0){i("No agents available.");return}let d=N.map(r=>({id:r.id,name:r.name,description:r.description}));v(d);let o=y?d.findIndex(r=>r.id===y):-1;p(Math.max(o,0)),I("agent")}else if(x==="skills"){let d=Ee;if(d.length===0)try{d=await Xe()}catch{i("Failed to load skills.");return}if(d.length===0){i("No skills available.");return}let o=d.map(r=>({id:r.id,name:r.name,description:r.description}));v(o),p(0),I("skills")}else if(x==="schedules"){let d=Se;if(d.length===0)try{d=await Qe()}catch{i("Failed to load schedules.");return}if(d.length===0){i("No schedules found.");return}let o=d.map(r=>({id:r.id,name:r.name,description:`${r.agent.name} - ${r.isActive?"Active":"Paused"}`}));v(o),p(0),I("schedules")}else if(x==="connectors"){if(V.length===0){i("No connectors available.");return}let d=V.map(o=>({id:o.id,name:o.name}));v(d),p(0),w(new Set(P??[])),I("connectors")}else if(x==="capabilities"){v([{id:"fileSystem",name:"FileSystem",description:"Local file operations"}]),p(0);let o=new Set;b&&o.add("fileSystem"),R(o),I("capabilities")}else if(x==="tasks"){if(!C){i("Not authenticated.");return}try{let d=new me,{tasks:o}=await d.getTasks(C.accessToken,C.workspaceId,20);if(o.length===0){i("No tasks available.");return}mt(o);let r=o.map(c=>({id:c.id,name:c.title||"Untitled",description:new Date(c.createdAt).toLocaleDateString()}));v(r);let u=r.findIndex(c=>c.id===n);p(Math.max(u,0)),I("tasks")}catch{i("Failed to load tasks.")}}else if(x==="profile"){let d=ae.getProfileNames(),o=ae.getCurrentProfileName(),r=d.map(c=>({id:c,name:c,description:c===o?"(current)":void 0}));v(r);let u=r.findIndex(c=>c.id===o);p(Math.max(u,0)),I("profile")}le(!1),Y([])},[E,N,Ee,Se,V,P,m,y,b,Xe,Qe,C,n,i]),Pe=je(x=>{let d=fe.getAll(x);h(d.model?.default),g(void 0),$(null);let o=d.connectors?.defaults;Q(o&&o.length>0?o:void 0);let r=d.localTools;k(r?.fileSystem??T.fileSystem)},[h,g,$,Q,k,T]),Ae=je(async()=>{try{let x=await We();pe({accessToken:x.accessToken,workspaceId:x.workspaceId}),te({status:"ready"})}catch(x){if(pe(null),x instanceof Je){if(x.code==="not-logged-in"){te({status:"not-logged-in"});return}if(x.code==="no-workspace"){te({status:"no-workspace"});return}}let d=x instanceof Error?x.message:"Failed to authenticate";te({status:"error",message:d})}},[pe,te]),He=je(async x=>{switch(x.type){case"help":return i(ro),!0;case"clear":return f("Started a new task."),!0;case"model":{if(x.value){let d=x.value.toLowerCase(),o=E.find(r=>r.id.toLowerCase()===d||r.name.toLowerCase().includes(d));if(o)y?f(`Switched to model: ${o.name} (new task)`):i(`Switched to model: ${o.name}`),h(o.id),g(void 0),$(null),fe.setDefaultModel(o.id);else{let r=E.map(u=>u.name).join(", ");i(`Model "${x.value}" not found.
117
- Available: ${r||"none"}`)}}else{let d=E.find(o=>o.id===m)?.name||m;i(m?`Current model: ${d}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!x.value)return N.length===0?(i("No agents available."),!0):(ke("agent"),!0);let d=x.value.toLowerCase(),o=N.find(r=>r.id.toLowerCase()===d||r.name.toLowerCase().includes(d));if(o)o.id!==y?f(`Switched to agent: ${o.name} (new task)`):i(`Switched to agent: ${o.name}`),g(o.id),h(void 0);else{let r=N.map(u=>u.name).join(", ");i(`Agent "${x.value}" not found.
118
- Available: ${r||"none"}`)}return!0}case"skills":{if(!x.value)return ke("skills"),!0;let d=x.value.toLowerCase();return(Ee.length>0?Promise.resolve(Ee):Xe().catch(()=>[])).then(r=>{let u=r.find(c=>c.id.toLowerCase()===d||c.name.toLowerCase().includes(d));i(u?`Skill: ${u.name}
119
- ${u.description}
120
- Provider: ${u.provider}
121
- Author: ${u.author.name}
122
- ID: ${u.id}`:`Skill "${x.value}" not found.`)}),!0}case"schedules":{if(!x.value)return ke("schedules"),!0;let d=x.value.toLowerCase();return(Se.length>0?Promise.resolve(Se):Qe().catch(()=>[])).then(r=>{let u=r.find(c=>c.id.toLowerCase()===d||c.name.toLowerCase().includes(d));if(u){let c=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";i(`Schedule: ${u.name}
123
- Agent: ${u.agent.name}
124
- Status: ${u.isActive?"Active":"Paused"}
125
- Repeat: ${tn(u.config)}
126
- Next Run: ${c}
127
- ID: ${u.id}`)}else i(`Schedule "${x.value}" not found.`)}),!0}case"connectors":{if(y){let o=j?.connectors??[];if(o.length===0)i("No agent connectors.");else{let r=o.map(u=>` - ${u.name}`).join(`
128
- `);i(`Agent connectors:
129
- ${r}`)}return!0}let d=V.filter(o=>P?.includes(o.id));if(d.length===0)i("No active connectors.");else{let o=d.map(r=>` - ${r.name}`).join(`
130
- `);i(`Active connectors:
131
- ${o}`)}return!0}case"capabilities":{if(y){let r=(j?.capabilities??[]).map(u=>F.get(u)??u);return i(r.length>0?`Agent capabilities:
132
- ${r.map(u=>` - ${u}`).join(`
133
- `)}`:"No agent capabilities."),!0}let d=[];return b&&d.push("FileSystem"),i(d.length>0?`Active capabilities:
134
- ${d.map(o=>` - ${o}`).join(`
135
- `)}`:"No capabilities enabled."),!0}case"tasks":return i(l?`Current task: ${l}`:`Current task: ${n.slice(0,8)}...`),!0;case"workspace":{if(!C)return i("Not authenticated."),!0;let d=new me;if(!x.value){try{let{workspaces:r}=await d.getWorkspaces(C.accessToken);if(r.length===0)i("No workspaces found.");else{let u=r.map(c=>` ${c.id===C.workspaceId?"* ":" "}${c.name}
136
- ID: ${c.id}`);i(`Workspaces:
137
- ${u.join(`
138
- `)}`)}}catch(r){i(`Failed to load workspaces: ${r instanceof Error?r.message:"Unknown error"}`)}return!0}let o=x.value;try{let{workspaces:r}=await d.getWorkspaces(C.accessToken),u=r.find(c=>c.id===o);if(!u)return i(`Workspace not found: ${o}`),!0;await rt.saveWorkspaceId(o),i(`Switched to workspace: ${u.name}`),i("Please restart the task to apply changes.")}catch(r){i(`Failed to switch workspace: ${r instanceof Error?r.message:"Unknown error"}`)}return!0}case"budget":{if(!C)return i("Not authenticated."),!0;let d=new me;if(!x.value){try{let u=await d.getBudget(C.accessToken,C.workspaceId);u.budget===null?i("No budget set for this workspace."):i(`Current budget: $${u.budget}`)}catch(u){i(`Failed to get budget: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let o=x.value.toLowerCase();if(o==="clear"||o==="null"){try{await d.updateBudget(C.accessToken,C.workspaceId,null),i("Budget cleared.")}catch(u){i(`Failed to clear budget: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let r=parseFloat(o);if(isNaN(r)||r<0)return i("Invalid budget amount. Must be a positive number."),!0;try{await d.updateBudget(C.accessToken,C.workspaceId,o),i(`Budget set to: $${o}`)}catch(u){i(`Failed to set budget: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"usage":{if(!C)return i("Not authenticated."),!0;let d=new me;try{let o=[],r,u=0,c=10;do{let ge=await d.getMonthlyUsages(C.accessToken,C.workspaceId,{nextKey:r,limit:20});if(o.push(...ge.monthlyUsages),r=ge.nextKey,u++,u>=c){i(`Warning: Showing first ${o.length} entries (pagination limit reached)`);break}}while(r);if(o.length===0)return i("No usage data found for this workspace."),!0;let D=0,ee=0;for(let ge of o)D+=parseFloat(ge.totalCost),ee+=ge.operationCount;let Te=[...o].toSorted((ge,qe)=>parseFloat(qe.totalCost)-parseFloat(ge.totalCost)),H=10,de=Te.slice(0,H),Ce=[`Total Cost: $${D.toFixed(2)}`,`Total Operations: ${ee.toLocaleString()}`,`Users: ${o.length}`,"",`Top ${de.length} Users by Cost:`,...de.map(ge=>` ${ge.user.name}: $${parseFloat(ge.totalCost).toFixed(2)} (${ge.operationCount.toLocaleString()} ops)`)];o.length>H&&(Ce.push("",`... and ${o.length-H} more users`),Ce.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),i(Ce.join(`
139
- `))}catch(o){i(`Failed to get usage: ${o instanceof Error?o.message:"Unknown error"}`)}return!0}case"status":{let d=ae.getCurrentProfileName(),o=m?E.find(D=>D.id===m)?.name||m:null,r=y?N.find(D=>D.id===y)?.name||y:null,u=P?V.filter(D=>P.includes(D.id)).map(D=>D.name):[],c=[];return b&&c.push("FileSystem"),rt.getEmail().then(D=>{let ee=[`Profile: ${d}${d!=="default"?" (non-default)":""}`,D?`Logged in as: ${D}`:"Not logged in",C?.workspaceId?`Workspace: ${C.workspaceId}`:null,q?`Task ID: ${n}`:null,o?`Model: ${o}`:null,r?`Agent: ${r}`:null,`Connectors: ${u.length>0?u.join(", "):"none"}`,`Capabilities: ${c.length>0?c.join(", "):"none"}`].filter(Boolean);i(ee.join(`
140
- `))}).catch(()=>{let D=[`Profile: ${d}`,"Not logged in",q?`Task ID: ${n}`:null,o?`Model: ${o}`:null,r?`Agent: ${r}`:null,`Connectors: ${u.length>0?u.join(", "):"none"}`,`Capabilities: ${c.length>0?c.join(", "):"none"}`].filter(Boolean);i(D.join(`
141
- `))}),!0}case"profile":{let d=x.value?x.value.split(/\s+/).filter(Boolean):[];if(d.length===0)return ke("profile"),!0;let o=d[0]?.toLowerCase()||"list",r=d[1],u=d[2],c=ae.getProfileNames(),D=ae.getCurrentProfileName(),ee=ae.getOverrideProfile(),Te=(H,de=!1)=>{if(H)return H;if(de&&c.length===1)return c[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(o==="list"){let H=[`Profiles (${c.length}):`];for(let de of c){let Ce=de===D?" (current)":"";H.push(` ${de}${Ce}`)}return i(H.join(`
142
- `)),!0}if(o==="current")return i(`Current profile: ${D}`),!0;if(o==="show"){let H=Te(r,!0),de=fe.getAll(H),Ce=await rt.getAll(H),ge=!!Ce?.accessToken,qe=de.connectors?.defaults&&de.connectors.defaults.length>0?de.connectors.defaults.join(", "):"unset",go=[`Profile: ${H}${H===D?" (current)":""}`,`API URL: ${de.apiUrl??"default"}`,`Hub URL: ${de.hubUrl??"default"}`,`Model: ${de.model?.default??"unset"}`,`Connectors: ${qe}`,ge?`Logged in as: ${Ce?.email??"unknown"}`:"Not logged in",ge&&Ce?.workspaceId?`Workspace ID: ${Ce.workspaceId}`:null].filter(Boolean);return i(go.join(`
143
- `)),!0}if(o==="create"){let H=r||ae.DEFAULT_PROFILE;return ae.createProfile(H),i(`Profile created: ${H}`),!0}if(o==="use"||o==="switch"){let H=Te(r,!0);return ae.setOverrideProfile(H),ae.setCurrentProfile(H),Pe(H),await Ae(),f(`Switched to profile: ${H} (new task)`),!0}if(o==="delete"||o==="remove"||o==="rm"){let H=Te(r,!0),de=H===D,Ce=ae.deleteProfile(H),ge=`Profile deleted: ${H}`;if(de)ae.setOverrideProfile(Ce.currentProfile),Pe(Ce.currentProfile),await Ae(),f(`${ge}
144
- Switched to profile: ${Ce.currentProfile} (new task)`);else if(ee===H){let qe=ae.getCurrentProfileName();ae.setOverrideProfile(qe),Pe(qe),await Ae(),f(`${ge}
145
- Switched to profile: ${qe} (new task)`)}else i(ge);return!0}if(o==="rename"||o==="move"||o==="mv"){let H=Te(r,!0);if(!u)throw new Error("New profile name is required.");let de=ae.renameProfile(H,u);return i(`Profile renamed: ${H} -> ${u}`),ee===H?(ae.setOverrideProfile(u),Pe(u)):de.currentProfile===u&&Pe(u),!0}if(o==="clone"||o==="copy"){let H=Te(r,!0);if(!u)throw new Error("Target profile name is required.");let de=fe.getAll(H);return ae.createProfile(u),fe.setAll(de,u),await rt.clear(u),i(`Profile cloned: ${H} -> ${u}`),!0}i(`Unknown profile command: ${o}`)}catch(H){let de=H instanceof Error?H.message:"Unknown error";i(`Profile error: ${de}`)}return!0}case"open-in-browser":{let d=Bt().hubUrl.replace(/\/$/,""),o=q||Z.some(ee=>ee.role!=="system"),r=C?`/${C.workspaceId}`:"",u=o?`${r}/task/${n}`:`${r}/task/new`,c=y?`?agentId=${encodeURIComponent(y)}`:"",D=`${d}${u}${c}`;try{await to(D),i(`Opened in browser: ${D}`)}catch(ee){i(`Failed to open browser: ${ee instanceof Error?ee.message:"Unknown error"}
146
- URL: ${D}`)}return!0}case"share":{if(!C)return i("Not authenticated."),!0;if(!(q||Z.some(o=>o.role!=="system")))return i("No conversation to share. Start a task first."),!0;try{let r=await new me().createTaskShare(C.accessToken,C.workspaceId,n,"public"),c=`${Bt().hubUrl.replace(/\/$/,"")}/share/${r.id}`;i(`Share link: ${c}`)}catch(o){i(`Failed to create share link: ${o instanceof Error?o.message:"Unknown error"}`)}return!0}case"delete":return C?q?(xe(!0),i("Delete this task? (y/N)"),!0):(i("No task to delete."),!0):(i("Not authenticated."),!0);case"quit":return se(),!0;case"unknown":return i(`Unknown command: ${x.input}
147
- Type /help for available commands.`),!0;default:return!1}},[i,E,N,V,Ee,Se,m,y,P,b,n,l,se,ke,f,F,j,q,Z,Xe,Qe,ce,h,g,$,h,Pe,Ae]),ht=je(x=>{if(ze.current=!1,Fe){(x===""||x.startsWith("/"))&&(t(x),x.startsWith("/")&&xe(!1));return}if(t(x),st(x),Ne!==null&&Me(null),L&&(I(null),v([])),x.startsWith("/")&&!x.includes(" ")){let d=oo(x);Y(d),z(0),le(d.length>0)}else le(!1),Y([])},[L,Ne,Fe,t]),Ze=je((x,d=!1)=>{if(x>=0&&x<A.length){let o=A[x];le(!1),Y([]),o.name==="model"?(t("/model "),ke("model")):o.name==="agent"?(t("/agent "),ke("agent")):o.name==="skills"?(t("/skills "),ke("skills")):o.name==="schedules"?(t("/schedules "),ke("schedules")):o.name==="connectors"?(t("/connectors "),ke("connectors")):o.name==="capabilities"?(t("/capabilities "),ke("capabilities")):o.name==="tasks"?(t("/tasks "),ke("tasks")):o.name==="profile"?(t("/profile "),ke("profile")):d?(t(""),He({type:o.name})):t(`/${o.name}`)}},[A,ke,t,He]),Ot=je(async x=>{ze.current=!1;let d=x.trim();if(!d||Fe)return;if(L==="model"&&B.length>0){let r=B[G];r&&(y?f(`Switched to model: ${r.name} (new task)`):i(`Switched to model: ${r.name}`),h(r.id),g(void 0),$(null)),I(null),v([]),t("");return}if(L==="agent"&&B.length>0){let r=B[G];r&&(r.id!==y?f(`Switched to agent: ${r.name} (new task)`):i(`Switched to agent: ${r.name}`),g(r.id),h(void 0)),I(null),v([]),t("");return}if(L==="skills"&&B.length>0){let r=B[G];if(r){let u=Ee.find(c=>c.id===r.id);u&&i(`Skill: ${u.name}
148
- ${u.description}
149
- Provider: ${u.provider}
150
- Author: ${u.author.name}
151
- ID: ${u.id}`)}I(null),v([]),t("");return}if(L==="schedules"&&B.length>0){let r=B[G];if(r){let u=Se.find(c=>c.id===r.id);if(u){let c=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";i(`Schedule: ${u.name}
152
- Agent: ${u.agent.name}
153
- Status: ${u.isActive?"Active":"Paused"}
154
- Repeat: ${tn(u.config)}
155
- Next Run: ${c}
156
- ID: ${u.id}`)}}I(null),v([]),t("");return}if(L==="connectors"){let r=Array.from(S);Q(r.length>0?r:void 0),fe.setDefaultConnectorIds(r);let u=V.filter(c=>S.has(c.id)).map(c=>c.name);i(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled."),I(null),v([]),t("");return}if(L==="capabilities"){let r=ie.has("fileSystem");k(r),fe.setLocalTools({fileSystem:r});let u=[];r&&u.push("FileSystem"),i(u.length>0?`Active capabilities: ${u.join(", ")}`:"All capabilities disabled."),I(null),v([]),t("");return}if(L==="profile"&&B.length>0){let r=B[G];if(r){let u=ae.getCurrentProfileName();r.id!==u?(ae.setOverrideProfile(r.id),ae.setCurrentProfile(r.id),Pe(r.id),Ae(),f(`Switched to profile: ${r.name}`)):i(`Already using profile: ${r.name}`)}I(null),v([]),t("");return}if(O&&A.length>0){Ze(K,!0);return}Me(null),st(""),gt(r=>r.length>0&&r.at(-1)===d?r:[...r,d]);let o=so(d);if(o){await He(o),t(""),le(!1);return}if(oe){i("Please wait for file uploads to complete.");return}t(""),le(!1),_(d)},[_,He,O,A,K,Ze,L,B,G,S,ie,V,Ee,Se,i,t,y,f,h,g,$,Q,k,oe,Pe,Ae,Fe,C,q,n]);return ns((x,d)=>{if(d.ctrl&&x==="c"){if(e.length>0){ht(""),ze.current=!0,i("Press Ctrl+C again to exit.");return}if(ze.current){se();return}se();return}if(d.ctrl&&x==="o"){W(o=>!o);return}if(Fe){if(d.escape||d.return||x==="n"||x==="N"){xe(!1),t(""),i("Task deletion cancelled.");return}if(x==="y"||x==="Y"){xe(!1),t(""),C&&q&&new me().deleteTask(C.accessToken,C.workspaceId,n).then(()=>{f("Task deleted. Started a new task.")}).catch(r=>{i(`Failed to delete task: ${r.message||"Unknown error"}`)});return}return}if(L&&B.length>0){if(d.upArrow){p(o=>o<=0?B.length-1:o-1);return}if(d.downArrow){p(o=>o>=B.length-1?0:o+1);return}if(d.escape){I(null),v([]),t("");return}if(d.return){if(L==="model"){let o=B[G];o&&(y?f(`Switched to model: ${o.name} (new task)`):i(`Switched to model: ${o.name}`),h(o.id),g(void 0),$(null),fe.setDefaultModel(o.id))}else if(L==="agent"){let o=B[G];o&&(o.id!==y?f(`Switched to agent: ${o.name} (new task)`):i(`Switched to agent: ${o.name}`),g(o.id),h(void 0))}else if(L==="skills"){let o=B[G];if(o){let r=Ee.find(u=>u.id===o.id);r&&i(`Skill: ${r.name}
157
- ${r.description}
158
- Provider: ${r.provider}
159
- Author: ${r.author.name}
160
- ID: ${r.id}`)}}else if(L==="schedules"){let o=B[G];if(o){let r=Se.find(u=>u.id===o.id);if(r){let u=r.nextRunAt?new Date(r.nextRunAt).toLocaleString():"-";i(`Schedule: ${r.name}
161
- Agent: ${r.agent.name}
162
- Status: ${r.isActive?"Active":"Paused"}
163
- Repeat: ${tn(r.config)}
164
- Next Run: ${u}
165
- ID: ${r.id}`)}}}else if(L==="connectors"){let o=Array.from(S);Q(o.length>0?o:void 0),fe.setDefaultConnectorIds(o);let r=V.filter(u=>S.has(u.id)).map(u=>u.name);i(r.length>0?`Active connectors: ${r.join(", ")}`:"All connectors disabled.")}else if(L==="capabilities"){let o=ie.has("fileSystem");k(o),fe.setLocalTools({fileSystem:o});let r=[];o&&r.push("FileSystem"),i(r.length>0?`Active capabilities: ${r.join(", ")}`:"All capabilities disabled.")}else if(L==="tasks"){let o=B[G];if(o){let r=$e.find(u=>u.id===o.id);r&&C&&(s(r.id),a(r.title||void 0),M(!0),new me().getMessages(C.accessToken,C.workspaceId,r.id,20).then(({messages:c})=>{let D=c.filter(ee=>ee.role==="user"||ee.role==="assistant").map(ee=>({role:ee.role,content:Ke(ee.parts,!1),parts:ee.parts})).filter(ee=>ee.content).toReversed();ce(D),i(`Switched to: ${r.title||"Untitled"}`)}).catch(()=>{i("Failed to load task messages.")}))}}else if(L==="profile"){let o=B[G];if(o){let r=ae.getCurrentProfileName();o.id!==r?(ae.setOverrideProfile(o.id),ae.setCurrentProfile(o.id),Pe(o.id),Ae(),f(`Switched to profile: ${o.name}`)):i(`Already using profile: ${o.name}`)}}I(null),v([]),t("");return}if(x===" "&&(L==="connectors"||L==="capabilities")){let o=B[G];o&&(L==="connectors"?w:R)(u=>{let c=new Set(u);return c.has(o.id)?c.delete(o.id):c.add(o.id),c});return}if(x==="a"&&(L==="connectors"||L==="capabilities")){(L==="connectors"?w:R)(new Set(B.map(r=>r.id)));return}if(x==="n"&&(L==="connectors"||L==="capabilities")){(L==="connectors"?w:R)(new Set);return}return}if(O&&A.length>0){if(d.upArrow){z(o=>o<=0?A.length-1:o-1);return}if(d.downArrow){z(o=>o>=A.length-1?0:o+1);return}if(d.escape){le(!1),Y([]);return}if(d.tab){Ze(K);return}}if(d.upArrow){if(e.includes(`
166
- `)||Le.length===0)return;if(Ne===null){st(e);let r=Le.length-1;Me(r),t(Le[r]);return}let o=Math.max(0,Ne-1);Me(o),t(Le[o]);return}if(d.downArrow){if(e.includes(`
167
- `)||Ne===null)return;if(Ne>=Le.length-1){Me(null),t(Ft);return}let o=Ne+1;Me(o),t(Le[o])}}),{suggestions:A,suggestionIndex:K,showSuggestions:O,argMode:L,argItems:B,argIndex:G,selectedConnectorIds:S,selectedCapabilities:ie,deleteConfirmMode:Fe,handleInputChange:ht,handleSubmit:Ot}}import{useCallback as pt,useRef as ss,useState as rs}from"react";function lo({credentials:e,currentModel:t,modelProviders:n,onUploadSuccess:s,onUploadError:l}){let[a,m]=rs([]),h=ss(0),y=pt(k=>{if(!(!Array.isArray(n)||n.length===0)){for(let E of n)if(E.models.some(V=>V.id===k))return E.id;return n[0]?.id}},[n]),g=pt(async k=>{if(!e){l?.(k.filename,"Not logged in");return}if(!Array.isArray(n)||n.length===0){l?.(k.filename,"Model providers not loaded yet. Please wait and try again.");return}let E=t?y(t):n[0]?.id;if(!E){l?.(k.filename,"No model provider available");return}let N=`file-${++h.current}`;m(V=>[...V,{id:N,filename:k.filename,mimeType:k.mimeType,status:"uploading"}]);try{let Z=await new me().uploadFile(e.accessToken,e.workspaceId,k,E);m(q=>q.map(M=>M.id===N?{...M,status:"uploaded",fileId:Z.id}:M)),s?.(k.filename)}catch(V){let Z=V instanceof Error?V.message:"Upload failed";m(q=>q.map(M=>M.id===N?{...M,status:"error",error:Z}:M)),l?.(k.filename,Z)}},[e,t,y,n,s,l]),j=pt(k=>{m(E=>E.filter(N=>N.id!==k))},[]),$=pt(()=>{m([])},[]),P=pt(()=>a.filter(k=>k.status==="uploaded"&&k.fileId).map(k=>k.fileId),[a]),Q=a.some(k=>k.status==="uploading"),b=a.length>0;return{pendingFiles:a,addFile:g,removeFile:j,clearFiles:$,getUploadedFileIds:P,hasUploadingFiles:Q,hasFiles:b}}import{jsx as J,jsxs as re}from"react/jsx-runtime";var ls=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],as=[Zt,Zt,Qt,Qt,Ye,Ye,Ye,Ye],ao=ls.map((e,t)=>`${as[t]??Ye}${e}${X}`).join(`
168
- `),cs=`${Ye}EntryDesk${X}`,us=500;function ds(e){let t="",n=0;for(;n<e.length;){if(e.charCodeAt(n)===27&&e[n+1]==="["){for(n+=2;n<e.length;){let s=e.charCodeAt(n);if(s>=64&&s<=126){n+=1;break}n+=1}continue}t+=e[n],n+=1}return t}function fs(e){let t=ds(e);return Math.max(...t.split(`
169
- `).map(n=>n.length))}function ps(e){let t=fs(ao);return e>=t?ao:cs}function co({agentId:e,model:t,message:n,taskId:s,taskTitle:l,connectorIds:a,enableFileSystem:m=!0}){let h=process.stdout.columns??80,y=ps(h),g=rn(null),j=Hn(s,l),{state:$,setState:P,messages:Q,setMessages:b,input:k,setInput:E,taskId:N,setTaskId:V,currentTaskTitle:Z,setCurrentTaskTitle:q,hasPersistedTask:M,setHasPersistedTask:ce,credentials:i,setCredentials:f,currentResponse:_,setCurrentResponse:W,fullOutput:C,setFullOutput:pe,addSystemMessage:te,startNewTask:T}=j,{credentials:F}=Jn(P);Et(()=>{F&&!i&&f(F)},[F,i,f]);let{availableConnectors:oe,availableModels:se,availableAgents:A,modelProviders:Y,loading:K}=Yn(i),{currentModel:z,setCurrentModel:O,currentAgentId:le,setCurrentAgentId:L,activeConnectorIds:I,setActiveConnectorIds:B}=eo(t,e,a),v=rn(!1);Et(()=>{if(!v.current){if(v.current=!0,!t&&!e){let c=fe.getDefaultModel();c&&O(c)}if(!a&&!e){let c=fe.getDefaultConnectorIds();c&&B(c.length>0?c:void 0)}}},[t,e,a,O,B]);let{currentAgentDetails:G}=Zn(le,i),{fileSystem:p,setFileSystem:S,capabilityLabelMap:w}=Qn(m),{pendingFiles:ie,addFile:R,removeFile:$e,clearFiles:mt,getUploadedFileIds:Ee,hasUploadingFiles:Lt,hasFiles:Se}=lo({credentials:i,currentModel:z,modelProviders:Y,onUploadSuccess:c=>{te(`\u2713 Attached: ${c}`)},onUploadError:(c,D)=>{te(`\u2717 Failed to upload ${c}: ${D}`)}}),{sendMessage:ot}=zn({taskId:N,credentials:i,currentAgentId:le,currentModel:z,activeConnectorIds:I,localTools:p,fullOutput:C,setMessages:b,setState:P,setCurrentResponse:W,setCredentials:f,setHasPersistedTask:ce,getFileIds:Ee,clearFiles:mt}),Le=sn(c=>{T(c),W("")},[T]),[gt,Ne]=is(!1),Me=sn(async c=>{let D=c.text.trim(),ee=St(D);if(/^https?:\/\//.test(ee))return;if(await jn(D)&&Un(ee)){let H=await Mn(D);H&&(c.preventDefault(),await R(H))}},[R]),Ft=sn(async()=>{if(!(gt||$.status!=="ready")){if(K||Y.length===0){te("Please wait for resources to load before pasting images.");return}te("Reading clipboard..."),Ne(!0);try{let c=await Bn();if(c){let D=`clipboard-${Date.now()}.png`;te(`Uploading: ${D} (${Math.round(c.buffer.length/1024)}KB)`),await R({buffer:c.buffer,filename:D,mimeType:c.mime})}else te("No image found in clipboard. Copy an image first.")}catch(c){let D=c instanceof Error?c.message:"Failed to read clipboard";te(`Clipboard error: ${D}`)}finally{Ne(!1)}}},[R,te,gt,$.status,K,Y.length]),{suggestions:st,suggestionIndex:ze,showSuggestions:Fe,argMode:xe,argItems:Xe,argIndex:Qe,selectedConnectorIds:ke,selectedCapabilities:Pe,deleteConfirmMode:Ae,handleInputChange:He,handleSubmit:ht}=io({input:k,setInput:E,taskId:N,setTaskId:V,currentTaskTitle:Z,setCurrentTaskTitle:q,currentModel:z,setCurrentModel:O,currentAgentId:le,setCurrentAgentId:L,currentAgentDetails:G,setCurrentAgentDetails:()=>{},activeConnectorIds:I,setActiveConnectorIds:B,fileSystem:p,setFileSystem:S,availableModels:se,availableAgents:A,availableConnectors:oe,messages:Q,hasPersistedTask:M,setHasPersistedTask:ce,setMessages:b,addSystemMessage:te,startNewTask:Le,sendMessage:ot,setFullOutput:pe,credentials:i,setCredentials:f,setState:P,defaultCapabilities:{fileSystem:m},capabilityLabelMap:w,hasUploadingFiles:Lt});nn((c,D)=>{(D.ctrl||D.meta)&&c==="v"&&Ft()},{isActive:$.status==="ready"&&!xe}),nn((c,D)=>{if(!D.escape)return;let ee=Date.now(),Te=g.current;g.current=ee,!(!Te||ee-Te>us)&&(xe||Fe||(g.current=null,Se&&mt(),k.length>0&&He("")))},{isActive:$.status==="ready"}),nn((c,D)=>{D.return&&(Le("Started a new task."),P({status:"ready"}))},{isActive:$.status==="error"}),Et(()=>{if(i&&!K&&$.status==="loading")if(!z&&!le){let c=fe.getDefaultModel(),D=c&&se.some(Te=>Te.id===c),ee=D?c:se[0]?.id;ee?(D||fe.setDefaultModel(ee),O(ee),P({status:"ready"})):A.length===0?P({status:"no-model"}):P({status:"ready"})}else P({status:"ready"})},[i,K,z,le,se,A,$.status,O,P]);let Ze=rn(!1);if(Et(()=>{Ze.current||n&&i&&$.status==="ready"&&(Ze.current=!0,ot(n))},[i,n,$.status,ot]),$.status==="loading")return re(ye,{flexDirection:"column",children:[J(U,{children:y}),re(ye,{children:[J(U,{color:"cyan",children:J(on,{type:"dots"})}),J(U,{children:" Initializing task..."})]})]});if($.status==="not-logged-in")return re(ye,{flexDirection:"column",children:[J(U,{children:y}),J(U,{color:"yellow",children:"Not logged in"}),J(U,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if($.status==="no-workspace")return re(ye,{flexDirection:"column",children:[J(U,{children:y}),J(U,{color:"yellow",children:"No workspace selected"}),J(U,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if($.status==="no-model")return re(ye,{flexDirection:"column",children:[J(U,{children:y}),J(U,{color:"yellow",children:"No model or agent specified"}),s&&J(U,{dimColor:!0,children:"Could not determine the model used in this task."}),J(U,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),J(U,{dimColor:!0,children:"Example: entrydesk task -c 1 -i --model gemini-2.5-flash-lite"})]});if($.status==="error")return re(ye,{flexDirection:"column",children:[J(U,{children:y}),re(U,{color:"red",children:["Error: ",$.message]}),J(U,{dimColor:!0,children:"Press Enter to start a new task, or Ctrl+C to exit"})]});let Ot=le?G?G.connectors&&G.connectors.length>0?G.connectors.map(c=>c.name).join(", "):"none":"loading...":I&&I.length>0?oe.filter(c=>I.includes(c.id)).map(c=>c.name).join(", ")||`${I.length} connector(s)`:"none",x=[];if(le)if(G?.capabilities)for(let c of G.capabilities)x.push(w.get(c)??c);else x.push("loading...");p&&x.push("FileSystem");let d=ae.getCurrentProfileName(),o=d!=="default",r=(()=>{switch(xe){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:"}})(),u=(()=>{if(xe==="connectors")return ke;if(xe==="capabilities")return Pe})();return re(ye,{flexDirection:"column",children:[re(ye,{marginBottom:1,flexDirection:"column",children:[J(U,{children:y}),re(ye,{children:[J(U,{bold:!0,color:"cyan",children:Z?`Continuing: ${Z}`:"EntryDesk CLI"}),re(U,{dimColor:!0,children:[" v","1.22.0"]}),o&&re(U,{color:"magenta",children:[" [",d,"]"]}),J(U,{dimColor:!0,children:" (type /help for commands)"})]})]}),Q.map((c,D)=>{let ee=c.parts&&C?Ke(c.parts,!0):c.content,Te=c.role==="user"?"green":c.role==="system"?"yellow":"blue",H=c.role==="user"?"You":c.role==="system"?"System":"Assistant";return re(ye,{flexDirection:"column",marginBottom:1,children:[re(U,{bold:!0,color:Te,children:[H,":"]}),J(Xt,{text:ee})]},D)}),_&&re(ye,{flexDirection:"column",marginBottom:1,children:[J(U,{bold:!0,color:"blue",children:"Assistant:"}),J(Xt,{text:_})]}),$.status==="ready"&&J(Tn,{suggestions:st,activeIndex:ze,visible:Fe}),$.status==="ready"&&xe&&J(kn,{items:Xe,activeIndex:Qe,pageSize:xe==="agent"||xe==="skills"||xe==="model"?5:10,selectedIds:u,multiSelect:xe==="connectors"||xe==="capabilities",visible:!0,title:r}),$.status==="sending"&&!_?re(ye,{children:[J(U,{color:"cyan",children:J(on,{type:"dots"})}),J(U,{children:" Thinking..."})]}):$.status==="ready"&&!xe?re(ye,{flexDirection:"column",children:[Ae&&J(ye,{marginBottom:1,children:J(U,{color:"yellow",children:"\u26A0\uFE0F Delete this task? (y/N) "})}),Se&&!Ae&&re(ye,{marginBottom:1,flexDirection:"row",gap:1,children:[J(U,{dimColor:!0,children:"Attachments:"}),ie.map((c,D)=>re(U,{children:[c.status==="uploading"?re(U,{color:"yellow",children:[J(on,{type:"dots"})," ",c.filename]}):c.status==="error"?re(U,{color:"red",children:["\u2717 ",c.filename]}):re(U,{color:"green",children:["\u2713 ",c.filename]}),D<ie.length-1&&J(U,{children:", "})]},c.id))]}),re(ye,{children:[J(U,{color:"green",children:"> "}),J(_n,{value:k,onChange:He,onSubmit:ht,onPaste:Me,leadingOffset:2,multiline:!0})]})]}):null,re(ye,{marginTop:1,flexDirection:"column",children:[re(ye,{gap:2,children:[re(U,{children:[J(U,{dimColor:!0,children:"Model: "}),J(U,{color:"magenta",children:le?G?.model?.name||"loading...":se.find(c=>c.id===z)?.name||z||"none"})]}),re(U,{children:[J(U,{dimColor:!0,children:"Connectors: "}),J(U,{color:"cyan",children:Ot})]}),re(U,{children:[J(U,{dimColor:!0,children:"Capabilities: "}),J(U,{color:"green",children:x.length>0?x.join(", "):"none"})]})]}),re(U,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",C?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as xs}from"react/jsx-runtime";function Ri(){console.log(`
170
- Usage: entrydesk task [options]
171
-
172
- Send a message to a model or agent, or start an interactive session.
173
-
174
- Options:
175
- -m, --message <text> Message to send (or pipe via stdin)
176
- --model <modelId> Model to use
177
- -a, --agent <agentId> Agent to use (instead of --model)
178
- -c, --continue <n> Continue recent task #n
179
- -i, --interactive Interactive mode (continuous chat)
180
- --connectors id1,id2 Use specific connectors
181
- --plain Plain text output
182
- --output stream-json Stream events as JSON
183
- --full-output Show full tool outputs
184
- --no-file-system Disable local file operations
185
- --json Output JSON
186
-
187
- Examples:
188
- entrydesk task -m "Hello" --model <model>
189
- entrydesk task -m "Hello" -a <agentId>
190
- entrydesk task -c 1 -m "Follow up" # Continue recent task
191
- entrydesk task -i # Interactive mode
192
- echo "Explain this" | entrydesk task --model <model> # Pipe stdin
193
- entrydesk task -m "Hi" --model <m> --output stream-json
194
- `)}async function gs(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function hs(e,t,n,s){if(s<1)return console.error("Task number must be 1 or greater"),null;let{tasks:l}=await e.getTasks(t,n,20);if(l.length===0)return console.error("No tasks found. Start a new task first."),null;if(s>l.length)return console.error(`Task number ${s} not found. You have ${l.length} recent tasks.`),console.error("Use `entrydesk tasks` to see available tasks."),null;let a=l[s-1],m;if(!a.agentId){let{messages:h}=await e.getMessages(t,n,a.id,10);m=h.find(g=>g.role==="assistant"&&g.modelId)?.modelId}return{task:a,modelId:m}}var Ve="\x1B[2m",we="\x1B[0m",ln="\x1B[36m",Rt="\x1B[33m",Nt="\x1B[32m",fo="stream-json";function ys(e,t,n,s){e&&t&&(console.error(`Error: Cannot use both ${n} and ${s}`),process.exit(1))}function At(e,t){let n=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(n)}
195
- `)}function Dt(e,t){if(t)return e;let n=e.split(`
196
- `);if(n.length<=20)return e;let s=n.slice(0,5),l=n.slice(-5),a=n.length-10;return[...s,`${Ve}... (${a} lines omitted, use --full-output to see all) ...${we}`,...l].join(`
197
- `)}function ws(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function po(e,t){if(!e)return"(no result)";if(typeof e!="object")return Dt(String(e),t);let n=e;if("structuredContent"in n&&n.structuredContent){let s=n.structuredContent,l=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&l.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&l.push(`${Rt}[stderr]${we} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let a=s.urls;for(let m of a)m.path&&m.url&&l.push(`${m.path}: ${m.url}`)}return l.length===0&&l.push(JSON.stringify(s,null,2)),Dt(l.join(`
198
- `),t)}if("content"in n&&Array.isArray(n.content)){let l=n.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
199
- `);return Dt(l||JSON.stringify(e,null,2),t)}return Dt(JSON.stringify(e,null,2),t)}function mo(e){try{let n=(typeof e.data=="string"?JSON.parse(e.data):e.data)?.parts;return Array.isArray(n)?n.filter(s=>typeof s=="object"&&s!==null&&s.type==="text"&&typeof s.text=="string").map(s=>s.text).join(""):""}catch{return""}}async function Li(e){let t,n;try{let A=await We();t=A.accessToken,n=A.workspaceId}catch(A){cn(A)}let s=e.output===fo;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${fo}`),process.exit(1));let l=!s&&(e.plain||!process.stdout.isTTY),a=fe.getDefaultModel(),m=e.message;!m&&!process.stdin.isTTY&&(m=await gs());let h=new me,y,g=!1;async function j(){if(g)return y;g=!0;try{({models:y}=await h.listSelectableModels(t,n))}catch{y=void 0}return y}async function $(){let A=await j();if(!A||a&&A.some(K=>K.id===a))return;let Y=A[0]?.id;Y&&(fe.setDefaultModel(Y),a=Y)}let P,Q,b,k;if(e.continue){let A=await hs(h,t,n,e.continue);if(A||process.exit(1),P=A.task.id,Q=A.task.title??void 0,b=A.task.agentId??void 0,k=A.modelId,k&&!b&&!e.model){let K=await j();K&&!K.some(z=>z.id===k)&&(k=void 0)}let Y=e.agentId||e.model||b||k||a;!Y&&!e.interactive&&(await $(),Y=e.agentId||e.model||b||k||a),!Y&&!e.interactive&&(l||console.log(`Continuing task: ${A.task.title||"Untitled"}`),console.error(`
200
- 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)),!l&&!e.interactive&&console.log(`Continuing task: ${A.task.title||"Untitled"}
201
- `)}let E=e.agentId||b,N=e.model||k||void 0;!E&&!N&&(await $(),N=e.model||k||a||void 0),ys(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let V=fe.getDefaultConnectorIds(),Z=e.connectors??V??void 0,q=fe.getLocalTools(),M=e.noFileSystem?!1:e.fileSystem?!0:q?.fileSystem??!0;if(e.interactive){ms(xs(co,{agentId:E,model:N,message:e.message,taskId:P,taskTitle:Q??void 0,connectorIds:Z,enableFileSystem:M}),{exitOnCtrlC:!1});return}let ce=!e.continue&&!N&&!E;(!m||ce)&&(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 i=e.fullOutput??!1,f=e.dangerouslyAutoApproveTools??!1,_=P||uo(),W=M?wt():void 0,C=M?xt():void 0,pe=A=>{let Y={id:_,...f&&{toolApprovalMode:"allow_always"}};return A&&(Y.message=A),E?Y.agentId=E:(N&&(Y.model=N),Y.connectorIds=Z??[]),W&&(Y.clientTools=W),C&&(Y.clientToolSystemPrompt=C),Y},te=async A=>{if(!A.body)throw new Error("No response body");let Y=A.body.getReader(),K=new TextDecoder,z="",O=new Map,le=[],L=!1,I="";for(;;){let{done:B,value:v}=await Y.read();if(B)break;z+=K.decode(v,{stream:!0});let G=z.split(`
202
- `);z=G.pop()||"";for(let p of G){let S=p.trimEnd();if(S==="data: [DONE]"){s&&At("done");continue}if(S.startsWith("data: "))try{let w=JSON.parse(S.slice(6));if((w.type==="text-delta"||w.type==="reasoning-delta"||w.type==="tool-call"||w.type==="tool-input-available"||w.type==="tool-result"||w.type==="data-appendMessage")&&(L=!0),w.type==="start"&&typeof w.messageId=="string"&&(I=w.messageId),s){w.type==="text-delta"&&w.delta!==void 0?At("text-delta",w.delta):w.type==="reasoning-delta"&&w.delta!==void 0?At("reasoning-delta",w.delta):At(w.type||"event",w);continue}if(l){if(w.type==="text-delta"&&w.delta&&process.stdout.write(w.delta),w.type==="data-appendMessage"&&process.stdout.write(mo(w)),M&&(w.type==="tool-input-available"||w.type==="tool-call")&&w.toolCallId&&w.toolName&&Be(w.toolName)){let ie=w.args||w.input||{};le.push({toolCallId:w.toolCallId,toolName:w.toolName,args:ie})}continue}switch(w.type){case"reasoning-delta":w.delta&&process.stdout.write(`${Ve}${w.delta}${we}`);break;case"reasoning-end":process.stdout.write(`
203
-
204
- `);break;case"text-delta":w.delta&&process.stdout.write(w.delta);break;case"data-appendMessage":process.stdout.write(mo(w));break;case"tool-call-streaming-start":case"tool-input-start":if(w.toolCallId&&w.toolName){O.set(w.toolCallId,{toolName:w.toolName});let R=M&&Be(w.toolName)?`${Nt}[LOCAL]${we} `:"";console.log(`
205
- ${ln}\u250C\u2500 ${R}Tool Call: ${w.toolName}${we}`)}break;case"tool-call":case"tool-input-available":if(w.toolCallId&&w.toolName){let ie=w.args||w.input||{},R=ws(ie);console.log(`${Rt}\u2502 Arguments:${we}`);for(let $e of R.split(`
206
- `))console.log(`${Ve}\u2502 ${$e}${we}`);M&&Be(w.toolName)&&(O.set(w.toolCallId,{toolName:w.toolName,args:ie}),le.push({toolCallId:w.toolCallId,toolName:w.toolName,args:ie}))}break;case"tool-result":if(w.toolCallId){let ie=O.get(w.toolCallId),R=po(w.result,i);console.log(`${Nt}\u2502 Result:${we}`);for(let $e of R.split(`
207
- `))console.log(`${Ve}\u2502 ${$e}${we}`);console.log(`${ln}\u2514\u2500 ${ie?.toolName||"Tool"} completed${we}
208
- `),O.delete(w.toolCallId)}break;case"error":w.errorText&&console.error(`${Ve}Error: ${w.errorText}${we}`);break}}catch{}}}return{pendingClientTools:le,hadContent:L,messageId:I}},T=pe({id:uo(),createdAt:new Date,role:"user",parts:[{type:"text",text:m}]}),F=await h.task(t,n,T),oe=await te(F),se=oe.hadContent;for(;oe.pendingClientTools.length>0;){let A=oe.messageId,Y=[];for(let z of oe.pendingClientTools){!l&&!s&&console.log(`${Nt}\u2502 Executing locally...${we}`);let O=await kt(z.toolName,z.args);if(Y.push({type:`tool-${z.toolName}`,toolCallId:z.toolCallId,state:"output-available",output:{content:[{type:"text",text:O.success?JSON.stringify(O.result):O.error||"Unknown error"}],isError:!O.success}}),!l&&!s){let le=po(O.success?O.result:{error:O.error},i);console.log(`${Nt}\u2502 Result:${we}`);for(let L of le.split(`
209
- `))console.log(`${Ve}\u2502 ${L}${we}`);console.log(`${ln}\u2514\u2500 ${z.toolName} completed${we}
210
- `)}}A||(console.error(`${Rt}Cannot continue: missing assistant message id for tool results.${we}`),process.exit(1));let K=pe({id:A,role:"assistant",parts:Y});F=await h.task(t,n,K),oe=await te(F),se=se||oe.hadContent}se||(console.error(`${Rt}No response received from the server (empty stream).${we}`),console.error(`${Ve}The task may have failed server-side. Re-run with DEBUG=1 for details.${we}`),process.exit(1)),s||console.log("")}export{Ri as printTaskHelp,Li as runTask};