@entrydesk/cli 1.7.12 → 1.7.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +49 -49
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -61,12 +61,12 @@ You have access to filesystem tools that allow you to interact with the user's l
|
|
|
61
61
|
|
|
62
62
|
... (truncated, ${e.length-t} more characters)`}async function fn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ke(t.path),s=await et.readFile(o,"utf-8");return{success:!0,result:oo(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Ke(n);try{let r=await et.readFile(i,"utf-8");s[n]=oo(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ke(t.path),s=t.content;return await et.mkdir(Ao.dirname(o),{recursive:!0}),await et.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ke(t.path);return await et.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ke(t.path);return{success:!0,result:(await et.readdir(o,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Ke(t.cwd):process.cwd(),n=await Qs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ke(t.path),s=await et.stat(o);return{success:!0,result:{path:o,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 o=Ke(t.source),s=Ke(t.destination);return await et.mkdir(Ao.dirname(s),{recursive:!0}),await et.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Ke(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Xs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await er(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:oo(i,5e4),stderr:oo(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function No(e){return e.startsWith("filesystem__")}function pn(){return[dn()]}function no(){return pn().flatMap(e=>e.tools)}function so(){return pn().map(e=>e.systemPrompt).filter(Boolean).join(`
|
|
63
63
|
|
|
64
|
-
`)}function tt(e){return No(e)}async function ro(e,t){return No(e)?fn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as V,useInput as Vo}from"ink";import Ko from"ink-spinner";import{useCallback as qo,useEffect as ho,useRef as rs,useState as Fr}from"react";import{Box as io,Text as Ot}from"ink";import{jsx as ao,jsxs as Rt}from"react/jsx-runtime";function gn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function mn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),C=Math.max(1,r),k=Math.floor(t/C)*C,b=Math.min(e.length,k+C),S=e.slice(k,b);return Rt(io,{flexDirection:"column",marginBottom:1,children:[ao(Ot,{bold:!0,color:"cyan",children:i}),ao(io,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:S.map((g,
|
|
65
|
-
`){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Sn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ar=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=bn(()=>Do(e).length),d=xn(null),[C,k]=bn(0),b=xn(null),{stdout:S}=rr(),g=Lo(()=>Do(e),[e]),{lines:
|
|
66
|
-
`,...g.slice(a)].join("");z(_,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&N>0?l($[N]-1):l($[N]+Oo(W,R)),b.current=null):(R===0&&N>0?l($[N]-1):l(_=>lo(_-1,g.length)),b.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=E&&N<
|
|
64
|
+
`)}function tt(e){return No(e)}async function ro(e,t){return No(e)?fn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as V,useInput as Vo}from"ink";import Ko from"ink-spinner";import{useCallback as qo,useEffect as ho,useRef as rs,useState as Fr}from"react";import{Box as io,Text as Ot}from"ink";import{jsx as ao,jsxs as Rt}from"react/jsx-runtime";function gn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function mn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),C=Math.max(1,r),k=Math.floor(t/C)*C,b=Math.min(e.length,k+C),S=e.slice(k,b);return Rt(io,{flexDirection:"column",marginBottom:1,children:[ao(Ot,{bold:!0,color:"cyan",children:i}),ao(io,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:S.map((g,m)=>{let D=k+m===t,H=o?.has(g.id),X=gn(g.name,d),ie=g.description?gn(g.description,Math.max(0,d-l)):"",z=s?" ".repeat(l):"";return Rt(io,{paddingX:1,flexDirection:"column",children:[Rt(io,{children:[s&&ao(Ot,{color:H?"green":"gray",children:H?"[\u2713] ":"[ ] "}),ao(Ot,{backgroundColor:D?"cyan":void 0,color:D?"black":H?"green":"white",bold:!0,children:X})]}),ie&&Rt(Ot,{dimColor:!0,children:[z,"\xB7 ",ie]})]},g.id)})}),Rt(Ot,{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>C?` \xB7 Showing ${k+1}-${b} of ${e.length}`:""]})]})}import{Box as Eo,Text as Ut}from"ink";import{jsx as jt,jsxs as _o}from"react/jsx-runtime";function hn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:_o(Eo,{flexDirection:"column",marginBottom:1,children:[jt(Eo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return _o(Eo,{paddingX:1,children:[_o(Ut,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),jt(Ut,{dimColor:!0,children:r}),jt(Ut,{children:" - "}),jt(Ut,{color:i?"white":"gray",children:s.description})]},s.name)})}),jt(Ut,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as nr,Text as yn,useInput as sr,useStdout as rr}from"ink";import{useCallback as wn,useEffect as kn,useMemo as Lo,useRef as xn,useState as bn}from"react";import{jsx as Ro}from"react/jsx-runtime";function lo(e,t){return e<0?0:e>t?t:e}function Do(e){return Array.from(e)}function co(e){return/\s/.test(e)}function Oo(e,t){let o=t;for(;o>0&&co(e[o-1]??"");)o-=1;for(;o>0&&!co(e[o-1]??"");)o-=1;return o}function Cn(e,t){let o=t;for(;o<e.length&&co(e[o]??"");)o+=1;for(;o<e.length&&!co(e[o]??"");)o+=1;return o}function ir(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((r,a)=>{if(r===`
|
|
65
|
+
`){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Sn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ar=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=bn(()=>Do(e).length),d=xn(null),[C,k]=bn(0),b=xn(null),{stdout:S}=rr(),g=Lo(()=>Do(e),[e]),{lines:m,lineStarts:$,lineLengths:D}=Lo(()=>ir(g),[g]),{row:H,col:X}=Lo(()=>Sn(a,$,D),[a,$,D]),ie=Math.max(1,(S?.columns??80)-i);kn(()=>{d.current!==e?(l(g.length),b.current=null):l(j=>lo(j,g.length)),d.current=e},[e,g.length]),kn(()=>{k(j=>{let P=j;X<P?P=X:X>=P+ie&&(P=X-ie+1);let N=D[H]??0,R=X===N?N+1:N,W=Math.max(0,R-ie);return P>W&&(P=W),P<0&&(P=0),P})},[ie,X,H,D]);let z=wn((j,P)=>{d.current=j,t(j),l(P),b.current=null},[t]),$e=wn(async(j,P)=>{if(!n)return;let{row:N,col:R}=Sn(a,$,D),W=m[N]??[],E=D[N]??0,he=m.length>1;if(r&&(P.meta&&P.return||P.ctrl&&j==="j"||P.shift&&P.return)){let _=[...g.slice(0,a),`
|
|
66
|
+
`,...g.slice(a)].join("");z(_,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&N>0?l($[N]-1):l($[N]+Oo(W,R)),b.current=null):(R===0&&N>0?l($[N]-1):l(_=>lo(_-1,g.length)),b.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=E&&N<m.length-1?l($[N+1]):l($[N]+Cn(W,R)),b.current=null):(R>=E&&N<m.length-1?l($[N+1]):l(_=>lo(_+1,g.length)),b.current=null);return}if(r&&he&&P.upArrow){let _=b.current??R,p=Math.max(0,N-1),re=Math.min(_,D[p]??0);l(($[p]??0)+re),b.current=_;return}if(r&&he&&P.downArrow){let _=b.current??R,p=Math.min(m.length-1,N+1),re=Math.min(_,D[p]??0);l(($[p]??0)+re),b.current=_;return}if(P.ctrl){if(j==="a"){l($[N]??0),b.current=null;return}if(j==="e"){l(($[N]??0)+E),b.current=null;return}if(j==="u"){if(R>0){let _=$[N]??0,p=[...g.slice(0,_),...g.slice(a)].join("");z(p,_)}return}if(j==="k"){if(R<E){let _=($[N]??0)+E,p=[...g.slice(0,a),...g.slice(_)].join("");z(p,a)}return}if(j==="w"){if(R===0&&N>0){let p=[...g.slice(0,a-1),...g.slice(a)].join("");z(p,a-1);return}let _=Oo(W,R);if(_!==R){let p=($[N]??0)+_,re=[...g.slice(0,p),...g.slice(a)].join("");z(re,p)}return}if(j==="d"){if(a<g.length){let _=[...g.slice(0,a),...g.slice(a+1)].join("");z(_,a)}return}return}if(P.meta){j==="b"?(R===0&&N>0?l($[N]-1):l($[N]+Oo(W,R)),b.current=null):j==="f"&&(R>=E&&N<m.length-1?l($[N+1]):l($[N]+Cn(W,R)),b.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let _=[...g.slice(0,a-1),...g.slice(a)].join("");z(_,a-1);return}if(!(P.tab||P.escape)&&j.length>0){let _=r?j.replace(/\r\n/g,`
|
|
67
67
|
`).replace(/\r/g,`
|
|
68
68
|
`):j.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=ar||_.includes(`
|
|
69
|
-
`))&&s){let K=!1,A={text:_,preventDefault:()=>{K=!0}};if(await Promise.resolve(s(A)),K)return}let re=Do(_),ke=[...g.slice(0,a),...re,...g.slice(a)].join("");z(ke,a+re.length)}},[g,a,n,D,$,
|
|
69
|
+
`))&&s){let K=!1,A={text:_,preventDefault:()=>{K=!0}};if(await Promise.resolve(s(A)),K)return}let re=Do(_),ke=[...g.slice(0,a),...re,...g.slice(a)].join("");z(ke,a+re.length)}},[g,a,n,D,$,m,r,s,o,z,e]);return sr($e,{isActive:n}),Ro(nr,{flexDirection:"column",children:m.map((j,P)=>{let N=P===H,W=(N&&X===j.length?[...j," "]:j).slice(C,C+ie),E=W.join("");if(!N)return Ro(yn,{children:E||" "},P);let he=lo(X-C,Math.max(0,W.length-1)),_=W.slice(0,he).join(""),p=W[he]??" ",re=W.slice(he+1).join(""),A=`${_}\x1B[7m${p}\x1B[27m${re}`;return Ro(yn,{children:A},P)})})}import{Box as qe,Text as ft}from"ink";import Fo from"react";import{Text as Be}from"ink";import lr from"react";import{Fragment as dr,jsx as Je,jsxs as vn}from"react/jsx-runtime";var Uo=2,jo=1,Bo=2,cr=1,Tn=3,In=4,ur=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Je(Be,{color:n,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>r&&i.push(Je(Be,{color:n,children:e.slice(r,l.index)},`t-${r}`));let d=l[0],C=null,k=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Uo*2)C=Je(Be,{bold:!0,color:n,children:d.slice(Uo,-Uo)},k);else if(d.length>jo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(l.index-1,l.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(l.index-2,l.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))C=Je(Be,{italic:!0,color:n,children:d.slice(jo,-jo)},k);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Bo*2)C=Je(Be,{strikethrough:!0,color:n,children:d.slice(Bo,-Bo)},k);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>cr){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(C=Je(Be,{color:s,children:b[2]},k))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let S=b[1],g=b[2];C=vn(Be,{color:n,children:[S,vn(Be,{color:o,children:[" (",g,")"]})]},k)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Tn+In-1?C=Je(Be,{underline:!0,color:n,children:d.slice(Tn,-In)},k):d.match(/^https?:\/\//)&&(C=Je(Be,{color:o,children:d},k))}catch{C=null}i.push(C??Je(Be,{color:n,children:d},k)),r=a.lastIndex}return r<e.length&&i.push(Je(Be,{color:n,children:e.slice(r)},`t-${r}`)),Je(dr,{children:i.filter(d=>d!==null)})},Bt=lr.memo(ur);import{Fragment as wr,jsx as we,jsxs as En}from"react/jsx-runtime";var fr=1,Nn=1,pr=1,gr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return we(qe,{paddingLeft:Nn,flexDirection:"column",children:we(ft,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],C=!1,k=!0,b=[],S="";function g(m){m&&(d.push(m),k=!1)}return o.forEach((m,$)=>{let D=`line-${$}`;if(C){let P=m.match(n);P&&P[1].startsWith(S[0])&&P[1].length>=S.length?(g(we(Pn,{content:b},D)),C=!1,b=[],S=""):b.push(m);return}let H=m.match(n),X=m.match(s),ie=m.match(i),z=m.match(r),$e=m.match(a),j=m.match(l);if(H)C=!0,S=H[1];else if($e)g(we(qe,{children:we(ft,{dimColor:!0,children:"---"})},D));else if(X){let P=X[1].length,N=X[2],R=P<=2?"cyan":"blue";g(we(qe,{children:we(ft,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:we(Bt,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},D))}else if(j){let P=j[1];g(we(qe,{paddingLeft:1,children:En(ft,{dimColor:!0,children:["> ",we(Bt,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},D))}else if(ie){let P=ie[1],N=ie[2],R=ie[3];g(we(An,{itemText:R,type:"ul",marker:N,leadingWhitespace:P},D))}else if(z){let P=z[1],N=z[2],R=z[3];g(we(An,{itemText:R,type:"ol",marker:N,leadingWhitespace:P},D))}else m.trim().length===0?k||(d.push(we(qe,{height:fr},`spacer-${$}`)),k=!0):g(we(qe,{children:we(ft,{wrap:"wrap",children:we(Bt,{text:m,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},D))}),C&&g(we(Pn,{content:b},"line-eof")),we(wr,{children:d})},hr=({content:e})=>{let t=e.join(`
|
|
70
70
|
`);return we(qe,{paddingLeft:Nn,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},Pn=Fo.memo(hr),yr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return En(qe,{paddingLeft:r+pr,flexDirection:"row",children:[we(qe,{width:i,children:we(ft,{children:n})}),we(qe,{flexGrow:gr,children:we(ft,{wrap:"wrap",children:we(Bt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},An=Fo.memo(yr),Wo=Fo.memo(mr);import{execFile as kr}from"child_process";import xr from"fs";import $t from"fs/promises";import _n from"os";import fo from"path";import{promisify as br}from"util";var uo=br(kr);async function Cr(){let e=fo.join(_n.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
|
|
71
71
|
set imageData to the clipboard as "PNGf"
|
|
72
72
|
set fileRef to open for access POSIX file "${e}" with write permission
|
|
@@ -81,7 +81,7 @@ You have access to filesystem tools that allow you to interact with the user's l
|
|
|
81
81
|
$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
82
82
|
[System.Convert]::ToBase64String($ms.ToArray())
|
|
83
83
|
}
|
|
84
|
-
`,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("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 uo("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 Ln(){let e=_n.platform();if(e==="darwin")return Cr();if(e==="win32")return Sr();if(e==="linux")return $r()}var Tr=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 Dn(e){let t=fo.extname(e).toLowerCase();return Tr.has(t)}function Ir(e){let t=fo.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 po(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 On(e){let t=po(e);if(/^https?:\/\//.test(t))return!1;try{return await $t.access(t),!0}catch{return!1}}async function Rn(e){let t=po(e);try{if(!(await $t.stat(t)).isFile())return;let s=await $t.readFile(t),n=Ir(t),i=fo.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Fe="\x1B[2m",se="\x1B[0m",ve="\x1B[36m",Tt="\x1B[32m",Un="\x1B[31m",mt="\x1B[38;2;59;91;204m",Mo="\x1B[38;2;126;200;248m",Jo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as jn}from"uuid";function Bn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||jn()),[C,k]=ot(t),[b,S]=ot(!!e),[g,
|
|
84
|
+
`,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("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 uo("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 Ln(){let e=_n.platform();if(e==="darwin")return Cr();if(e==="win32")return Sr();if(e==="linux")return $r()}var Tr=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 Dn(e){let t=fo.extname(e).toLowerCase();return Tr.has(t)}function Ir(e){let t=fo.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 po(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 On(e){let t=po(e);if(/^https?:\/\//.test(t))return!1;try{return await $t.access(t),!0}catch{return!1}}async function Rn(e){let t=po(e);try{if(!(await $t.stat(t)).isFile())return;let s=await $t.readFile(t),n=Ir(t),i=fo.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Fe="\x1B[2m",se="\x1B[0m",ve="\x1B[36m",Tt="\x1B[32m",Un="\x1B[31m",mt="\x1B[38;2;59;91;204m",Mo="\x1B[38;2;126;200;248m",Jo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as jn}from"uuid";function Bn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||jn()),[C,k]=ot(t),[b,S]=ot(!!e),[g,m]=ot(null),[$,D]=ot(""),[H,X]=ot(!1),ie=$e=>{i(j=>[...j,{role:"system",content:$e}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:l,setChatId:d,currentChatTitle:C,setCurrentChatTitle:k,hasPersistedChat:b,setHasPersistedChat:S,credentials:g,setCredentials:m,currentResponse:$,setCurrentResponse:D,fullOutput:H,setFullOutput:X,addSystemMessage:ie,startNewChat:$e=>{let j=jn();d(j),k(void 0),S(!1),i([]),$e&&ie($e)}}}import{useEffect as vr,useState as Fn}from"react";function Wn(e){let[t,o]=Fn(null),[s,n]=Fn(!0);return vr(()=>{let i=!1;async function r(){try{let a=await fe();if(i)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof Qe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),n(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Pr,useState as Ft}from"react";function Mn(e){let[t,o]=Ft([]),[s,n]=Ft([]),[i,r]=Ft([]),[a,l]=Ft([]),[d,C]=Ft(!1);return Pr(()=>{if(!e)return;let k=!1;C(!0);async function b(){if(e)try{let S=new B,[g,m,$,D]=await Promise.all([S.getConnectors(e.accessToken,e.workspaceId),S.getModels(e.accessToken,e.workspaceId),S.getAgents(e.accessToken,e.workspaceId),S.getModelProviders(e.accessToken,e.workspaceId)]);if(k)return;o(g.connectors),n(m.models),r($.agents),l(D.providers??[])}catch{}finally{k||C(!1)}}return b(),()=>{k=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import It from"fs";import Gn from"path";import{useCallback as Ar}from"react";import{v4 as Nr}from"uuid";function Jn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
|
|
85
85
|
`);return n?t||n.length<=200?n:n.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 ht(e,t=!1){let o=[];for(let s of e)if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="reasoning"&&s.text)t?o.push(`${Fe}[Thinking]
|
|
86
86
|
${s.text}${se}`):o.push(`${Fe}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${ve}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let i=JSON.stringify(s.args,null,t?2:void 0),r=t||i.length<=100?i:i.slice(0,100)+"...";n.push(`${Fe}\u2502 Args: ${r}${se}`)}s.result!==void 0?(n.push(`${Tt}\u2502 Result: ${Jn(s.result,t)}${se}`),n.push(`${ve}\u2514\u2500 completed${se}`)):n.push(`${ve}\u2514\u2500${se}`),o.push(n.join(`
|
|
87
87
|
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${ve}\u250C\u2500 Tool: ${n}${se}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Fe}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Tt}\u2502 Output: ${Jn(s.output,t)}${se}`),i.push(`${ve}\u2514\u2500 completed${se}`)):s.state==="error"?i.push(`${ve}\u2514\u2500 failed${se}`):i.push(`${ve}\u2514\u2500${se}`),o.push(i.join(`
|
|
@@ -112,13 +112,13 @@ ${ve}\u2514\u2500 failed${se}
|
|
|
112
112
|
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Wt=Gn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
|
|
113
113
|
DATA: ${JSON.stringify(t,null,2)}`),s+=`
|
|
114
114
|
`;try{It.appendFileSync(Wt,s)}catch{}}function Er(){try{if(It.existsSync(Wt)&&It.unlinkSync(Wt),process.env.DEBUG){let e=Gn.dirname(Wt);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(Wt,`=== Debug session started at ${new Date().toISOString()} ===
|
|
115
|
-
`)}}catch{}}function mo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Hn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:C,setMessages:k,setState:b,setCurrentResponse:S,setCredentials:g,setHasPersistedChat:
|
|
115
|
+
`)}}catch{}}function mo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Hn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:C,setMessages:k,setState:b,setCurrentResponse:S,setCredentials:g,setHasPersistedChat:m,getFileIds:$,clearFiles:D}){let H=d?no():void 0,X=d?so():void 0;return{sendMessage:Ar(async(z,$e,j)=>{Er(),ae("=== sendMessage called ===",{text:z,localTools:d,clientToolsCount:H?.length});let P=$e||t?.accessToken,N=j||t?.workspaceId;if(!P||!N)try{let E=await fe();P=E.accessToken,N=E.workspaceId,g(E)}catch(E){if(E instanceof Qe){if(E.code==="not-logged-in"){b({status:"not-logged-in"});return}if(E.code==="no-workspace"){b({status:"no-workspace"});return}}let he=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:he});return}else try{let E=await dt();E!==P&&(P=E,g({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof Qe&&E.code==="not-logged-in"){b({status:"not-logged-in"});return}let he=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:he});return}k(E=>[...E,{role:"user",content:z}]),b({status:"sending"}),S("");let R=null,W=null;try{let E=new B,he=$?.()??[],_={id:e,message:{id:Nr(),createdAt:new Date,role:"user",parts:[{type:"text",text:z}]}};he.length>0&&(_.fileIds=he),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=i,_.enableWebSearch=r,_.enableImageGeneration=a,_.enableChart=l),H&&(_.clientTools=H),X&&(_.clientToolSystemPrompt=X);let p=await E.chat(P,N,_);if(!p.ok){let F=await p.text();throw new Error(`API error ${p.status}: ${F}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let re=new TextDecoder,ke="",K="",A="",ee="",Q="",pe="",le="",M=new go,Z=[],q=[],de=[],Te=()=>{let F=M.hasExecuting();F&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}S(K+M.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:ne}=await R.read();if(F)break;ke+=re.decode(ne,{stream:!0});let O=ke.split(`
|
|
116
116
|
`);ke=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,S(`${Fe}[Thinking...]${se}
|
|
117
117
|
${A}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let T={type:"reasoning",id:ee,text:A,state:"done"};Q&&(T.providerMetadata={anthropic:{signature:Q}}),q.push(T),ae("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S("");break;case"text-delta":w.delta&&(M.hasPending()&&(K=M.flushPending(K)),K+=w.delta,pe+=w.delta,S(K));break;case"tool-input-start":{let T=M.handleToolInputStart(w);T&&S(K+T),Te();break}case"tool-input-delta":{let T=M.handleToolInputDelta(w);T&&S(K+T),Te();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?tt(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let T=mo(w.args??w.input);q.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added tool to messageParts",{messagePartsCount:q.length})}if(d&&w.toolCallId&&w.toolName&&tt(w.toolName)){let T=mo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),S(K+M.buildToolDisplay()+`
|
|
118
118
|
[Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?tt(w.toolName):!1});break}case"tool-output-start":{let T=M.handleToolOutputStart(w);T&&S(K+T),Te();break}case"tool-output-delta":{let T=M.handleToolOutputDelta(w);T&&S(K+T),Te();break}case"tool-output-end":{let T=M.handleToolOutputEnd(w,K);T&&(K=T.fullResponse,S(K+T.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let T=M.handleToolError(w,K);T&&(K=T.fullResponse,S(K+T.toolDisplay)),Te();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let F=q.findIndex(O=>O.type!=="reasoning"),ne=F===-1?q.length:F;q.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:q.length,messageParts:q.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let F=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),M.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),M.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),S(K+M.buildToolDisplay()),Te();let w=await ro(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let T=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:T}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=M.handleToolOutputEnd({toolCallId:f.toolCallId},K);te&&(K=te.fullResponse)}else{let te=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},K);te&&(K=te.fullResponse)}S(K+M.buildToolDisplay()),Te()}Z.length=0;for(let f of F){let w=q.find(T=>(T.type==="tool-input-available"||T.type==="tool-call")&&T.toolCallId===f.toolCallId);if(w){let T=[];for(let U of f.content)U.type==="text"?T.push(U.text):U.type==="image"?T.push("[Image]"):U.type==="audio"?T.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&T.push("[Resource]");let te=T.join(`
|
|
119
119
|
`);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let ne={id:e,clientToolResults:F};o?ne.agentId=o:(s&&(ne.model=s),ne.connectorIds=n??[],ne.enableSandbox=i,ne.enableWebSearch=r,ne.enableImageGeneration=a,ne.enableChart=l),H&&(ne.clientTools=H),X&&(ne.clientToolSystemPrompt=X),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:F.length});let O=await E.chat(P,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),R=O.body.getReader(),q.length=0,pe="",A="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}ke+=re.decode(w,{stream:!0});let T=ke.split(`
|
|
120
120
|
`);ke=T.pop()||"";for(let te of T)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let U=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":ee=U.id||"0",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,S(`${Fe}[Thinking...]${se}
|
|
121
|
-
${A}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Se={type:"reasoning",id:ee,text:A,state:"done"};Q&&(Se.providerMetadata={anthropic:{signature:Q}}),q.push(Se),ae("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S(K);break;case"text-delta":U.delta&&(K+=U.delta,pe+=U.delta,S(K));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Se=mo(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Se})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Se=mo(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Se}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(T=>T.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:K.length})}if(d&&H&&H.length>0){let F=[];for(let O of de)F.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 q)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=ht(F,C);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(O=>O.type==="text").length,contentLength:ne.length}),k(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:K.length,fullResponsePreview:K.slice(0,200)});try{let{messages:F}=await E.getMessages(P,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=ht(O,C);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),k(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),k(O=>[...O,{role:"assistant",content:K}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),k(ne=>[...ne,{role:"assistant",content:K}])}}ae("=== Message handling complete ==="),S(""),b({status:"ready"}),
|
|
121
|
+
${A}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Se={type:"reasoning",id:ee,text:A,state:"done"};Q&&(Se.providerMetadata={anthropic:{signature:Q}}),q.push(Se),ae("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S(K);break;case"text-delta":U.delta&&(K+=U.delta,pe+=U.delta,S(K));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Se=mo(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Se})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Se=mo(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Se}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(T=>T.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:K.length})}if(d&&H&&H.length>0){let F=[];for(let O of de)F.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 q)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=ht(F,C);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(O=>O.type==="text").length,contentLength:ne.length}),k(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:K.length,fullResponsePreview:K.slice(0,200)});try{let{messages:F}=await E.getMessages(P,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=ht(O,C);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),k(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),k(O=>[...O,{role:"assistant",content:K}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),k(ne=>[...ne,{role:"assistant",content:K}])}}ae("=== Message handling complete ==="),S(""),b({status:"ready"}),m(!0),he.length>0&&D?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let he=E instanceof Error?E.message:"Failed to send message";b({status:"error",message:he})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,o,s,n,i,r,a,l,d,H,X,C,k,b,S,g,m,$,D])}}import{useState as Mt}from"react";var Vn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},Kn=new Map(Object.values(Vn).map(e=>[e.apiKey,e.name]));function qn(){return Object.values(Vn)}function zn(e,t,o,s,n){let[i,r]=Mt(e),[a,l]=Mt(t),[d,C]=Mt(o),[k,b]=Mt(s),[S,g]=Mt(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:C,chart:k,setChart:b,fileSystem:S,setFileSystem:g,capabilityLabelMap:Kn}}import{useEffect as _r,useState as Lr}from"react";function Yn(e,t){let[o,s]=Lr(null);return _r(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new B().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Go}from"react";function Xn(e,t,o){let[s,n]=Go(e),[i,r]=Go(t),[a,l]=Go(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Or,useInput as Rr}from"ink";import{useCallback as nt,useRef as Ur,useState as De}from"react";import{spawn as Dr}from"child_process";function Zn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let i=Dr(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Qn=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{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:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{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 chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function es(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Qn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Qn}function ts(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.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: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"chats":case"c":return{type:"chats"};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:t}}}var os=`Available commands:
|
|
122
122
|
/help, /h, /? Show this help message
|
|
123
123
|
/clear, /cls, /new Start a new chat
|
|
124
124
|
/model [name], /m Show current model or switch to [name]
|
|
@@ -142,67 +142,67 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
|
|
|
142
142
|
|
|
143
143
|
Keyboard shortcuts:
|
|
144
144
|
Ctrl+O Toggle full output mode
|
|
145
|
-
Ctrl+C Exit`;function Ho(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 ns({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:C,setCurrentAgentDetails:k,activeConnectorIds:b,setActiveConnectorIds:S,sandbox:g,setSandbox:
|
|
146
|
-
Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!v.value)return N.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=v.value.toLowerCase(),c=N.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=N.map(
|
|
147
|
-
Available: ${u||"none"}`)}return!0}case"skills":{if(!v.value)return _e("skills"),!0;let y=v.value.toLowerCase();return(We.length?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let
|
|
148
|
-
${
|
|
149
|
-
Provider: ${
|
|
150
|
-
Author: ${
|
|
151
|
-
ID: ${
|
|
152
|
-
Agent: ${
|
|
153
|
-
Status: ${
|
|
154
|
-
Repeat: ${Ho(
|
|
145
|
+
Ctrl+C Exit`;function Ho(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 ns({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:C,setCurrentAgentDetails:k,activeConnectorIds:b,setActiveConnectorIds:S,sandbox:g,setSandbox:m,webSearch:$,setWebSearch:D,imageGeneration:H,setImageGeneration:X,chart:ie,setChart:z,fileSystem:$e,setFileSystem:j,availableModels:P,availableAgents:N,availableConnectors:R,messages:W,hasPersistedChat:E,setHasPersistedChat:he,setMessages:_,addSystemMessage:p,startNewChat:re,sendMessage:ke,setFullOutput:K,credentials:A,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:M=!1}){let{exit:Z}=Or(),[q,de]=De([]),[Te,F]=De(0),[ne,O]=De(!1),[f,w]=De(null),[T,te]=De([]),[U,Se]=De(0),[rt,it]=De(new Set),[Re,at]=De(new Set),[To,Xt]=De([]),[We,wt]=De([]),[Ye,Zt]=De([]),[lt,Io]=De([]),[Ve,Xe]=De(null),[Qt,kt]=De(""),gt=Ur(!1),[ct,xt]=De(!1),bt=nt(async()=>{if(!A)return[];let v=new B,y=[],c;do{let u=await v.listAvailableSkills(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.skills),c=u.nextKey}while(c);return wt(y),y},[A]),Ct=nt(async()=>{if(!A)return[];let v=new B,y=[],c;do{let u=await v.getSchedules(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.schedules),c=u.nextKey}while(c);return Zt(y),y},[A]),_e=nt(async v=>{if(v==="model"){if(P.length===0){p("No models available.");return}let y=P.map(u=>({id:u.id,name:u.name,description:u.description}));te(y);let c=r?y.findIndex(u=>u.id===r):-1;Se(Math.max(c,0)),w("model")}else if(v==="agent"){if(N.length===0){p("No agents available.");return}let y=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(y);let c=l?y.findIndex(u=>u.id===l):-1;Se(Math.max(c,0)),w("agent")}else if(v==="skills"){let y=We;if(y.length===0)try{y=await bt()}catch{p("Failed to load skills.");return}if(y.length===0){p("No skills available.");return}let c=y.map(u=>({id:u.id,name:u.name,description:u.description}));te(c),Se(0),w("skills")}else if(v==="schedules"){let y=Ye;if(y.length===0)try{y=await Ct()}catch{p("Failed to load schedules.");return}if(y.length===0){p("No schedules found.");return}let c=y.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(c),Se(0),w("schedules")}else if(v==="connectors"){if(R.length===0){p("No connectors available.");return}let y=R.map(c=>({id:c.id,name:c.name}));te(y),Se(0),it(new Set(b||[])),w("connectors")}else if(v==="capabilities"){let y=qn().map(u=>({id:u.id,name:u.name,description:u.description}));te(y),Se(0);let c=new Set;g&&c.add("sandbox"),$&&c.add("webSearch"),H&&c.add("imageGeneration"),ie&&c.add("chart"),$e&&c.add("fileSystem"),at(c),w("capabilities")}else if(v==="chats"){if(!A){p("Not authenticated.");return}try{let y=new B,{chats:c}=await y.getChats(A.accessToken,A.workspaceId,20);if(c.length===0){p("No chats available.");return}Xt(c);let u=c.map(I=>({id:I.id,name:I.title||"Untitled",description:new Date(I.createdAt).toLocaleDateString()}));te(u);let h=u.findIndex(I=>I.id===o);Se(Math.max(h,0)),w("chats")}catch{p("Failed to load chats.")}}else if(v==="profile"){let y=G.getProfileNames(),c=G.getCurrentProfileName(),u=y.map(I=>({id:I,name:I,description:I===c?"(current)":void 0}));te(u);let h=u.findIndex(I=>I.id===c);Se(Math.max(h,0)),w("profile")}O(!1),de([])},[P,N,We,Ye,R,b,r,l,bt,Ct,g,$,H,ie,$e,A,o,p]),ye=nt(v=>{let y=oe.getAll(v);a(y.model?.default),d(void 0),k(null);let c=y.connectors?.defaults;S(c&&c.length>0?c:void 0);let u=y.capabilities;m(u?.sandbox??pe.sandbox),D(u?.webSearch??pe.webSearch),X(u?.imageGeneration??pe.imageGeneration),z(u?.chart??pe.chart);let h=y.localTools;j(h?.fileSystem??pe.fileSystem)},[a,d,k,S,m,D,X,z,j,pe]),Ze=nt(async()=>{try{let v=await fe();ee({accessToken:v.accessToken,workspaceId:v.workspaceId}),Q({status:"ready"})}catch(v){if(ee(null),v instanceof Qe){if(v.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(v.code==="no-workspace"){Q({status:"no-workspace"});return}}let y=v instanceof Error?v.message:"Failed to authenticate";Q({status:"error",message:y})}},[ee,Q]),St=nt(async v=>{switch(v.type){case"help":return p(os),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(v.value){let y=v.value.toLowerCase(),c=P.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),k(null),oe.setDefaultModel(c.id);else{let u=P.map(h=>h.name).join(", ");p(`Model "${v.value}" not found.
|
|
146
|
+
Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!v.value)return N.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=v.value.toLowerCase(),c=N.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=N.map(h=>h.name).join(", ");p(`Agent "${v.value}" not found.
|
|
147
|
+
Available: ${u||"none"}`)}return!0}case"skills":{if(!v.value)return _e("skills"),!0;let y=v.value.toLowerCase();return(We.length>0?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let h=u.find(I=>I.id.toLowerCase()===y||I.name.toLowerCase().includes(y));p(h?`Skill: ${h.name}
|
|
148
|
+
${h.description}
|
|
149
|
+
Provider: ${h.provider}
|
|
150
|
+
Author: ${h.author.name}
|
|
151
|
+
ID: ${h.id}`:`Skill "${v.value}" not found.`)}),!0}case"schedules":{if(!v.value)return _e("schedules"),!0;let y=v.value.toLowerCase();return(Ye.length>0?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let h=u.find(I=>I.id.toLowerCase()===y||I.name.toLowerCase().includes(y));if(h){let I=h.nextRunAt?new Date(h.nextRunAt).toLocaleString():"-";p(`Schedule: ${h.name}
|
|
152
|
+
Agent: ${h.agent.name}
|
|
153
|
+
Status: ${h.isActive?"Active":"Paused"}
|
|
154
|
+
Repeat: ${Ho(h.config)}
|
|
155
155
|
Next Run: ${I}
|
|
156
|
-
ID: ${
|
|
156
|
+
ID: ${h.id}`)}else p(`Schedule "${v.value}" not found.`)}),!0}case"connectors":{if(l){let c=C?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(h=>` - ${h.name}`).join(`
|
|
157
157
|
`);p(`Agent connectors:
|
|
158
158
|
${u}`)}return!0}let y=R.filter(c=>b?.includes(c.id));if(y.length===0)p("No active connectors.");else{let c=y.map(u=>` - ${u.name}`).join(`
|
|
159
159
|
`);p(`Active connectors:
|
|
160
|
-
${c}`)}return!0}case"capabilities":{if(l){let u=(C?.capabilities||[]).map(
|
|
161
|
-
${u.map(
|
|
160
|
+
${c}`)}return!0}case"capabilities":{if(l){let u=(C?.capabilities||[]).map(h=>le.get(h)??h);return p(u.length>0?`Agent capabilities:
|
|
161
|
+
${u.map(h=>` - ${h}`).join(`
|
|
162
162
|
`)}`:"No agent capabilities."),!0}let y=[];return g&&y.push("Sandbox"),$&&y.push("Web Search"),H&&y.push("Image Generation"),ie&&y.push("Chart"),$e&&y.push("FileSystem"),p(y.length>0?`Active capabilities:
|
|
163
163
|
${y.map(c=>` - ${c}`).join(`
|
|
164
|
-
`)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!v.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let
|
|
164
|
+
`)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!v.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let h=u.map(I=>` ${I.id===A.workspaceId?"* ":" "}${I.name}
|
|
165
165
|
ID: ${I.id}`);p(`Workspaces:
|
|
166
|
-
${
|
|
167
|
-
`)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=v.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),
|
|
168
|
-
`))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=G.getCurrentProfileName(),c=r?P.find(x=>x.id===r)?.name||r:null,u=l?N.find(x=>x.id===l)?.name||l:null,
|
|
169
|
-
`))}).catch(()=>{let x=[`Profile: ${y}`,"Not logged in",E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${
|
|
170
|
-
`))}),!0}case"profile":{let y=v.value?v.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],
|
|
166
|
+
${h.join(`
|
|
167
|
+
`)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=v.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),h=u.find(I=>I.id===c);if(!h)return p(`Workspace not found: ${c}`),!0;await Ce.saveWorkspaceId(c),p(`Switched to workspace: ${h.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!v.value){try{let h=await y.getBudget(A.accessToken,A.workspaceId);h.budget===null?p("No budget set for this workspace."):p(`Current budget: $${h.budget}`)}catch(h){p(`Failed to get budget: ${h instanceof Error?h.message:"Unknown error"}`)}return!0}let c=v.value.toLowerCase();if(c==="clear"||c==="null"){try{await y.updateBudget(A.accessToken,A.workspaceId,null),p("Budget cleared.")}catch(h){p(`Failed to clear budget: ${h instanceof Error?h.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await y.updateBudget(A.accessToken,A.workspaceId,c),p(`Budget set to: $${c}`)}catch(h){p(`Failed to set budget: ${h instanceof Error?h.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let y=new B;try{let c=[],u,h=0,I=10;do{let Ie=await y.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...Ie.monthlyUsages),u=Ie.nextKey,h++,h>=I){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let x=0,L=0;for(let Ie of c)x+=parseFloat(Ie.totalCost),L+=Ie.operationCount;let ge=[...c].toSorted((Ie,ut)=>parseFloat(ut.totalCost)-parseFloat(Ie.totalCost)),J=10,ce=ge.slice(0,J),Ue=[`Total Cost: $${x.toFixed(2)}`,`Total Operations: ${L.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Ie=>` ${Ie.user.name}: $${parseFloat(Ie.totalCost).toFixed(2)} (${Ie.operationCount.toLocaleString()} ops)`)];c.length>J&&(Ue.push("",`... and ${c.length-J} more users`),Ue.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Ue.join(`
|
|
168
|
+
`))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=G.getCurrentProfileName(),c=r?P.find(x=>x.id===r)?.name||r:null,u=l?N.find(x=>x.id===l)?.name||l:null,h=b?R.filter(x=>b.includes(x.id)).map(x=>x.name):[],I=[];return g&&I.push("Sandbox"),$&&I.push("Web Search"),H&&I.push("Image Gen"),ie&&I.push("Chart"),$e&&I.push("FileSystem"),Ce.getEmail().then(x=>{let L=[`Profile: ${y}${y!=="default"?" (non-default)":""}`,x?`Logged in as: ${x}`:"Not logged in",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${h.length>0?h.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(L.join(`
|
|
169
|
+
`))}).catch(()=>{let x=[`Profile: ${y}`,"Not logged in",E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${h.length>0?h.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(x.join(`
|
|
170
|
+
`))}),!0}case"profile":{let y=v.value?v.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],h=y[2],I=G.getProfileNames(),x=G.getCurrentProfileName(),L=G.getOverrideProfile(),ge=(J,ce=!1)=>{if(J)return J;if(ce&&I.length===1)return I[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let J=[`Profiles (${I.length}):`];for(let ce of I){let Ue=ce===x?" (current)":"";J.push(` ${ce}${Ue}`)}return p(J.join(`
|
|
171
171
|
`)),!0}if(c==="current")return p(`Current profile: ${x}`),!0;if(c==="show"){let J=ge(u,!0),ce=oe.getAll(J),Ue=await Ce.getAll(J),Ie=!!Ue?.accessToken,ut=ce.capabilities?Object.entries(ce.capabilities).filter(([,vo])=>vo).map(([vo])=>vo):[],Vs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Ks=[`Profile: ${J}${J===x?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Vs}`,`Capabilities: ${ut.length>0?ut.join(", "):"none"}`,Ie?`Logged in as: ${Ue?.email??"unknown"}`:"Not logged in",Ie&&Ue?.workspaceId?`Workspace ID: ${Ue.workspaceId}`:null].filter(Boolean);return p(Ks.join(`
|
|
172
172
|
`)),!0}if(c==="create"){let J=u||G.DEFAULT_PROFILE;return G.createProfile(J),p(`Profile created: ${J}`),!0}if(c==="use"||c==="switch"){let J=ge(u,!0);return G.setOverrideProfile(J),G.setCurrentProfile(J),ye(J),await Ze(),re(`Switched to profile: ${J} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let J=ge(u,!0),ce=J===x,Ue=G.deleteProfile(J),Ie=`Profile deleted: ${J}`;if(ce)G.setOverrideProfile(Ue.currentProfile),ye(Ue.currentProfile),await Ze(),re(`${Ie}
|
|
173
173
|
Switched to profile: ${Ue.currentProfile} (new chat)`);else if(L===J){let ut=G.getCurrentProfileName();G.setOverrideProfile(ut),ye(ut),await Ze(),re(`${Ie}
|
|
174
|
-
Switched to profile: ${ut} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let J=ge(u,!0);if(!
|
|
174
|
+
Switched to profile: ${ut} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let J=ge(u,!0);if(!h)throw new Error("New profile name is required.");let ce=G.renameProfile(J,h);return p(`Profile renamed: ${J} -> ${h}`),L===J?(G.setOverrideProfile(h),ye(h)):ce.currentProfile===h&&ye(h),!0}if(c==="clone"||c==="copy"){let J=ge(u,!0);if(!h)throw new Error("Target profile name is required.");let ce=oe.getAll(J);return G.createProfile(h),oe.setAll(ce,h),await Ce.clear(h),p(`Profile cloned: ${J} -> ${h}`),!0}p(`Unknown profile command: ${c}`)}catch(J){let ce=J instanceof Error?J.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=E||W.some(x=>x.role!=="system")?`/chat/${o}`:"/chat/new",h=l?`?agentId=${encodeURIComponent(l)}`:"",I=`${y}${u}${h}`;try{await Zn(I),p(`Opened in browser: ${I}`)}catch(x){p(`Failed to open browser: ${x instanceof Error?x.message:"Unknown error"}
|
|
175
175
|
URL: ${I}`)}return!0}case"share":{if(!A)return p("Not authenticated."),!0;if(!(E||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new B().createChatShare(A.accessToken,A.workspaceId,o,"public"),I=`${Me().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${I}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return A?E?(xt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${v.input}
|
|
176
|
-
Type /help for available commands.`),!0;default:return!1}},[p,P,N,R,We,Ye,r,l,b,g,$,H,ie,$e,o,n,Z,_e,re,le,C,E,W,bt,Ct,_,a,d,k,a,ye,Ze]),eo=nt(v=>{if(gt.current=!1,ct){(v===""||v.startsWith("/"))&&(t(v),v.startsWith("/")&&xt(!1));return}if(t(v),kt(v),Ve!==null&&Xe(null),f&&(w(null),te([])),v.startsWith("/")&&!v.includes(" ")){let y=es(v);de(y),F(0),O(y.length>0)}else O(!1),de([])},[f,Ve,ct,t]),Lt=nt((v,y=!1)=>{if(v>=0&&v<q.length){let c=q[v];O(!1),de([]),c.name==="model"?(t("/model "),_e("model")):c.name==="agent"?(t("/agent "),_e("agent")):c.name==="skills"?(t("/skills "),_e("skills")):c.name==="schedules"?(t("/schedules "),_e("schedules")):c.name==="connectors"?(t("/connectors "),_e("connectors")):c.name==="capabilities"?(t("/capabilities "),_e("capabilities")):c.name==="chats"?(t("/chats "),_e("chats")):c.name==="profile"?(t("/profile "),_e("profile")):y?(t(""),St({type:c.name})):t(`/${c.name}`)}},[q,_e,t,St]),to=nt(async v=>{gt.current=!1;let y=v.trim();if(!y||ct)return;if(f==="model"&&T.length>0){let u=T[U];u&&(l?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),k(null)),w(null),te([]),t("");return}if(f==="agent"&&T.length>0){let u=T[U];u&&(u.id!==l?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&T.length>0){let u=T[U];if(u){let
|
|
177
|
-
${
|
|
178
|
-
Provider: ${
|
|
179
|
-
Author: ${
|
|
180
|
-
ID: ${
|
|
181
|
-
Agent: ${
|
|
182
|
-
Status: ${
|
|
183
|
-
Repeat: ${Ho(
|
|
176
|
+
Type /help for available commands.`),!0;default:return!1}},[p,P,N,R,We,Ye,r,l,b,g,$,H,ie,$e,o,n,Z,_e,re,le,C,E,W,bt,Ct,_,a,d,k,a,ye,Ze]),eo=nt(v=>{if(gt.current=!1,ct){(v===""||v.startsWith("/"))&&(t(v),v.startsWith("/")&&xt(!1));return}if(t(v),kt(v),Ve!==null&&Xe(null),f&&(w(null),te([])),v.startsWith("/")&&!v.includes(" ")){let y=es(v);de(y),F(0),O(y.length>0)}else O(!1),de([])},[f,Ve,ct,t]),Lt=nt((v,y=!1)=>{if(v>=0&&v<q.length){let c=q[v];O(!1),de([]),c.name==="model"?(t("/model "),_e("model")):c.name==="agent"?(t("/agent "),_e("agent")):c.name==="skills"?(t("/skills "),_e("skills")):c.name==="schedules"?(t("/schedules "),_e("schedules")):c.name==="connectors"?(t("/connectors "),_e("connectors")):c.name==="capabilities"?(t("/capabilities "),_e("capabilities")):c.name==="chats"?(t("/chats "),_e("chats")):c.name==="profile"?(t("/profile "),_e("profile")):y?(t(""),St({type:c.name})):t(`/${c.name}`)}},[q,_e,t,St]),to=nt(async v=>{gt.current=!1;let y=v.trim();if(!y||ct)return;if(f==="model"&&T.length>0){let u=T[U];u&&(l?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),k(null)),w(null),te([]),t("");return}if(f==="agent"&&T.length>0){let u=T[U];u&&(u.id!==l?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&T.length>0){let u=T[U];if(u){let h=We.find(I=>I.id===u.id);h&&p(`Skill: ${h.name}
|
|
177
|
+
${h.description}
|
|
178
|
+
Provider: ${h.provider}
|
|
179
|
+
Author: ${h.author.name}
|
|
180
|
+
ID: ${h.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&T.length>0){let u=T[U];if(u){let h=Ye.find(I=>I.id===u.id);if(h){let I=h.nextRunAt?new Date(h.nextRunAt).toLocaleString():"-";p(`Schedule: ${h.name}
|
|
181
|
+
Agent: ${h.agent.name}
|
|
182
|
+
Status: ${h.isActive?"Active":"Paused"}
|
|
183
|
+
Repeat: ${Ho(h.config)}
|
|
184
184
|
Next Run: ${I}
|
|
185
|
-
ID: ${
|
|
185
|
+
ID: ${h.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(rt);S(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let h=R.filter(I=>rt.has(I.id)).map(I=>I.name);p(h.length>0?`Active connectors: ${h.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),h=Re.has("webSearch"),I=Re.has("imageGeneration"),x=Re.has("chart"),L=Re.has("fileSystem");m(u),D(h),X(I),z(x),j(L),oe.setCapabilities({sandbox:u,webSearch:h,imageGeneration:I,chart:x}),oe.setLocalTools({fileSystem:L});let ge=[];u&&ge.push("Sandbox"),h&&ge.push("Web Search"),I&&ge.push("Image Generation"),x&&ge.push("Chart"),L&&ge.push("FileSystem"),p(ge.length>0?`Active capabilities: ${ge.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&T.length>0){let u=T[U];if(u){let h=G.getCurrentProfileName();u.id!==h?(G.setOverrideProfile(u.id),G.setCurrentProfile(u.id),ye(u.id),Ze(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&q.length>0){Lt(Te,!0);return}Xe(null),kt(""),Io(u=>u.length>0&&u.at(-1)===y?u:[...u,y]);let c=ts(y);if(c){await St(c),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),ke(y)},[ke,St,ne,q,Te,Lt,f,T,U,rt,Re,R,We,Ye,p,t,l,re,a,d,k,S,m,D,X,z,j,M,ye,Ze,ct,A,E,o]);return Rr((v,y)=>{if(y.ctrl&&v==="c"){if(e.length>0){eo(""),gt.current=!0,p("Press Ctrl+C again to exit.");return}if(gt.current){Z();return}Z();return}if(y.ctrl&&v==="o"){K(c=>!c);return}if(ct){if(y.escape||y.return||v==="n"||v==="N"){xt(!1),t(""),p("Chat deletion cancelled.");return}if(v==="y"||v==="Y"){xt(!1),t(""),A&&E&&new B().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&T.length>0){if(y.upArrow){Se(c=>c<=0?T.length-1:c-1);return}if(y.downArrow){Se(c=>c>=T.length-1?0:c+1);return}if(y.escape){w(null),te([]),t("");return}if(y.return){if(f==="model"){let c=T[U];c&&(l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),k(null),oe.setDefaultModel(c.id))}else if(f==="agent"){let c=T[U];c&&(c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0))}else if(f==="skills"){let c=T[U];if(c){let u=We.find(h=>h.id===c.id);u&&p(`Skill: ${u.name}
|
|
186
186
|
${u.description}
|
|
187
187
|
Provider: ${u.provider}
|
|
188
188
|
Author: ${u.author.name}
|
|
189
|
-
ID: ${u.id}`)}}else if(f==="schedules"){let c=T[U];if(c){let u=Ye.find(
|
|
189
|
+
ID: ${u.id}`)}}else if(f==="schedules"){let c=T[U];if(c){let u=Ye.find(h=>h.id===c.id);if(u){let h=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
|
|
190
190
|
Agent: ${u.agent.name}
|
|
191
191
|
Status: ${u.isActive?"Active":"Paused"}
|
|
192
192
|
Repeat: ${Ho(u.config)}
|
|
193
|
-
Next Run: ${
|
|
194
|
-
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);S(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=R.filter(
|
|
193
|
+
Next Run: ${h}
|
|
194
|
+
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);S(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=R.filter(h=>rt.has(h.id)).map(h=>h.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Re.has("sandbox"),u=Re.has("webSearch"),h=Re.has("imageGeneration"),I=Re.has("chart"),x=Re.has("fileSystem");m(c),D(u),X(h),z(I),j(x),oe.setCapabilities({sandbox:c,webSearch:u,imageGeneration:h,chart:I}),oe.setLocalTools({fileSystem:x});let L=[];c&&L.push("Sandbox"),u&&L.push("Web Search"),h&&L.push("Image Generation"),I&&L.push("Chart"),x&&L.push("FileSystem"),p(L.length>0?`Active capabilities: ${L.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=T[U];if(c){let u=To.find(h=>h.id===c.id);u&&A&&(s(u.id),i(u.title||void 0),he(!0),new B().getMessages(A.accessToken,A.workspaceId,u.id,20).then(({messages:I})=>{let x=I.filter(L=>L.role==="user"||L.role==="assistant").map(L=>({role:L.role,content:ht(L.parts,!1),parts:L.parts})).filter(L=>L.content).toReversed();_(x),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=T[U];if(c){let u=G.getCurrentProfileName();c.id!==u?(G.setOverrideProfile(c.id),G.setCurrentProfile(c.id),ye(c.id),Ze(),re(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),te([]),t("");return}if(v===" "&&(f==="connectors"||f==="capabilities")){let c=T[U];c&&(f==="connectors"?it:at)(h=>{let I=new Set(h);return I.has(c.id)?I.delete(c.id):I.add(c.id),I});return}if(v==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set(T.map(u=>u.id)));return}if(v==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set);return}return}if(ne&&q.length>0){if(y.upArrow){F(c=>c<=0?q.length-1:c-1);return}if(y.downArrow){F(c=>c>=q.length-1?0:c+1);return}if(y.escape){O(!1),de([]);return}if(y.tab){Lt(Te);return}}if(y.upArrow){if(e.includes(`
|
|
195
195
|
`)||lt.length===0)return;if(Ve===null){kt(e);let u=lt.length-1;Xe(u),t(lt[u]);return}let c=Math.max(0,Ve-1);Xe(c),t(lt[c]);return}if(y.downArrow){if(e.includes(`
|
|
196
|
-
`)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:q,suggestionIndex:Te,showSuggestions:ne,argMode:f,argItems:T,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as jr,useState as Br}from"react";function ss({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=Br([]),a=jr(0),l=Jt(
|
|
196
|
+
`)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:q,suggestionIndex:Te,showSuggestions:ne,argMode:f,argItems:T,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as jr,useState as Br}from"react";function ss({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=Br([]),a=jr(0),l=Jt(m=>{if(!(!Array.isArray(o)||o.length===0)){for(let $ of o)if($.models.some(H=>H.id===m))return $.id;return o[0]?.id}},[o]),d=Jt(async m=>{if(!e){n?.(m.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(m.filename,"Model providers not loaded yet. Please wait and try again.");return}let $=t?l(t):o[0]?.id;if(!$){n?.(m.filename,"No model provider available");return}let D=`file-${++a.current}`;r(H=>[...H,{id:D,filename:m.filename,mimeType:m.mimeType,status:"uploading"}]);try{let X=await new B().uploadFile(e.accessToken,e.workspaceId,m,$);r(ie=>ie.map(z=>z.id===D?{...z,status:"uploaded",fileId:X.id}:z)),s?.(m.filename)}catch(H){let X=H instanceof Error?H.message:"Upload failed";r(ie=>ie.map(z=>z.id===D?{...z,status:"error",error:X}:z)),n?.(m.filename,X)}},[e,t,l,o,s,n]),C=Jt(m=>{r($=>$.filter(D=>D.id!==m))},[]),k=Jt(()=>{r([])},[]),b=Jt(()=>i.filter(m=>m.status==="uploaded"&&m.fileId).map(m=>m.fileId),[i]),S=i.some(m=>m.status==="uploading"),g=i.length>0;return{pendingFiles:i,addFile:d,removeFile:C,clearFiles:k,getUploadedFileIds:b,hasUploadingFiles:S,hasFiles:g}}import{jsx as Y,jsxs as ue}from"react/jsx-runtime";var Wr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Mr=[Jo,Jo,Mo,Mo,mt,mt,mt,mt],is=Wr.map((e,t)=>`${Mr[t]??mt}${e}${se}`).join(`
|
|
197
197
|
`),Jr=`${mt}EntryDesk${se}`,Gr=500;function Hr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Vr(e){let t=Hr(e);return Math.max(...t.split(`
|
|
198
|
-
`).map(o=>o.length))}function Kr(e){let t=Vr(is);return e>=t?is:Jr}function as({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:C=!0}){let k=process.stdout.columns??80,b=Kr(k),S=rs(null),g=Bn(s,n),{state:
|
|
198
|
+
`).map(o=>o.length))}function Kr(e){let t=Vr(is);return e>=t?is:Jr}function as({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:C=!0}){let k=process.stdout.columns??80,b=Kr(k),S=rs(null),g=Bn(s,n),{state:m,setState:$,messages:D,setMessages:H,input:X,setInput:ie,chatId:z,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:P,hasPersistedChat:N,setHasPersistedChat:R,credentials:W,setCredentials:E,currentResponse:he,setCurrentResponse:_,fullOutput:p,setFullOutput:re,addSystemMessage:ke,startNewChat:K}=g,{credentials:A}=Wn($);ho(()=>{A&&!W&&E(A)},[A,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:M}=Mn(W),{currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,activeConnectorIds:F,setActiveConnectorIds:ne}=Xn(t,e,i),O=rs(!1);ho(()=>{if(!O.current){if(O.current=!0,!t&&!e){let x=oe.getDefaultModel();x&&q(x)}if(!i&&!e){let x=oe.getDefaultConnectorIds();x&&ne(x.length>0?x:void 0)}}},[t,e,i,q,ne]);let{currentAgentDetails:f}=Yn(de,W),{sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:Se,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,capabilityLabelMap:Xt}=zn(r,a,l,d,C),{pendingFiles:We,addFile:wt,removeFile:Ye,clearFiles:Zt,getUploadedFileIds:lt,hasUploadingFiles:Io,hasFiles:Ve}=ss({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:x=>{ke(`\u2713 Attached: ${x}`)},onUploadError:(x,L)=>{ke(`\u2717 Failed to upload ${x}: ${L}`)}}),{sendMessage:Xe}=Hn({chatId:z,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:F,sandbox:w,webSearch:te,imageGeneration:Se,chart:it,localTools:at,fullOutput:p,setMessages:H,setState:$,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:R,getFileIds:lt,clearFiles:Zt}),Qt=qo(x=>{K(x),_("")},[K]),[kt,gt]=Fr(!1),ct=qo(async x=>{let L=x.text.trim(),ge=po(L);if(/^https?:\/\//.test(ge))return;if(await On(L)&&Dn(ge)){let ce=await Rn(L);ce&&(x.preventDefault(),await wt(ce))}},[wt]),xt=qo(async()=>{if(!(kt||m.status!=="ready")){if(M||le.length===0){ke("Please wait for resources to load before pasting images.");return}ke("Reading clipboard..."),gt(!0);try{let x=await Ln();if(x){let L=`clipboard-${Date.now()}.png`;ke(`Uploading: ${L} (${Math.round(x.buffer.length/1024)}KB)`),await wt({buffer:x.buffer,filename:L,mimeType:x.mime})}else ke("No image found in clipboard. Copy an image first.")}catch(x){let L=x instanceof Error?x.message:"Failed to read clipboard";ke(`Clipboard error: ${L}`)}finally{gt(!1)}}},[wt,ke,kt,m.status,M,le.length]),{suggestions:bt,suggestionIndex:Ct,showSuggestions:_e,argMode:ye,argItems:Ze,argIndex:St,selectedConnectorIds:eo,selectedCapabilities:Lt,deleteConfirmMode:to,handleInputChange:v,handleSubmit:y}=ns({input:X,setInput:ie,chatId:z,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:P,currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:ne,sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:Se,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:D,hasPersistedChat:N,setHasPersistedChat:R,setMessages:H,addSystemMessage:ke,startNewChat:Qt,sendMessage:Xe,setFullOutput:re,credentials:W,setCredentials:E,setState:$,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:l,chart:d,fileSystem:C},capabilityLabelMap:Xt,hasUploadingFiles:Io});if(Vo((x,L)=>{(L.ctrl||L.meta)&&x==="v"&&xt()},{isActive:m.status==="ready"&&!ye}),Vo((x,L)=>{if(!L.escape)return;let ge=Date.now(),J=S.current;S.current=ge,!(!J||ge-J>Gr)&&(ye||_e||(S.current=null,Ve&&Zt(),X.length>0&&v("")))},{isActive:m.status==="ready"}),Vo((x,L)=>{L.return&&(Qt("Started a new chat."),$({status:"ready"}))},{isActive:m.status==="error"}),ho(()=>{if(W&&!M&&m.status==="loading")if(!Z&&!de){let x=oe.getDefaultModel(),L=x&&Q.some(J=>J.id===x),ge=L?x:Q[0]?.id;ge?(L||oe.setDefaultModel(ge),q(ge),$({status:"ready"})):pe.length===0?$({status:"no-model"}):$({status:"ready"})}else $({status:"ready"})},[W,M,Z,de,Q,pe,m.status,q,$]),ho(()=>{o&&W&&m.status==="ready"&&Xe(o)},[W,o]),m.status==="loading")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),ue(Pe,{children:[Y(V,{color:"cyan",children:Y(Ko,{type:"dots"})}),Y(V,{children:" Initializing chat..."})]})]});if(m.status==="not-logged-in")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"Not logged in"}),Y(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(m.status==="no-workspace")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No workspace selected"}),Y(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(m.status==="no-model")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No model or agent specified"}),s&&Y(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),Y(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),Y(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(m.status==="error")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),ue(V,{color:"red",children:["Error: ",m.message]}),Y(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(x=>x.name).join(", "):"none":"loading...":F&&F.length>0?ee.filter(x=>F.includes(x.id)).map(x=>x.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let x of f.capabilities)u.push(Xt.get(x)??x);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),Se&&u.push("Image"),it&&u.push("Chart");at&&u.push("FileSystem");let h=G.getCurrentProfileName(),I=h!=="default";return ue(Pe,{flexDirection:"column",children:[ue(Pe,{marginBottom:1,flexDirection:"column",children:[Y(V,{children:b}),ue(Pe,{children:[Y(V,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.7.13"]}),I&&ue(V,{color:"magenta",children:[" [",h,"]"]}),Y(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),D.map((x,L)=>{let ge=x.parts&&p?ht(x.parts,!0):x.content,J=x.role==="user"?"green":x.role==="system"?"yellow":"blue",ce=x.role==="user"?"You":x.role==="system"?"System":"Assistant";return ue(Pe,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:J,children:[ce,":"]}),Y(Wo,{text:ge})]},L)}),he&&ue(Pe,{flexDirection:"column",marginBottom:1,children:[Y(V,{bold:!0,color:"blue",children:"Assistant:"}),Y(Wo,{text:he})]}),m.status==="ready"&&Y(hn,{suggestions:bt,activeIndex:Ct,visible:_e}),m.status==="ready"&&ye&&Y(mn,{items:Ze,activeIndex:St,pageSize:ye==="agent"||ye==="skills"||ye==="model"?5:10,selectedIds:ye==="connectors"?eo:ye==="capabilities"?Lt:void 0,multiSelect:ye==="connectors"||ye==="capabilities",visible:!0,title:ye==="model"?"Select model:":ye==="agent"?"Select agent:":ye==="skills"?"Select skill:":ye==="connectors"?"Select connectors:":ye==="capabilities"?"Select capabilities:":"Select chat:"}),m.status==="sending"&&!he?ue(Pe,{children:[Y(V,{color:"cyan",children:Y(Ko,{type:"dots"})}),Y(V,{children:" Thinking..."})]}):m.status==="ready"&&!ye?ue(Pe,{flexDirection:"column",children:[to&&Y(Pe,{marginBottom:1,children:Y(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ve&&!to&&ue(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[Y(V,{dimColor:!0,children:"Attachments:"}),We.map((x,L)=>ue(V,{children:[x.status==="uploading"?ue(V,{color:"yellow",children:[Y(Ko,{type:"dots"})," ",x.filename]}):x.status==="error"?ue(V,{color:"red",children:["\u2717 ",x.filename]}):ue(V,{color:"green",children:["\u2713 ",x.filename]}),L<We.length-1&&Y(V,{children:", "})]},x.id))]}),ue(Pe,{children:[Y(V,{color:"green",children:"> "}),Y($n,{value:X,onChange:v,onSubmit:y,onPaste:ct,leadingOffset:2,multiline:!0})]})]}):null,ue(Pe,{marginTop:1,flexDirection:"column",children:[ue(Pe,{gap:2,children:[ue(V,{children:[Y(V,{dimColor:!0,children:"Model: "}),Y(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(x=>x.id===Z)?.name||Z||"none"})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Connectors: "}),Y(V,{color:"cyan",children:c})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Capabilities: "}),Y(V,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(V,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Zr}from"react/jsx-runtime";async function zr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function Yr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=n[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,o,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var vt="\x1B[2m",Oe="\x1B[0m",zo="\x1B[36m",ds="\x1B[33m",wo="\x1B[32m",ls="stream-json";function cs(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function ko(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
|
|
199
199
|
`)}function xo(e,t){if(t)return e;let o=e.split(`
|
|
200
200
|
`);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${vt}... (${i} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
|
|
201
201
|
`)}function Xr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function us(e,t){if(!e)return"(no result)";if(typeof e!="object")return xo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${ds}[stderr]${Oe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),xo(n.join(`
|
|
202
202
|
`),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
|
|
203
203
|
`);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}async function fs(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){xe(ee)}let s=e.output===ls;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${ls}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=oe.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await zr());let a=new B;async function l(){if(!i)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),i=Q}catch{}}let d,C,k,b;if(e.continue){let ee=await Yr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,C=ee.chat.title??void 0,k=ee.chat.agentId??void 0,b=ee.modelId;let Q=e.agentId||e.model||k||b||i;!Q&&!e.interactive&&(await l(),Q=e.agentId||e.model||k||b||i),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
|
|
204
204
|
Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
|
|
205
|
-
`)}let S=e.agentId||k,g=e.model||b||i||void 0;!S&&!g&&(await l(),g=e.model||b||i||void 0),cs(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),cs(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let
|
|
205
|
+
`)}let S=e.agentId||k,g=e.model||b||i||void 0;!S&&!g&&(await l(),g=e.model||b||i||void 0),cs(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),cs(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let m=oe.getCapabilities(),$=e.noSandbox?!1:e.sandbox?!0:m?.sandbox??!0,D=e.webSearch??m?.webSearch??!1,H=e.imageGen??m?.imageGeneration??!1,X=e.chart??m?.chart??!1,ie=oe.getDefaultConnectorIds(),z=e.connectors??ie??void 0,$e=oe.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:$e?.fileSystem??!0;if(e.interactive){qr(Zr(as,{agentId:S,model:g,message:e.message,chatId:d,chatTitle:C??void 0,connectorIds:z,enableSandbox:$,enableWebSearch:D,enableImageGeneration:H,enableChart:X,enableFileSystem:j}),{exitOnCtrlC:!1});return}let P=!e.continue&&!g&&!S;(!r||P)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -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 chat 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(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||yo(),W=j?no():void 0,E=j?so():void 0,he=[],_=yo(),p=(ee,Q,pe)=>{let le={id:R};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),S?le.agentId=S:(g&&(le.model=g),le.connectorIds=z??[],le.enableSandbox=$,le.enableWebSearch=D,le.enableImageGeneration=H,le.enableChart=X),W&&(le.clientTools=W),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},re=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",M=new Map,Z=[],q=[];for(;;){let{done:de,value:Te}=await Q.read();if(de)break;le+=pe.decode(Te,{stream:!0});let F=le.split(`
|
|
206
206
|
`);le=F.pop()||"";for(let ne of F){let O=ne.trimEnd();if(O==="data: [DONE]"){s&&ko("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&q.push(f),s){f.type==="text-delta"&&f.delta!==void 0?ko("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ko("reasoning-delta",f.delta):ko(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),j&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&tt(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${vt}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
|
|
207
207
|
|
|
208
208
|
`);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let T=j&&tt(f.toolName)?`${wo}[LOCAL]${Oe} `:"";console.log(`
|
|
@@ -226,9 +226,9 @@ ${zo}\u250C\u2500 ${T}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case
|
|
|
226
226
|
`))}return o.join(`
|
|
227
227
|
|
|
228
228
|
`).trim()}async function ws(e){let t=e.output===gs;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${gs}`),process.exit(1));let o=new B;if(e.shareId){let r;try{r=await dt()}catch{}try{let a=await o.getSharedChat(e.shareId,r),{messages:l}=await o.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(ze("chat",a),l.length===0)ze("info","No messages in this shared chat.");else for(let k of l.toReversed())ze("message",k);ze("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
|
|
229
|
-
`),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),C=e.fullOutput??!1;for(let k of d){let b=ys(k.parts,C);if(!b)continue;let S=k.role==="user"?"You":"Assistant";console.log(`[${S}] ${Yo(k.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await fe();s=r.accessToken,n=r.workspaceId}catch(r){xe(r)}if(e.chatId){let r=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let g=d===0?1:d,{chats:
|
|
229
|
+
`),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),C=e.fullOutput??!1;for(let k of d){let b=ys(k.parts,C);if(!b)continue;let S=k.role==="user"?"You":"Assistant";console.log(`[${S}] ${Yo(k.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await fe();s=r.accessToken,n=r.workspaceId}catch(r){xe(r)}if(e.chatId){let r=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let g=d===0?1:d,{chats:m}=await o.getChats(s,n,20);g>m.length&&(console.error(`Chat number ${g} not found. You have ${m.length} recent chats.`),process.exit(1));let $=m[g-1];r=$.id,a=!0,l=$,t||console.log(`Chat: ${$.title||"Untitled"}
|
|
230
230
|
`)}let{messages:k}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(k));return}if(t){if(l&&ze("chat",l),k.length===0)ze("info","No messages in this chat.");else for(let g of k.toReversed())ze("message",g);ze("done");return}if(k.length===0){console.log("No messages in this chat.");return}let b=k.toReversed(),S=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${k.length} messages
|
|
231
|
-
`);for(let g of b){let
|
|
231
|
+
`);for(let g of b){let m=ys(g.parts,S);if(!m)continue;let $=g.role==="user"?"You":"Assistant";console.log(`[${$}] ${Yo(g.createdAt)}`),console.log(m),console.log("")}return}let{chats:i}=await o.getChats(s,n,20);if(t){for(let r of i)ze("chat",r);ze("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
|
|
232
232
|
`),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${Yo(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as ei,Text as Ne}from"ink";import{jsx as je,jsxs as Pt}from"react/jsx-runtime";var At=["apiUrl","hubUrl"];function Qo(e){return At.includes(e)}async function ks(e){let t=e.action||"list",o=e.configKey,s=e.value,n=G.getEffectiveProfileName();if(t==="list"){let i=oe.getAll(),r=Object.entries(i);if(e.json){console.log(JSON.stringify(i));return}if(console.log(`Profile: ${n}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${At.join(", ")}`);return}console.log(`Configuration:
|
|
233
233
|
`);for(let[a,l]of r)console.log(` ${a}=${l}`);console.log(`
|
|
234
234
|
Available keys: ${At.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1));let i=oe.get(o);e.json?console.log(JSON.stringify({[o]:i??null})):console.log(i||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function xs(){let e=Me();return Pt(ei,{flexDirection:"column",children:[je(Ne,{bold:!0,children:"entrydesk config"}),je(Ne,{children:" "}),je(Ne,{children:"Manage CLI configuration"}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Usage:"}),je(Ne,{children:" entrydesk config List all configuration"}),Pt(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Available keys:"}),Pt(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Pt(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Examples:"}),je(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),je(Ne,{children:" entrydesk config get apiUrl"}),je(Ne,{children:" entrydesk config unset apiUrl"})]})}async function bs(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
|
|
@@ -402,7 +402,7 @@ Local Development:
|
|
|
402
402
|
For more information, visit https://entrydesk.com/docs/cli
|
|
403
403
|
`)}import{render as ci}from"ink";import{randomUUID as ti}from"crypto";import{chromium as oi}from"playwright";function ni(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function si(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid hub URL. Please check ENTRYDESK_HUB_URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Hub URL must use http or https.");if(t.username||t.password)throw new Error("Hub URL must not include credentials.");if(!t.hostname)throw new Error("Hub URL must include a hostname.");if(t.protocol==="http:"&&!ni(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function ri(e){try{let t=e.split(".");if(t.length<2)return null;let o=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-o.length%4)%4,n=o.padEnd(o.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i).exp??null}catch{return null}}async function en(e){let{hubUrl:t,auth:o}=Me(),s=si(t),n=new URL("/login",s),i=ti();n.searchParams.set("cli","true"),n.searchParams.set("state",i);let r;try{r=await oi.launch({headless:!1,args:["--disable-blink-features=AutomationControlled"]})}catch(a){throw a instanceof Error&&a.message.includes("Executable")?new Error(`Chromium browser is not installed. Please run:
|
|
404
404
|
npm install -g playwright
|
|
405
|
-
npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",g=>{console.log(`[Browser Console] ${g.type()}: ${g.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(g=>{let
|
|
405
|
+
npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",g=>{console.log(`[Browser Console] ${g.type()}: ${g.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(g=>{let m=new URL(g);if(m.host!==d)return!1;let $=m.pathname;if($==="/login"||$.startsWith("/auth/"))return!1;let D=m.searchParams.get("state");return!(D&&D!==i)},{timeout:o.loginTimeout});let C=new URL("/api/auth/session",s).toString();process.env.DEBUG&&(console.log(`[DEBUG] Fetching session from: ${C}`),console.log(`[DEBUG] Current page URL: ${l.url()}`),console.log(`[DEBUG] SSL ignore enabled: ${o.ignoreSslErrors}`));let k=await l.evaluate(async g=>{try{let m=await fetch(g);if(!m.ok)throw new Error(`Failed to fetch session: ${m.status} ${m.statusText}`);return m.json()}catch(m){throw console.error("[Browser Context] Fetch error:",m),m}},C);if(!k?.accessToken)throw new Error("Failed to get access token from session");let b=ri(k.accessToken);if(b&&b*1e3<=Date.now())throw new Error("Access token is expired. Please log in again.");let S=k.user?.email||"";return e?.onLoginSuccess?.(S||"unknown"),{accessToken:k.accessToken,email:S,workspaceId:k.currentWorkspaceId}}catch(a){let l;throw a instanceof Error?(l=a,l.message.includes("fetch failed")&&(l=new Error(`Network request failed. This might be due to SSL certificate issues. Current SSL ignore setting: ${o.ignoreSslErrors}. Original error: ${l.message}`))):l=new Error("Browser authentication failed."),e?.onError?.(l),l}finally{await r.close()}}import{Box as Ee,Text as Le,useApp as ii,useInput as ai}from"ink";import li from"ink-spinner";import Cs from"ink-text-input";import{useState as Ht}from"react";import{jsx as me,jsxs as Ge}from"react/jsx-runtime";function Ss(){let{exit:e}=ii(),[t,o]=Ht("email"),[s,n]=Ht(""),[i,r]=Ht(""),[a,l]=Ht(null),[d,C]=Ht(null);return ai((S,g)=>{g.escape&&e()}),Ge(Ee,{flexDirection:"column",padding:1,children:[me(Ee,{marginBottom:1,children:me(Le,{bold:!0,color:"cyan",children:"EntryDesk Login"})}),t==="email"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{children:"Email: "}),me(Cs,{value:s,onChange:n,onSubmit:S=>{if(!S.includes("@")){l("Please enter a valid email address");return}n(S),l(null),o("password")},placeholder:"user@example.com"})]}),a&&me(Ee,{marginTop:1,children:me(Le,{color:"red",children:a})}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Press Enter to continue, Esc to cancel"})})]}),t==="password"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{children:"Email: "}),me(Le,{color:"green",children:s})]}),Ge(Ee,{children:[me(Le,{children:"Password: "}),me(Cs,{value:i,onChange:r,onSubmit:async S=>{r(S),o("loading"),l(null);try{let g=new B,{token:m,refreshToken:$}=await g.login(s,S),{workspaces:D}=await g.getWorkspaces(m),H=D[0];await Ce.saveAll({accessToken:m,refreshToken:$,email:s,workspaceId:H?.id}),C(H?.name??null),o("success"),setTimeout(()=>{e()},1500)}catch(g){o("error"),g instanceof Error?g.message.includes("403")||g.message.includes("Invalid")?l("Invalid email or password"):l(g.message):l("Login failed. Please try again.")}},mask:"*",placeholder:"Enter password"})]}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Press Enter to login, Esc to cancel"})})]}),t==="loading"&&Ge(Ee,{children:[me(Le,{color:"cyan",children:me(li,{type:"dots"})}),me(Le,{children:" Logging in..."})]}),t==="success"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{color:"green",children:"\u2713"}),me(Le,{children:" Logged in as "}),me(Le,{bold:!0,children:s})]}),d&&me(Ee,{children:Ge(Le,{dimColor:!0,children:["Workspace: ",d]})})]}),t==="error"&&Ge(Ee,{flexDirection:"column",children:[me(Ee,{children:me(Le,{color:"red",children:"\u2717 Login failed"})}),a&&me(Ee,{children:me(Le,{color:"red",children:a})}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Run `entrydesk login` to try again"})})]})]})}import{jsx as ui}from"react/jsx-runtime";async function $s(e){if(!!(e.email||e.password)){(!e.email||!e.password)&&(console.error("Usage: entrydesk login --email <email> --password <password>"),console.error(" entrydesk login"),console.error(" entrydesk login --google"),console.error(" entrydesk login -i (interactive mode)"),process.exit(1));let a=new B,{token:l,refreshToken:d}=await a.login(e.email,e.password),{workspaces:C}=await a.getWorkspaces(l),k=C[0];await Ce.saveAll({accessToken:l,refreshToken:d,email:e.email,workspaceId:k?.id}),e.json?console.log(JSON.stringify({email:e.email,workspaceId:k?.id,workspaceName:k?.name})):(console.log(`Logged in as ${e.email}`),k&&console.log(`Workspace: ${k.name}`));return}if(e.google){console.log("Opening browser for Google OAuth...");let a=await en(),l=new B,{workspaces:d}=await l.getWorkspaces(a.accessToken),C=d[0],k=a.workspaceId||C?.id;await Ce.saveAll({accessToken:a.accessToken,refreshToken:"",email:a.email,workspaceId:k}),e.json?console.log(JSON.stringify({email:a.email,workspaceId:k,workspaceName:C?.name})):(console.log(`Logged in as ${a.email}`),C&&console.log(`Workspace: ${C.name}`));return}if(e.interactive){ci(ui(Ss,{}));return}if(console.log("Opening browser for login..."),process.env.DEBUG){let{getApiUrl:a,getHubUrl:l}=await import("./config-MDF3SS7Z.js");console.log(`[DEBUG] Hub URL: ${l()}`),console.log(`[DEBUG] API URL: ${a()}`)}let o=await en(),s=new B,{workspaces:n}=await s.getWorkspaces(o.accessToken),i=n[0],r=o.workspaceId||i?.id;await Ce.saveAll({accessToken:o.accessToken,refreshToken:"",email:o.email,workspaceId:r}),e.json?console.log(JSON.stringify({email:o.email,workspaceId:r,workspaceName:i?.name})):(console.log(`Logged in as ${o.email}`),i&&console.log(`Workspace: ${i.name}`))}async function Ts(e){try{let t=await Ce.getAll();if(!t){console.log("Not logged in");return}try{await new B().revokeToken(t.refreshToken)}catch{}await Ce.clear(),console.log("Logged out successfully")}catch(t){xe(t)}}import di from"http";import{Client as fi}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as pi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as gi}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as hi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as yi,ListToolsRequestSchema as wi}from"@modelcontextprotocol/sdk/types.js";async function ki(e,t,o){let s=new fi({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new pi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Is(e){let t=new gi({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(wi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(yi,async o=>{let{name:s,arguments:n}=o.params,i=await e.callTool({name:s,arguments:n}),r=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&r.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:r,structuredContent:i.structuredContent,isError:i.isError}}),t}async function xi(e,t){let o=di.createServer(async(s,n)=>{if(s.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),n.writeHead(204),n.end();return}if(s.url!=="/mcp"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Not found"}));return}let i=Is(e),r=new hi({sessionIdGenerator:void 0});if(n.setHeader("Access-Control-Allow-Origin","*"),n.on("close",()=>{r.close(),i.close()}),await i.connect(r),s.method==="POST"){let a="";s.on("data",l=>{a+=l.toString()}),s.on("end",async()=>{try{let l=JSON.parse(a);await r.handleRequest(s,n,l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Invalid JSON"}))}})}else await r.handleRequest(s,n)});o.listen(t,()=>{console.error(`EntryDesk MCP server running at http://localhost:${t}/mcp`),console.error("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{console.error(`
|
|
406
406
|
Shutting down...`),o.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{o.close(),await e.close(),process.exit(0)})}async function bi(e){let t=Is(e),o=new mi;o.onclose=async()=>{await e.close()},await t.connect(o)}async function vs(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{console.error("[entrydesk-mcp] Starting MCP server...");let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let a=r instanceof Error?r.message:"Authentication failed";console.error(a),process.exit(1)}let{apiUrl:s,mcp:n}=Me();console.error(`[entrydesk-mcp] Connecting to ${s}...`),console.error(`[entrydesk-mcp] Workspace: ${o}`);let i=await ki(s,t,o);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||n.httpPort;await xi(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await bi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Ps(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
|
|
407
407
|
`);for(let i of n)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){xe(t)}}function Ci(){console.log(`
|
|
408
408
|
Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
|
|
@@ -477,7 +477,7 @@ Options:
|
|
|
477
477
|
--me Only list skills created by me
|
|
478
478
|
--force Overwrite an existing skill with the same name
|
|
479
479
|
--json Output JSON (for list/upload/versions)
|
|
480
|
-
`)}function Pi(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Ai(e){let t=await Nt.realpath(e),o=[process.cwd(),_s.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await Nt.realpath(i)}catch{return st.resolve(i)}}))).some(i=>Pi(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ni(e){let t=await Nt.mkdtemp(st.join(_s.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ii.createWriteStream(o),r=vi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function Ls(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new B;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),So(),process.exit(1));let l=st.resolve(a),d;try{d=await Nt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let C=l,k=null;try{try{await Ai(l)}catch(
|
|
480
|
+
`)}function Pi(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Ai(e){let t=await Nt.realpath(e),o=[process.cwd(),_s.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await Nt.realpath(i)}catch{return st.resolve(i)}}))).some(i=>Pi(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ni(e){let t=await Nt.mkdtemp(st.join(_s.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ii.createWriteStream(o),r=vi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function Ls(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new B;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),So(),process.exit(1));let l=st.resolve(a),d;try{d=await Nt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let C=l,k=null;try{try{await Ai(l)}catch(m){let $=m instanceof Error?m.message:"Invalid upload path.";console.error($),process.exit(1)}if(d.isDirectory()){let m=await Ni(l);C=m.zipPath,k=m.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));st.extname(C).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await Nt.readFile(C),S=new FormData;S.append("file",new Blob([b],{type:"application/zip"}),st.basename(C)),e.force&&S.append("force","true");let g;try{g=await n.uploadSkill(t,o,S)}catch(m){if(m instanceof Error&&m.name==="HTTPError"){let $=m;if($.response&&$.response.status===409){try{(await $.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw m}if(e.json){console.log(JSON.stringify(g));return}console.log(`Uploaded skill: ${g.name}`),console.log(` ID: ${g.id}`),console.log(` Version ID: ${g.versionId}`),console.log(` Description: ${g.description}`);return}finally{k&&await Nt.rm(k,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),So(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(s==="versions"){let a=e.configKey;a||(console.error("Missing skill name."),So(),process.exit(1));let l=[],d;do{let b=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});l.push(...b.skills),d=b.nextKey}while(d);let C=l.find(b=>b.name===a);C||(console.error(`Skill not found: ${a}`),process.exit(1));let k=await n.listSkillVersions(t,o,C.id);if(e.json){console.log(JSON.stringify(k));return}if(console.log(`Versions for skill "${k.skillName}":
|
|
481
481
|
`),k.versions.length===0){console.log(" No versions found.");return}for(let b of k.versions){let S=new Date(b.createdAt);console.log(` ${S.toLocaleString()}`),console.log(` ID: ${b.id}`),console.log(` Description: ${b.description.slice(0,80)}`),console.log(` Created by: ${b.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),So(),process.exit(1));let i=[],r;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:r,limit:100});i.push(...a.skills),r=a.nextKey}while(r);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${i.length}):
|
|
482
482
|
`);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Ds(e){try{let t=G.getEffectiveProfileName(),o=await Ce.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let i=new B,r=await dt(),{workspaces:a}=await i.getWorkspaces(r);n=a.find(d=>d.id===o.workspaceId)?.name}catch(i){if(i instanceof Qe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){xe(t)}}import Mi from"fs";import{Client as Ei}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as _i}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Li(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Me().apiUrl);let n=new Ei({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new _i(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function $o(){return Li()}import on from"fs/promises";import Di from"os";import zt from"path";var tn=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,Et={green:tn?"\x1B[32m":"",yellow:tn?"\x1B[33m":"",reset:tn?"\x1B[0m":""},Oi=10*1024,Os=8*1024,Rs=2*1024,Ri=100,Ui=100;function ji(){return zt.join(Di.homedir(),".entrydesk","tool-results")}function Bi(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Ri);return!t||t==="."||t===".."?"unnamed_tool":t}function Fi(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Wi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=Bi(e);return`${o}_${s}.json`}async function Us(e,t){try{return await on.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function js(e,t){try{let o=ji();await on.mkdir(o,{recursive:!0});let s=Wi(e),n=zt.extname(s),i=s.slice(0,-n.length),r=Fi(t),a=zt.join(o,s);if(await Us(a,r))return a;for(let C=1;C<=Ui;C++){let k=zt.join(o,`${i}-${C}${n}`);if(await Us(k,r))return k}let l=Math.random().toString(36).slice(2,10),d=zt.join(o,`${i}-${l}${n}`);return await on.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Et.yellow}Warning: Could not save result to file: ${s}${Et.reset}`),null}}function Bs(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Oi)return e;let s=e.slice(0,Os),n=e.slice(-Rs),r=((o-Os-Rs)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(l+=`
|
|
483
483
|
Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
|
|
@@ -525,10 +525,10 @@ Examples:
|
|
|
525
525
|
entrydesk usage --limit 10 # Show top 10 users
|
|
526
526
|
entrydesk usage --sort-by operations # Sort by operation count
|
|
527
527
|
entrydesk usage --json # JSON output
|
|
528
|
-
`)}async function Js(e){if(e.help){Xi();return}let t,o;try{let g=await fe();t=g.accessToken,o=g.workspaceId}catch(g){let
|
|
528
|
+
`)}async function Js(e){if(e.help){Xi();return}let t,o;try{let g=await fe();t=g.accessToken,o=g.workspaceId}catch(g){let m=g instanceof Error?g.message:"Authentication failed";console.error(m),process.exit(1)}let s=new B,n=[],i,r=0,a=100;do{let g=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...g.monthlyUsages),i=g.nextKey,r++,r>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
|
|
529
529
|
`);let l=0,d=0;for(let g of n)l+=parseFloat(g.totalCost),d+=g.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
|
|
530
|
-
`);let C=e.sortBy||"cost",k=[...n].toSorted((g,
|
|
531
|
-
`);for(let g of S){let
|
|
530
|
+
`);let C=e.sortBy||"cost",k=[...n].toSorted((g,m)=>C==="cost"?parseFloat(m.totalCost)-parseFloat(g.totalCost):m.operationCount-g.operationCount),b=e.limit&&e.limit>0?e.limit:k.length,S=k.slice(0,b);console.log(`Usage by User (sorted by ${C}, showing ${S.length} of ${n.length}):
|
|
531
|
+
`);for(let g of S){let m=parseFloat(g.totalCost);console.log(` ${g.user.name} (${g.user.email})`),console.log(` Cost: $${m.toFixed(2)}`),console.log(` Operations: ${g.operationCount.toLocaleString()}`),console.log("")}S.length<n.length&&console.log(`... and ${n.length-S.length} more users`)}function nn(){console.log("entrydesk 1.7.13")}function sn(){console.log(`
|
|
532
532
|
Usage: entrydesk workspaces [list|switch|use] [options]
|
|
533
533
|
|
|
534
534
|
Commands:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entrydesk/cli",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.13",
|
|
4
4
|
"description": "EntryDesk CLI - Interact with EntryDesk from your terminal",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"@lydell/node-pty": "^1.1.0",
|
|
27
27
|
"@testing-library/react": "^16.3.1",
|
|
28
28
|
"@types/archiver": "^7.0.0",
|
|
29
|
-
"@types/node": "^24.
|
|
29
|
+
"@types/node": "^24.12.0",
|
|
30
30
|
"@types/react": "^19.2.9",
|
|
31
31
|
"@vitest/coverage-v8": "^4.0.10",
|
|
32
32
|
"happy-dom": "^20.0.11",
|