@entrydesk/cli 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +149 -136
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as $e,b as Qe,c as dt,d as pe,e as
|
|
2
|
+
import{a as $e,b as Qe,c as dt,d as pe,e as Lt,f as xe,g as H,h as ne,i as Me,n as F}from"./chunk-J6ER4MMT.js";import{render as Xi}from"ink";function Io(){console.log(`
|
|
3
3
|
Usage: entrydesk agents [list|create|update|delete] [options]
|
|
4
4
|
|
|
5
5
|
Commands:
|
|
@@ -21,8 +21,8 @@ Create/Update Options:
|
|
|
21
21
|
|
|
22
22
|
Flags:
|
|
23
23
|
--json Output JSON
|
|
24
|
-
`)}function
|
|
25
|
-
`);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){xe(t)}}function
|
|
24
|
+
`)}function Ks(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function rn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),Io(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:Ks(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function an(e){try{if(e.help){Io();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new F;if(n==="create"){let a=rn(e),l=await i.createAgent(o,s,a);if(e.json){console.log(JSON.stringify(l));return}console.log(`Created agent: ${l.name}`),console.log(` ID: ${l.id}`);return}if(n==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let l=rn(e);await i.updateAgent(o,s,a,l),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),Io(),process.exit(1));let{agents:r}=await i.getAgents(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
|
|
25
|
+
`);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){xe(t)}}function qs(){console.log(`
|
|
26
26
|
Usage: entrydesk budget [get|set|clear] [options]
|
|
27
27
|
|
|
28
28
|
Commands:
|
|
@@ -32,7 +32,7 @@ Commands:
|
|
|
32
32
|
|
|
33
33
|
Flags:
|
|
34
34
|
--json Output JSON
|
|
35
|
-
`)}async function
|
|
35
|
+
`)}async function ln(e){try{if(e.help){qs();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new F;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){xe(t)}}import{render as Kr}from"ink";import{v4 as ho}from"uuid";import{exec as zs}from"child_process";import Ys from"fs";import et from"fs/promises";import cn from"os";import vo from"path";import{promisify as Xs}from"util";import{glob as Zs}from"glob";var Qs=Xs(zs),er=`## Filesystem Tool Instructions
|
|
36
36
|
|
|
37
37
|
You have access to filesystem tools that allow you to interact with the user's local filesystem.
|
|
38
38
|
|
|
@@ -56,24 +56,24 @@ You have access to filesystem tools that allow you to interact with the user's l
|
|
|
56
56
|
- Search results are limited to prevent overwhelming responses
|
|
57
57
|
- Execute Command has a default timeout of 30 seconds (max 5 minutes)
|
|
58
58
|
- The current working directory is: ${process.cwd()}
|
|
59
|
-
- The user's home directory is: ${
|
|
60
|
-
`,
|
|
59
|
+
- The user's home directory is: ${cn.homedir()}
|
|
60
|
+
`,tr=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function un(){return{name:"filesystem",systemPrompt:er,tools:tr}}function Ke(e){return e.startsWith("~/")?vo.join(cn.homedir(),e.slice(2)):e}function eo(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
|
|
61
61
|
|
|
62
|
-
... (truncated, ${e.length-t} more characters)`}async function
|
|
62
|
+
... (truncated, ${e.length-t} more characters)`}async function dn(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:eo(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]=eo(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(vo.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 Zs(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(vo.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(!Ys.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await Qs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:eo(i,5e4),stderr:eo(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function Po(e){return e.startsWith("filesystem__")}function fn(){return[un()]}function to(){return fn().flatMap(e=>e.tools)}function oo(){return fn().map(e=>e.systemPrompt).filter(Boolean).join(`
|
|
63
63
|
|
|
64
|
-
`)}function tt(e){return
|
|
65
|
-
`){t.push(s),s=[],
|
|
66
|
-
`,...m.slice(a)].join("");Y(L,a+1);return}if(P.return){
|
|
64
|
+
`)}function tt(e){return Po(e)}async function no(e,t){return Po(e)?dn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as K,useInput as Go}from"ink";import Ho from"ink-spinner";import{useCallback as Vo,useEffect as go,useRef as ss,useState as Fr}from"react";import{Box as so,Text as Dt}from"ink";import{jsx as ro,jsxs as Ot}from"react/jsx-runtime";function pn(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),b=Math.max(1,r),x=Math.floor(t/b)*b,C=Math.min(e.length,x+b),$=e.slice(x,C);return Ot(so,{flexDirection:"column",marginBottom:1,children:[ro(Dt,{bold:!0,color:"cyan",children:i}),ro(so,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:$.map((m,h)=>{let O=x+h===t,V=o?.has(m.id),Z=pn(m.name,d),ae=m.description?pn(m.description,Math.max(0,d-l)):"",Y=s?" ".repeat(l):"";return Ot(so,{paddingX:1,flexDirection:"column",children:[Ot(so,{children:[s&&ro(Dt,{color:V?"green":"gray",children:V?"[\u2713] ":"[ ] "}),ro(Dt,{backgroundColor:O?"cyan":void 0,color:O?"black":V?"green":"white",bold:!0,children:Z})]}),ae&&Ot(Dt,{dimColor:!0,children:[Y,"\xB7 ",ae]})]},m.id)})}),Ot(Dt,{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>b?` \xB7 Showing ${x+1}-${C} of ${e.length}`:""]})]})}import{Box as Ao,Text as Rt}from"ink";import{jsx as Ut,jsxs as No}from"react/jsx-runtime";function gn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:No(Ao,{flexDirection:"column",marginBottom:1,children:[Ut(Ao,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return No(Ao,{paddingX:1,children:[No(Rt,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),Ut(Rt,{dimColor:!0,children:r}),Ut(Rt,{children:" - "}),Ut(Rt,{color:i?"white":"gray",children:s.description})]},s.name)})}),Ut(Rt,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as or,Text as hn,useInput as nr,useStdout as sr}from"ink";import{useCallback as yn,useEffect as wn,useMemo as Eo,useRef as kn,useState as xn}from"react";import{jsx as Do}from"react/jsx-runtime";function io(e,t){return e<0?0:e>t?t:e}function _o(e){return Array.from(e)}function ao(e){return/\s/.test(e)}function Lo(e,t){let o=t;for(;o>0&&ao(e[o-1]??"");)o-=1;for(;o>0&&!ao(e[o-1]??"");)o-=1;return o}function bn(e,t){let o=t;for(;o<e.length&&ao(e[o]??"");)o+=1;for(;o<e.length&&!ao(e[o]??"");)o+=1;return o}function rr(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 Cn(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 ir=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=xn(()=>_o(e).length),d=kn(null),[b,x]=xn(0),C=kn(null),{stdout:$}=sr(),m=Eo(()=>_o(e),[e]),{lines:h,lineStarts:T,lineLengths:O}=Eo(()=>rr(m),[m]),{row:V,col:Z}=Eo(()=>Cn(a,T,O),[a,T,O]),ae=Math.max(1,($?.columns??80)-i);wn(()=>{d.current!==e?(l(m.length),C.current=null):l(j=>io(j,m.length)),d.current=e},[e,m.length]),wn(()=>{x(j=>{let P=j;Z<P?P=Z:Z>=P+ae&&(P=Z-ae+1);let E=O[V]??0,R=Z===E?E+1:E,W=Math.max(0,R-ae);return P>W&&(P=W),P<0&&(P=0),P})},[ae,Z,V,O]);let Y=yn((j,P)=>{d.current=j,t(j),l(P),C.current=null},[t]),Se=yn(async(j,P)=>{if(!n)return;let{row:E,col:R}=Cn(a,T,O),W=h[E]??[],_=O[E]??0,he=h.length>1;if(r&&(P.meta&&P.return||P.ctrl&&j==="j"||P.shift&&P.return)){let L=[...m.slice(0,a),`
|
|
66
|
+
`,...m.slice(a)].join("");Y(L,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&E>0?l(T[E]-1):l(T[E]+Lo(W,R)),C.current=null):(R===0&&E>0?l(T[E]-1):l(L=>io(L-1,m.length)),C.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),C.current=null):(R>=_&&E<h.length-1?l(T[E+1]):l(L=>io(L+1,m.length)),C.current=null);return}if(r&&he&&P.upArrow){let L=C.current??R,p=Math.max(0,E-1),ie=Math.min(L,O[p]??0);l((T[p]??0)+ie),C.current=L;return}if(r&&he&&P.downArrow){let L=C.current??R,p=Math.min(h.length-1,E+1),ie=Math.min(L,O[p]??0);l((T[p]??0)+ie),C.current=L;return}if(P.ctrl){if(j==="a"){l(T[E]??0),C.current=null;return}if(j==="e"){l((T[E]??0)+_),C.current=null;return}if(j==="u"){if(R>0){let L=T[E]??0,p=[...m.slice(0,L),...m.slice(a)].join("");Y(p,L)}return}if(j==="k"){if(R<_){let L=(T[E]??0)+_,p=[...m.slice(0,a),...m.slice(L)].join("");Y(p,a)}return}if(j==="w"){if(R===0&&E>0){let p=[...m.slice(0,a-1),...m.slice(a)].join("");Y(p,a-1);return}let L=Lo(W,R);if(L!==R){let p=(T[E]??0)+L,ie=[...m.slice(0,p),...m.slice(a)].join("");Y(ie,p)}return}if(j==="d"){if(a<m.length){let L=[...m.slice(0,a),...m.slice(a+1)].join("");Y(L,a)}return}return}if(P.meta){j==="b"?(R===0&&E>0?l(T[E]-1):l(T[E]+Lo(W,R)),C.current=null):j==="f"&&(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),C.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let L=[...m.slice(0,a-1),...m.slice(a)].join("");Y(L,a-1);return}if(!(P.tab||P.escape)&&j.length>0){let L=r?j.replace(/\r\n/g,`
|
|
67
67
|
`).replace(/\r/g,`
|
|
68
|
-
`):j.replace(/\r?\n/g,"");if(!L||(L=L.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!L))return;if((L.length>=
|
|
69
|
-
`))&&s){let q=!1,A={text:L,preventDefault:()=>{q=!0}};if(await Promise.resolve(s(A)),q)return}let ie=
|
|
70
|
-
`);return we(qe,{paddingLeft:
|
|
68
|
+
`):j.replace(/\r?\n/g,"");if(!L||(L=L.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!L))return;if((L.length>=ir||L.includes(`
|
|
69
|
+
`))&&s){let q=!1,A={text:L,preventDefault:()=>{q=!0}};if(await Promise.resolve(s(A)),q)return}let ie=_o(L),ke=[...m.slice(0,a),...ie,...m.slice(a)].join("");Y(ke,a+ie.length)}},[m,a,n,O,T,h,r,s,o,Y,e]);return nr(Se,{isActive:n}),Do(or,{flexDirection:"column",children:h.map((j,P)=>{let E=P===V,W=(E&&Z===j.length?[...j," "]:j).slice(b,b+ae),_=W.join("");if(!E)return Do(hn,{children:_||" "},P);let he=io(Z-b,Math.max(0,W.length-1)),L=W.slice(0,he).join(""),p=W[he]??" ",ie=W.slice(he+1).join(""),A=`${L}\x1B[7m${p}\x1B[27m${ie}`;return Do(hn,{children:A},P)})})}import{Box as qe,Text as ft}from"ink";import jo from"react";import{Text as Fe}from"ink";import ar from"react";import{Fragment as ur,jsx as Je,jsxs as In}from"react/jsx-runtime";var Oo=2,Ro=1,Uo=2,lr=1,Sn=3,Tn=4,cr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Je(Fe,{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(Fe,{color:n,children:e.slice(r,l.index)},`t-${r}`));let d=l[0],b=null,x=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Oo*2)b=Je(Fe,{bold:!0,color:n,children:d.slice(Oo,-Oo)},x);else if(d.length>Ro*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)))b=Je(Fe,{italic:!0,color:n,children:d.slice(Ro,-Ro)},x);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Uo*2)b=Je(Fe,{strikethrough:!0,color:n,children:d.slice(Uo,-Uo)},x);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>lr){let C=d.match(/^(`+)(.+?)\1$/s);C&&C[2]&&(b=Je(Fe,{color:s,children:C[2]},x))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let C=d.match(/\[(.*?)\]\((.*?)\)/);if(C){let $=C[1],m=C[2];b=In(Fe,{color:n,children:[$,In(Fe,{color:o,children:[" (",m,")"]})]},x)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Sn+Tn-1?b=Je(Fe,{underline:!0,color:n,children:d.slice(Sn,-Tn)},x):d.match(/^https?:\/\//)&&(b=Je(Fe,{color:o,children:d},x))}catch{b=null}i.push(b??Je(Fe,{color:n,children:d},x)),r=a.lastIndex}return r<e.length&&i.push(Je(Fe,{color:n,children:e.slice(r)},`t-${r}`)),Je(ur,{children:i.filter(d=>d!==null)})},jt=ar.memo(cr);import{Fragment as yr,jsx as we,jsxs as Nn}from"react/jsx-runtime";var dr=1,An=1,fr=1,pr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return we(qe,{paddingLeft:An,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=[],b=!1,x=!0,C=[],$="";function m(h){h&&(d.push(h),x=!1)}return o.forEach((h,T)=>{let O=`line-${T}`;if(b){let P=h.match(n);P&&P[1].startsWith($[0])&&P[1].length>=$.length?(m(we(vn,{content:C},O)),b=!1,C=[],$=""):C.push(h);return}let V=h.match(n),Z=h.match(s),ae=h.match(i),Y=h.match(r),Se=h.match(a),j=h.match(l);if(V)b=!0,$=V[1];else if(Se)m(we(qe,{children:we(ft,{dimColor:!0,children:"---"})},O));else if(Z){let P=Z[1].length,E=Z[2],R=P<=2?"cyan":"blue";m(we(qe,{children:we(ft,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:we(jt,{text:E,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},O))}else if(j){let P=j[1];m(we(qe,{paddingLeft:1,children:Nn(ft,{dimColor:!0,children:["> ",we(jt,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},O))}else if(ae){let P=ae[1],E=ae[2],R=ae[3];m(we(Pn,{itemText:R,type:"ul",marker:E,leadingWhitespace:P},O))}else if(Y){let P=Y[1],E=Y[2],R=Y[3];m(we(Pn,{itemText:R,type:"ol",marker:E,leadingWhitespace:P},O))}else h.trim().length===0?x||(d.push(we(qe,{height:dr},`spacer-${T}`)),x=!0):m(we(qe,{children:we(ft,{wrap:"wrap",children:we(jt,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},O))}),b&&m(we(vn,{content:C},"line-eof")),we(yr,{children:d})},gr=({content:e})=>{let t=e.join(`
|
|
70
|
+
`);return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},vn=jo.memo(gr),hr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return Nn(qe,{paddingLeft:r+fr,flexDirection:"row",children:[we(qe,{width:i,children:we(ft,{children:n})}),we(qe,{flexGrow:pr,children:we(ft,{wrap:"wrap",children:we(jt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Pn=jo.memo(hr),Fo=jo.memo(mr);import{execFile as wr}from"child_process";import kr from"fs";import St from"fs/promises";import En from"os";import co from"path";import{promisify as xr}from"util";var lo=xr(wr);async function br(){let e=co.join(En.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
|
|
73
73
|
set eof fileRef to 0
|
|
74
74
|
write imageData to fileRef
|
|
75
75
|
close access fileRef
|
|
76
|
-
`;return await
|
|
76
|
+
`;return await lo("osascript",["-e",t]),(await St.stat(e)).size===0?void 0:{buffer:await St.readFile(e),mime:"image/png"}}catch{return}finally{try{kr.existsSync(e)&&await St.unlink(e)}catch{}}}async function Cr(){try{let e=`
|
|
77
77
|
Add-Type -AssemblyName System.Windows.Forms
|
|
78
78
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
79
79
|
if ($img) {
|
|
@@ -81,44 +81,44 @@ 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
|
|
85
|
-
`);return
|
|
86
|
-
${s.text}${re}`):
|
|
87
|
-
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let
|
|
88
|
-
`))}return
|
|
89
|
-
|
|
90
|
-
`).trim()}var
|
|
91
|
-
|
|
92
|
-
${ve}\u250C\u2500 Tool: ${s}${re}`;if(
|
|
93
|
-
${
|
|
94
|
-
${Tt}\u2502 Output: ${i}${re}`}else if(
|
|
95
|
-
${ve}\u2502${re} (executing... ${r}s)`}else
|
|
96
|
-
${ve}\u2502${re} (preparing...)`);t.push(
|
|
97
|
-
|
|
98
|
-
${ve}\u250C\u2500 Tool: ${
|
|
99
|
-
${
|
|
84
|
+
`,{stdout:t}=await lo("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 lo("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 lo("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 _n(){let e=En.platform();if(e==="darwin")return br();if(e==="win32")return Cr();if(e==="linux")return $r()}var Sr=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 Ln(e){let t=co.extname(e).toLowerCase();return Sr.has(t)}function Tr(e){let t=co.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 uo(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 Dn(e){let t=uo(e);if(/^https?:\/\//.test(t))return!1;try{return await St.access(t),!0}catch{return!1}}async function On(e){let t=uo(e);try{if(!(await St.stat(t)).isFile())return;let s=await St.readFile(t),n=Tr(t),i=co.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Be="\x1B[2m",re="\x1B[0m",ve="\x1B[36m",Tt="\x1B[32m",Rn="\x1B[31m",gt="\x1B[38;2;59;91;204m",Bo="\x1B[38;2;126;200;248m",Wo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as Un}from"uuid";function jn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||Un()),[b,x]=ot(t),[C,$]=ot(!!e),[m,h]=ot(null),[T,O]=ot(""),[V,Z]=ot(!1),ae=Se=>{i(j=>[...j,{role:"system",content:Se}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:l,setChatId:d,currentChatTitle:b,setCurrentChatTitle:x,hasPersistedChat:C,setHasPersistedChat:$,credentials:m,setCredentials:h,currentResponse:T,setCurrentResponse:O,fullOutput:V,setFullOutput:Z,addSystemMessage:ae,startNewChat:Se=>{let j=Un();d(j),x(void 0),$(!1),i([]),Se&&ae(Se)}}}import{useEffect as Ir,useState as Fn}from"react";function Bn(e){let[t,o]=Fn(null),[s,n]=Fn(!0);return Ir(()=>{let i=!1;async function r(){try{let a=await pe();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 vr,useState as Ft}from"react";function Wn(e){let[t,o]=Ft([]),[s,n]=Ft([]),[i,r]=Ft([]),[a,l]=Ft([]),[d,b]=Ft(!1);return vr(()=>{if(!e)return;let x=!1;b(!0);async function C(){if(e)try{let $=new F,[m,h,T,O]=await Promise.all([$.getConnectors(e.accessToken,e.workspaceId),$.getModels(e.accessToken,e.workspaceId),$.getAgents(e.accessToken,e.workspaceId),$.getModelProviders(e.accessToken,e.workspaceId)]);if(x)return;o(m.connectors),n(h.models),r(T.agents),l(O.providers??[])}catch{}finally{x||b(!1)}}return C(),()=>{x=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import mo from"fs";import Jn from"path";import{useCallback as Pr}from"react";import{v4 as Ar}from"uuid";function Mn(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
|
+
`);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(`${Be}[Thinking]
|
|
86
|
+
${s.text}${re}`):o.push(`${Be}[Thinking...]${re}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${ve}\u250C\u2500 Tool: ${s.toolName}${re}`),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(`${Be}\u2502 Args: ${r}${re}`)}s.result!==void 0?(n.push(`${Tt}\u2502 Result: ${Mn(s.result,t)}${re}`),n.push(`${ve}\u2514\u2500 completed${re}`)):n.push(`${ve}\u2514\u2500${re}`),o.push(n.join(`
|
|
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}${re}`),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(`${Be}\u2502 Input: ${a}${re}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Tt}\u2502 Output: ${Mn(s.output,t)}${re}`),i.push(`${ve}\u2514\u2500 completed${re}`)):s.state==="error"?i.push(`${ve}\u2514\u2500 failed${re}`):i.push(`${ve}\u2514\u2500${re}`),o.push(i.join(`
|
|
88
|
+
`))}return o.join(`
|
|
89
|
+
|
|
90
|
+
`).trim()}var fo=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let s=o.toolName.replace(/__/g," "),n=`
|
|
91
|
+
|
|
92
|
+
${ve}\u250C\u2500 Tool: ${s}${re}`;if(o.args){let i=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
|
|
93
|
+
${Be}\u2502 Input: ${i}${re}`}if(o.output){let i=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
|
|
94
|
+
${Tt}\u2502 Output: ${i}${re}`}else if(o.status==="executing"){let i=o.startedAt??Date.now(),r=Math.floor((Date.now()-i)/1e3);n+=`
|
|
95
|
+
${ve}\u2502${re} (executing... ${r}s)`}else o.status==="preparing"&&(n+=`
|
|
96
|
+
${ve}\u2502${re} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,s]of this.pendingToolCalls){let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
|
|
97
|
+
|
|
98
|
+
${ve}\u250C\u2500 Tool: ${n}${re}`,i&&(t+=`
|
|
99
|
+
${Be}\u2502 Input: ${i}${re}`),t+=`
|
|
100
100
|
${ve}\u2514\u2500 completed${re}
|
|
101
|
-
`,this.pendingToolCalls.delete(
|
|
101
|
+
`,this.pendingToolCalls.delete(o)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.args=(o.args||"")+t.inputTextDelta,o.status="executing",o.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output="",o.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output=(o.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,o){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"",r=(s.output||"").length>200?(s.output||"").slice(0,200)+"...":s.output||"";return o+=`
|
|
102
102
|
|
|
103
|
-
${ve}\u250C\u2500 Tool: ${
|
|
104
|
-
${
|
|
105
|
-
${Tt}\u2502 Output: ${r}${re}`,
|
|
103
|
+
${ve}\u250C\u2500 Tool: ${n}${re}`,i&&(o+=`
|
|
104
|
+
${Be}\u2502 Input: ${i}${re}`),o+=`
|
|
105
|
+
${Tt}\u2502 Output: ${r}${re}`,o+=`
|
|
106
106
|
${ve}\u2514\u2500 completed${re}
|
|
107
|
-
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:
|
|
107
|
+
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),i=t.errorText||"Unknown error",r=i.length>200?i.slice(0,200)+"...":i;return o+=`
|
|
108
108
|
|
|
109
|
-
${ve}\u250C\u2500 Tool: ${
|
|
110
|
-
${
|
|
109
|
+
${ve}\u250C\u2500 Tool: ${n}${re}`,o+=`
|
|
110
|
+
${Rn}\u2502 Error: ${r}${re}`,o+=`
|
|
111
111
|
${ve}\u2514\u2500 failed${re}
|
|
112
|
-
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:
|
|
112
|
+
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Mo=Jn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function le(e,t){let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
|
|
113
113
|
DATA: ${JSON.stringify(t,null,2)}`),s+=`
|
|
114
|
-
`;try{
|
|
115
|
-
`)}catch{}}function
|
|
116
|
-
`);ke=D.pop()||"";for(let f of D)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(le(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":te=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta
|
|
117
|
-
${A}`)),w.providerMetadata?.anthropic?.signature&&(ee=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let
|
|
118
|
-
[Executing ${w.toolName} locally...]`)}else le("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
|
|
119
|
-
`);fe.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:oe,isError:f.isError})}}if(le("=== Sending clientToolResults for continuation ===",{toolResultsCount:
|
|
120
|
-
`);ke=
|
|
121
|
-
${A}`)),U.providerMetadata?.anthropic?.signature&&(ee=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Ce={type:"reasoning",id:te,text:A,state:"done"};ee&&(Ce.providerMetadata={anthropic:{signature:ee}}),z.push(Ce),le("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee=""
|
|
114
|
+
`;try{mo.appendFileSync(Mo,s)}catch{}}function Nr(){try{let e=Jn.dirname(Mo);mo.existsSync(e)||mo.mkdirSync(e,{recursive:!0}),mo.writeFileSync(Mo,`=== Debug session started at ${new Date().toISOString()} ===
|
|
115
|
+
`)}catch{}}function po(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Gn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:b,setMessages:x,setState:C,setCurrentResponse:$,setCredentials:m,setHasPersistedChat:h,getFileIds:T,clearFiles:O}){let V=d?to():void 0,Z=d?oo():void 0;return{sendMessage:Pr(async(Y,Se,j)=>{Nr(),le("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:V?.length});let P=Se||t?.accessToken,E=j||t?.workspaceId;if(!P||!E)try{let _=await pe();P=_.accessToken,E=_.workspaceId,m(_)}catch(_){if(_ instanceof Qe){if(_.code==="not-logged-in"){C({status:"not-logged-in"});return}if(_.code==="no-workspace"){C({status:"no-workspace"});return}}let he=_ instanceof Error?_.message:"Authentication failed";C({status:"error",message:he});return}else try{let _=await dt();_!==P&&(P=_,m({accessToken:_,workspaceId:E}))}catch(_){if(_ instanceof Qe&&_.code==="not-logged-in"){C({status:"not-logged-in"});return}let he=_ instanceof Error?_.message:"Authentication failed";C({status:"error",message:he});return}x(_=>[..._,{role:"user",content:Y}]),C({status:"sending"}),$("");let R=null,W=null;try{let _=new F,he=T?.()??[],L={id:e,message:{id:Ar(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};he.length>0&&(L.fileIds=he),o?L.agentId=o:(s&&(L.model=s),L.connectorIds=n??[],L.enableSandbox=i,L.enableWebSearch=r,L.enableImageGeneration=a,L.enableChart=l),V&&(L.clientTools=V),Z&&(L.clientToolSystemPrompt=Z);let p=await _.chat(P,E,L);if(!p.ok){let B=await p.text();throw new Error(`API error ${p.status}: ${B}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let ie=new TextDecoder,ke="",q="",A="",te="",ee="",me="",ce="",M=new fo,Q=[],z=[],fe=[],Te=()=>{let B=M.hasExecuting();B&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}$(q+M.buildToolDisplay())},1e3):!B&&W&&(clearInterval(W),W=null)};for(;;){let{done:B,value:se}=await R.read();if(B)break;ke+=ie.decode(se,{stream:!0});let D=ke.split(`
|
|
116
|
+
`);ke=D.pop()||"";for(let f of D)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(le(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":te=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,$(`${Be}[Thinking...]${re}
|
|
117
|
+
${A}`)),w.providerMetadata?.anthropic?.signature&&(ee=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let I={type:"reasoning",id:te,text:A,state:"done"};ee&&(I.providerMetadata={anthropic:{signature:ee}}),z.push(I),le("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$("");break;case"text-delta":w.delta&&(M.hasPending()&&(q=M.flushPending(q)),q+=w.delta,me+=w.delta,$(q));break;case"tool-input-start":{let I=M.handleToolInputStart(w);I&&$(q+I),Te();break}case"tool-input-delta":{let I=M.handleToolInputDelta(w);I&&$(q+I),Te();break}case"tool-call":case"tool-input-available":{if(le(`=== 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 I=po(w.args??w.input);z.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:I}),le("Added tool to messageParts",{messagePartsCount:z.length})}if(d&&w.toolCallId&&w.toolName&&tt(w.toolName)){let I=po(w.args??w.input);Q.push({toolCallId:w.toolCallId,toolName:w.toolName,args:I}),le("Added to pendingClientTools",{pendingCount:Q.length,pendingClientTools:Q}),$(q+M.buildToolDisplay()+`
|
|
118
|
+
[Executing ${w.toolName} locally...]`)}else le("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 I=M.handleToolOutputStart(w);I&&$(q+I),Te();break}case"tool-output-delta":{let I=M.handleToolOutputDelta(w);I&&$(q+I),Te();break}case"tool-output-end":{let I=M.handleToolOutputEnd(w,q);I&&(q=I.fullResponse,$(q+I.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let I=M.handleToolError(w,q);I&&(q=I.fullResponse,$(q+I.toolDisplay)),Te();break}case"start":w.messageId&&(ce=w.messageId,le("Captured messageId from start event",{messageId:ce}));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(me){let B=z.findIndex(D=>D.type!=="reasoning"),se=B===-1?z.length:B;z.splice(se,0,{type:"text",text:me}),le("Added accumulated text to messageParts",{textLength:me.length,insertIndex:se})}for(le("=== Initial stream ended ===",{pendingClientToolsCount:Q.length,pendingClientTools:Q,messagePartsCount:z.length,messageParts:z.map(B=>({type:B.type,toolCallId:B.toolCallId,toolName:B.toolName}))});Q.length>0;){le("=== Starting pending tools execution loop ===",{pendingCount:Q.length});let B=[];for(let f of Q){le(`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)}),$(q+M.buildToolDisplay()),Te();let w=await no(f.toolName,f.args);le(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let I=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(B.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:I}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let oe=M.handleToolOutputEnd({toolCallId:f.toolCallId},q);oe&&(q=oe.fullResponse)}else{let oe=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},q);oe&&(q=oe.fullResponse)}$(q+M.buildToolDisplay()),Te()}Q.length=0;for(let f of B){let w=z.find(I=>(I.type==="tool-input-available"||I.type==="tool-call")&&I.toolCallId===f.toolCallId);if(w){let I=[];for(let U of f.content)U.type==="text"?I.push(U.text):U.type==="image"?I.push("[Image]"):U.type==="audio"?I.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&I.push("[Resource]");let oe=I.join(`
|
|
119
|
+
`);fe.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:oe,isError:f.isError})}}if(le("=== Sending clientToolResults for continuation ===",{toolResultsCount:B.length,toolResults:B.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let se={id:e,clientToolResults:B};o?se.agentId=o:(s&&(se.model=s),se.connectorIds=n??[],se.enableSandbox=i,se.enableWebSearch=r,se.enableImageGeneration=a,se.enableChart=l),V&&(se.clientTools=V),Z&&(se.clientToolSystemPrompt=Z),le("=== Sending continuation request ===",{chatId:e,hasAgentId:!!se.agentId,hasModel:!!se.model,clientToolResultsCount:B.length});let D=await _.chat(P,E,se);if(le("=== Continuation response received ===",{ok:D.ok,status:D.status}),!D.ok){let f=await D.text();throw new Error(`Continuation failed: ${D.status}: ${f}`)}if(!D.body)break;for(le("=== Processing continuation stream ==="),R=D.body.getReader(),z.length=0,me="",A="",te="",ee="";;){let{done:f,value:w}=await R.read();if(f){le("=== Continuation stream done ===");break}ke+=ie.decode(w,{stream:!0});let I=ke.split(`
|
|
120
|
+
`);ke=I.pop()||"";for(let oe of I)if(oe.trim()!=="data: [DONE]"&&oe.startsWith("data: "))try{let U=JSON.parse(oe.slice(6));switch(le(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":te=U.id||"0",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,$(`${Be}[Thinking...]${re}
|
|
121
|
+
${A}`)),U.providerMetadata?.anthropic?.signature&&(ee=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Ce={type:"reasoning",id:te,text:A,state:"done"};ee&&(Ce.providerMetadata={anthropic:{signature:ee}}),z.push(Ce),le("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$(q);break;case"text-delta":U.delta&&(q+=U.delta,me+=U.delta,$(q));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Ce=po(U.args??U.input);z.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Ce})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Ce=po(U.args??U.input);Q.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Ce}),le("Continuation: Added to pendingClientTools",{pendingCount:Q.length})}break;case"finish":le("Continuation finish event",U);break}}catch{}}if(me){let f=z.findIndex(I=>I.type!=="reasoning"),w=f===-1?z.length:f;z.splice(w,0,{type:"text",text:me})}le("=== Continuation stream processing complete ===",{pendingClientToolsCount:Q.length,messagePartsCount:z.length,fullResponseLength:q.length})}if(d&&V&&V.length>0){let B=[];for(let D of fe)B.push({type:String(D.type),title:String(D.toolName).replace(/__/g," "),input:D.input,output:D.output,state:D.isError?"error":"output-available"});for(let D of z)D.type==="text"&&D.text&&B.push({type:"text",text:D.text});let se=ht(B,b);le("=== Using formatted parts for local tools ===",{executedToolsCount:fe.length,textPartsCount:z.filter(D=>D.type==="text").length,contentLength:se.length}),x(D=>[...D,{role:"assistant",content:se,parts:B}])}else{le("=== Fetching message from API ===",{fullResponseLength:q.length,fullResponsePreview:q.slice(0,200)});try{let{messages:B}=await _.getMessages(P,E,e,10);le("=== API messages received ===",{count:B.length,roles:B.map(D=>D.role)});let se=B.find(D=>D.role==="assistant");if(se){let D=se.parts,f=ht(D,b);le("=== Setting message from API ===",{partsCount:D.length,partTypes:D.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),x(w=>[...w,{role:"assistant",content:f,parts:D}])}else le("=== No assistant message found, using fallback ==="),x(D=>[...D,{role:"assistant",content:q}])}catch(B){le("=== API fetch failed, using fallback ===",{error:B instanceof Error?B.message:String(B)}),x(se=>[...se,{role:"assistant",content:q}])}}le("=== Message handling complete ==="),$(""),C({status:"ready"}),h(!0),he.length>0&&O?.()}catch(_){le("=== ERROR ===",{message:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0});let he=_ instanceof Error?_.message:"Failed to send message";C({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,V,Z,b,x,C,$,m,h,T,O])}}import{useState as Bt}from"react";var Hn={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"}},Vn=new Map(Object.values(Hn).map(e=>[e.apiKey,e.name]));function Kn(){return Object.values(Hn)}function qn(e,t,o,s,n){let[i,r]=Bt(e),[a,l]=Bt(t),[d,b]=Bt(o),[x,C]=Bt(s),[$,m]=Bt(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:b,chart:x,setChart:C,fileSystem:$,setFileSystem:m,capabilityLabelMap:Vn}}import{useEffect as Er,useState as _r}from"react";function zn(e,t){let[o,s]=_r(null);return Er(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new F().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Jo}from"react";function Yn(e,t,o){let[s,n]=Jo(e),[i,r]=Jo(t),[a,l]=Jo(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Dr,useInput as Or}from"ink";import{useCallback as nt,useRef as Rr,useState as De}from"react";import{spawn as Lr}from"child_process";function Xn(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=Lr(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Zn=[{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 Qn(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Zn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Zn}function es(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 ts=`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,97 +142,97 @@ 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
|
|
145
|
+
Ctrl+C Exit`;function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:b,setCurrentAgentDetails:x,activeConnectorIds:C,setActiveConnectorIds:$,sandbox:m,setSandbox:h,webSearch:T,setWebSearch:O,imageGeneration:V,setImageGeneration:Z,chart:ae,setChart:Y,fileSystem:Se,setFileSystem:j,availableModels:P,availableAgents:E,availableConnectors:R,messages:W,hasPersistedChat:_,setHasPersistedChat:he,setMessages:L,addSystemMessage:p,startNewChat:ie,sendMessage:ke,setFullOutput:q,credentials:A,setCredentials:te,setState:ee,defaultCapabilities:me,capabilityLabelMap:ce,hasUploadingFiles:M=!1}){let{exit:Q}=Dr(),[z,fe]=De([]),[Te,B]=De(0),[se,D]=De(!1),[f,w]=De(null),[I,oe]=De([]),[U,Ce]=De(0),[rt,it]=De(new Set),[Re,at]=De(new Set),[$o,zt]=De([]),[We,wt]=De([]),[Ye,Yt]=De([]),[lt,So]=De([]),[Ve,Xe]=De(null),[Xt,kt]=De(""),mt=Rr(!1),[ct,xt]=De(!1),bt=nt(async()=>{if(!A)return[];let v=new F,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 F,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 Yt(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}));oe(y);let c=r?y.findIndex(u=>u.id===r):-1;Ce(c>=0?c:0),w("model")}else if(v==="agent"){if(E.length===0){p("No agents available.");return}let y=E.map(u=>({id:u.id,name:u.name,description:u.description}));oe(y);let c=l?y.findIndex(u=>u.id===l):-1;Ce(c>=0?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}));oe(c),Ce(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"}`}));oe(c),Ce(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}));oe(y),Ce(0),it(new Set(C||[])),w("connectors")}else if(v==="capabilities"){let y=Kn().map(u=>({id:u.id,name:u.name,description:u.description}));oe(y),Ce(0);let c=new Set;m&&c.add("sandbox"),T&&c.add("webSearch"),V&&c.add("imageGeneration"),ae&&c.add("chart"),Se&&c.add("fileSystem"),at(c),w("capabilities")}else if(v==="chats"){if(!A){p("Not authenticated.");return}try{let y=new F,{chats:c}=await y.getChats(A.accessToken,A.workspaceId,20);if(c.length===0){p("No chats available.");return}zt(c);let u=c.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));oe(u);let g=u.findIndex(S=>S.id===o);Ce(g>=0?g:0),w("chats")}catch{p("Failed to load chats.")}}else if(v==="profile"){let y=H.getProfileNames(),c=H.getCurrentProfileName(),u=y.map(S=>({id:S,name:S,description:S===c?"(current)":void 0}));oe(u);let g=u.findIndex(S=>S.id===c);Ce(g>=0?g:0),w("profile")}D(!1),fe([])},[P,E,We,Ye,R,C,r,l,bt,Ct,m,T,V,ae,Se,A,o,p]),ye=nt(v=>{let y=ne.getAll(v);a(y.model?.default),d(void 0),x(null);let c=y.connectors?.defaults;$(c&&c.length>0?c:void 0);let u=y.capabilities;h(u?.sandbox??me.sandbox),O(u?.webSearch??me.webSearch),Z(u?.imageGeneration??me.imageGeneration),Y(u?.chart??me.chart);let g=y.localTools;j(g?.fileSystem??me.fileSystem)},[a,d,x,$,h,O,Z,Y,j,me]),Ze=nt(async()=>{try{let v=await pe();te({accessToken:v.accessToken,workspaceId:v.workspaceId}),ee({status:"ready"})}catch(v){if(te(null),v instanceof Qe){if(v.code==="not-logged-in"){ee({status:"not-logged-in"});return}if(v.code==="no-workspace"){ee({status:"no-workspace"});return}}let y=v instanceof Error?v.message:"Failed to authenticate";ee({status:"error",message:y})}},[te,ee]),$t=nt(async v=>{switch(v.type){case"help":return p(ts),!0;case"clear":return ie("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?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id);else{let u=P.map(g=>g.name).join(", ");p(`Model "${v.value}" not found.
|
|
146
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 E.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=v.value.toLowerCase(),c=E.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=E.map(g=>g.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?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let g=u.find(
|
|
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 g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));p(g?`Skill: ${g.name}
|
|
148
148
|
${g.description}
|
|
149
149
|
Provider: ${g.provider}
|
|
150
150
|
Author: ${g.author.name}
|
|
151
|
-
ID: ${g.id}`:`Skill "${v.value}" not found.`)}),!0}case"schedules":{if(!v.value)return _e("schedules"),!0;let y=v.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let g=u.find(
|
|
151
|
+
ID: ${g.id}`:`Skill "${v.value}" not found.`)}),!0}case"schedules":{if(!v.value)return _e("schedules"),!0;let y=v.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
|
|
152
152
|
Agent: ${g.agent.name}
|
|
153
153
|
Status: ${g.isActive?"Active":"Paused"}
|
|
154
|
-
Repeat: ${
|
|
154
|
+
Repeat: ${S(g.config)}
|
|
155
155
|
Next Run: ${k}
|
|
156
|
-
ID: ${g.id}`)}else p(`Schedule "${v.value}" not found.`)}),!0}case"connectors":{if(l){let c=
|
|
156
|
+
ID: ${g.id}`)}else p(`Schedule "${v.value}" not found.`)}),!0}case"connectors":{if(l){let c=b?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(g=>` - ${g.name}`).join(`
|
|
157
157
|
`);p(`Agent connectors:
|
|
158
|
-
${u}`)}return!0}let y=R.filter(c=>
|
|
158
|
+
${u}`)}return!0}let y=R.filter(c=>C?.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=(
|
|
160
|
+
${c}`)}return!0}case"capabilities":{if(l){let u=(b?.capabilities||[]).map(g=>ce.get(g)??g);return p(u.length>0?`Agent capabilities:
|
|
161
161
|
${u.map(g=>` - ${g}`).join(`
|
|
162
|
-
`)}`:"No agent capabilities."),!0}let y=[];return m&&y.push("Sandbox"),
|
|
162
|
+
`)}`:"No agent capabilities."),!0}let y=[];return m&&y.push("Sandbox"),T&&y.push("Web Search"),V&&y.push("Image Generation"),ae&&y.push("Chart"),Se&&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(
|
|
165
|
-
ID: ${
|
|
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 F;if(!v.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let g=u.map(S=>` ${S.id===A.workspaceId?"* ":" "}${S.name}
|
|
165
|
+
ID: ${S.id}`);p(`Workspaces:
|
|
166
166
|
${g.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),g=u.find(k=>k.id===c);if(!g)return p(`Workspace not found: ${c}`),!0;let{TokenStorage
|
|
168
|
-
`))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=H.getCurrentProfileName(),c=r?P.find(k=>k.id===r)?.name||r:null,u=l?E.find(k=>k.id===l)?.name||l:null,g=
|
|
169
|
-
`))}).catch(()=>{let k=[`Profile: ${y}`,"Not logged in",_?`Chat ID: ${
|
|
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],g=y[2]
|
|
171
|
-
`)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let G=J(u,!0),ue=ne.getAll(G),Ue=await $e.getAll(G),Ie=!!Ue?.accessToken,ut=ue.capabilities?Object.entries(ue.capabilities).filter(([,
|
|
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),g=u.find(k=>k.id===c);if(!g)return p(`Workspace not found: ${c}`),!0;let{TokenStorage:S}=await import("./token-storage-JKKVPVG3.js");await S.saveWorkspaceId(c),p(`Switched to workspace: ${g.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 F;if(!v.value){try{let g=await y.getBudget(A.accessToken,A.workspaceId);g.budget===null?p("No budget set for this workspace."):p(`Current budget: $${g.budget}`)}catch(g){p(`Failed to get budget: ${g instanceof Error?g.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(g){p(`Failed to clear budget: ${g instanceof Error?g.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(g){p(`Failed to set budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let y=new F;try{let c=[],u,g=0,S=10;do{let Ie=await y.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...Ie.monthlyUsages),u=Ie.nextKey,g++,g>=S){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 k=0,N=0;for(let Ie of c)k+=parseFloat(Ie.totalCost),N+=Ie.operationCount;let J=[...c].toSorted((Ie,ut)=>parseFloat(ut.totalCost)-parseFloat(Ie.totalCost)),G=10,ue=J.slice(0,G),Ue=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${N.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ue.length} Users by Cost:`,...ue.map(Ie=>` ${Ie.user.name}: $${parseFloat(Ie.totalCost).toFixed(2)} (${Ie.operationCount.toLocaleString()} ops)`)];c.length>G&&(Ue.push("",`... and ${c.length-G} 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=H.getCurrentProfileName(),c=r?P.find(k=>k.id===r)?.name||r:null,u=l?E.find(k=>k.id===l)?.name||l:null,g=C?R.filter(k=>C.includes(k.id)).map(k=>k.name):[],S=[];return m&&S.push("Sandbox"),T&&S.push("Web Search"),V&&S.push("Image Gen"),ae&&S.push("Chart"),Se&&S.push("FileSystem"),$e.getEmail().then(k=>{let N=[`Profile: ${y}${y!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(N.join(`
|
|
169
|
+
`))}).catch(()=>{let k=[`Profile: ${y}`,"Not logged in",_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(k.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],g=y[2],S=H.getProfileNames(),k=H.getCurrentProfileName(),N=H.getOverrideProfile(),J=(G,ue=!1)=>{if(G)return G;if(ue&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let G=[`Profiles (${S.length}):`];for(let ue of S){let Ue=ue===k?" (current)":"";G.push(` ${ue}${Ue}`)}return p(G.join(`
|
|
171
|
+
`)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let G=J(u,!0),ue=ne.getAll(G),Ue=await $e.getAll(G),Ie=!!Ue?.accessToken,ut=ue.capabilities?Object.entries(ue.capabilities).filter(([,To])=>To).map(([To])=>To):[],Hs=ue.connectors?.defaults&&ue.connectors.defaults.length>0?ue.connectors.defaults.join(", "):"unset",Vs=[`Profile: ${G}${G===k?" (current)":""}`,`API URL: ${ue.apiUrl??"default"}`,`Hub URL: ${ue.hubUrl??"default"}`,`Model: ${ue.model?.default??"unset"}`,`Connectors: ${Hs}`,`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(Vs.join(`
|
|
172
172
|
`)),!0}if(c==="create"){let G=u||H.DEFAULT_PROFILE;return H.createProfile(G),p(`Profile created: ${G}`),!0}if(c==="use"||c==="switch"){let G=J(u,!0);return H.setOverrideProfile(G),H.setCurrentProfile(G),ye(G),await Ze(),ie(`Switched to profile: ${G} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let G=J(u,!0),ue=G===k,Ue=H.deleteProfile(G),Ie=`Profile deleted: ${G}`;if(ue)H.setOverrideProfile(Ue.currentProfile),ye(Ue.currentProfile),await Ze(),ie(`${Ie}
|
|
173
173
|
Switched to profile: ${Ue.currentProfile} (new chat)`);else if(N===G){let ut=H.getCurrentProfileName();H.setOverrideProfile(ut),ye(ut),await Ze(),ie(`${Ie}
|
|
174
|
-
Switched to profile: ${ut} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let G=J(u,!0);if(!g)throw new Error("New profile name is required.");let ue=H.renameProfile(G,g);return p(`Profile renamed: ${G} -> ${g}`),N===G?(H.setOverrideProfile(g),ye(g)):ue.currentProfile===g&&ye(g),!0}if(c==="clone"||c==="copy"){let G=J(u,!0);if(!g)throw new Error("Target profile name is required.");let ue=ne.getAll(G);return H.createProfile(g),ne.setAll(ue,g),await $e.clear(g),p(`Profile cloned: ${G} -> ${g}`),!0}p(`Unknown profile command: ${c}`)}catch(G){let ue=G instanceof Error?G.message:"Unknown error";p(`Profile error: ${ue}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=_||W.some(k=>k.role!=="system")?`/chat/${
|
|
175
|
-
URL: ${
|
|
176
|
-
Type /help for available commands.`),!0;default:return!1}},[p,P,E,R,We,Ye,r,l,
|
|
174
|
+
Switched to profile: ${ut} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let G=J(u,!0);if(!g)throw new Error("New profile name is required.");let ue=H.renameProfile(G,g);return p(`Profile renamed: ${G} -> ${g}`),N===G?(H.setOverrideProfile(g),ye(g)):ue.currentProfile===g&&ye(g),!0}if(c==="clone"||c==="copy"){let G=J(u,!0);if(!g)throw new Error("Target profile name is required.");let ue=ne.getAll(G);return H.createProfile(g),ne.setAll(ue,g),await $e.clear(g),p(`Profile cloned: ${G} -> ${g}`),!0}p(`Unknown profile command: ${c}`)}catch(G){let ue=G instanceof Error?G.message:"Unknown error";p(`Profile error: ${ue}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=_||W.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",g=l?`?agentId=${encodeURIComponent(l)}`:"",S=`${y}${u}${g}`;try{await Xn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
|
|
175
|
+
URL: ${S}`)}return!0}case"share":{if(!A)return p("Not authenticated."),!0;if(!(_||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new F().createChatShare(A.accessToken,A.workspaceId,o,"public"),S=`${Me().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${S}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return A?_?(xt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Q(),!0;case"unknown":return p(`Unknown command: ${v.input}
|
|
176
|
+
Type /help for available commands.`),!0;default:return!1}},[p,P,E,R,We,Ye,r,l,C,m,T,V,ae,Se,o,n,Q,_e,ie,ce,b,_,W,bt,Ct,L,a,d,x,a,ye,Ze]),Zt=nt(v=>{if(mt.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),oe([])),v.startsWith("/")&&!v.includes(" ")){let y=Qn(v);fe(y),B(0),D(y.length>0)}else D(!1),fe([])},[f,Ve,ct,t]),_t=nt((v,y=!1)=>{if(v>=0&&v<z.length){let c=z[v];D(!1),fe([]),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(""),$t({type:c.name})):t(`/${c.name}`)}},[z,_e,t,$t]),Qt=nt(async v=>{mt.current=!1;let y=v.trim();if(!y||ct)return;if(f==="model"&&I.length>0){let u=I[U];u&&(l?ie(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),x(null)),w(null),oe([]),t("");return}if(f==="agent"&&I.length>0){let u=I[U];u&&(u.id!==l?ie(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),oe([]),t("");return}if(f==="skills"&&I.length>0){let u=I[U];if(u){let g=We.find(S=>S.id===u.id);g&&p(`Skill: ${g.name}
|
|
177
177
|
${g.description}
|
|
178
178
|
Provider: ${g.provider}
|
|
179
179
|
Author: ${g.author.name}
|
|
180
|
-
ID: ${g.id}`)}w(null),oe([]),t("");return}if(f==="schedules"&&
|
|
180
|
+
ID: ${g.id}`)}w(null),oe([]),t("");return}if(f==="schedules"&&I.length>0){let u=I[U];if(u){let g=Ye.find(S=>S.id===u.id);if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
|
|
181
181
|
Agent: ${g.agent.name}
|
|
182
182
|
Status: ${g.isActive?"Active":"Paused"}
|
|
183
|
-
Repeat: ${
|
|
183
|
+
Repeat: ${S(g.config)}
|
|
184
184
|
Next Run: ${k}
|
|
185
|
-
ID: ${g.id}`)}}w(null),oe([]),t("");return}if(f==="connectors"){let u=Array.from(rt)
|
|
185
|
+
ID: ${g.id}`)}}w(null),oe([]),t("");return}if(f==="connectors"){let u=Array.from(rt);$(u.length>0?u:void 0),ne.setDefaultConnectorIds(u);let g=R.filter(S=>rt.has(S.id)).map(S=>S.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),oe([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),g=Re.has("webSearch"),S=Re.has("imageGeneration"),k=Re.has("chart"),N=Re.has("fileSystem");h(u),O(g),Z(S),Y(k),j(N),ne.setCapabilities({sandbox:u,webSearch:g,imageGeneration:S,chart:k}),ne.setLocalTools({fileSystem:N});let J=[];u&&J.push("Sandbox"),g&&J.push("Web Search"),S&&J.push("Image Generation"),k&&J.push("Chart"),N&&J.push("FileSystem"),p(J.length>0?`Active capabilities: ${J.join(", ")}`:"All capabilities disabled."),w(null),oe([]),t("");return}if(f==="profile"&&I.length>0){let u=I[U];if(u){let g=H.getCurrentProfileName();u.id!==g?(H.setOverrideProfile(u.id),H.setCurrentProfile(u.id),ye(u.id),Ze(),ie(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),oe([]),t("");return}if(se&&z.length>0){_t(Te,!0);return}Xe(null),kt(""),So(u=>u.length>0&&u[u.length-1]===y?u:[...u,y]);let c=es(y);if(c){await $t(c),t(""),D(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),D(!1),ke(y)},[ke,$t,se,z,Te,_t,f,I,U,rt,Re,R,We,Ye,p,t,l,ie,a,d,x,$,h,O,Z,Y,j,M,ye,Ze,ct,A,_,o]);return Or((v,y)=>{if(y.ctrl&&v==="c"){if(e.length>0){Zt(""),mt.current=!0,p("Press Ctrl+C again to exit.");return}if(mt.current){Q();return}Q();return}if(y.ctrl&&v==="o"){q(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&&_&&new F().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&I.length>0){if(y.upArrow){Ce(c=>c<=0?I.length-1:c-1);return}if(y.downArrow){Ce(c=>c>=I.length-1?0:c+1);return}if(y.escape){w(null),oe([]),t("");return}if(y.return){if(f==="model"){let c=I[U];c&&(l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id))}else if(f==="agent"){let c=I[U];c&&(c.id!==l?ie(`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=I[U];if(c){let u=We.find(g=>g.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=
|
|
189
|
+
ID: ${u.id}`)}}else if(f==="schedules"){let c=I[U];if(c){let u=Ye.find(g=>g.id===c.id);if(u){let g=k=>{if(k.type==="no-repeat")return"No repeat";let{interval:N}=k;switch(N.unit){case"minutes":return`Every ${N.every} min`;case"hours":return`Every ${N.every} hr`;case"days":return`Every ${N.every} day at ${String(N.time.hour).padStart(2,"0")}:${String(N.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${N.every} week`;case"months":return`Every ${N.every} month`;default:return"Unknown"}},S=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: ${g(u.config)}
|
|
193
|
-
Next Run: ${
|
|
194
|
-
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt)
|
|
193
|
+
Next Run: ${S}
|
|
194
|
+
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);$(c.length>0?c:void 0),ne.setDefaultConnectorIds(c);let u=R.filter(g=>rt.has(g.id)).map(g=>g.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"),g=Re.has("imageGeneration"),S=Re.has("chart"),k=Re.has("fileSystem");h(c),O(u),Z(g),Y(S),j(k),ne.setCapabilities({sandbox:c,webSearch:u,imageGeneration:g,chart:S}),ne.setLocalTools({fileSystem:k});let N=[];c&&N.push("Sandbox"),u&&N.push("Web Search"),g&&N.push("Image Generation"),S&&N.push("Chart"),k&&N.push("FileSystem"),p(N.length>0?`Active capabilities: ${N.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=I[U];if(c){let u=$o.find(g=>g.id===c.id);u&&A&&(s(u.id),i(u.title||void 0),he(!0),new F().getMessages(A.accessToken,A.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(N=>N.role==="user"||N.role==="assistant").map(N=>({role:N.role,content:ht(N.parts,!1),parts:N.parts})).filter(N=>N.content).toReversed();L(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=I[U];if(c){let u=H.getCurrentProfileName();c.id!==u?(H.setOverrideProfile(c.id),H.setCurrentProfile(c.id),ye(c.id),Ze(),ie(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),oe([]),t("");return}if(v===" "&&(f==="connectors"||f==="capabilities")){let c=I[U];c&&(f==="connectors"?it:at)(g=>{let S=new Set(g);return S.has(c.id)?S.delete(c.id):S.add(c.id),S});return}if(v==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set(I.map(u=>u.id)));return}if(v==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set);return}return}if(se&&z.length>0){if(y.upArrow){B(c=>c<=0?z.length-1:c-1);return}if(y.downArrow){B(c=>c>=z.length-1?0:c+1);return}if(y.escape){D(!1),fe([]);return}if(y.tab){_t(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(
|
|
197
|
-
`),
|
|
198
|
-
`).map(
|
|
199
|
-
`)}function
|
|
200
|
-
`);if(
|
|
201
|
-
`)}function
|
|
202
|
-
`),t)}if("content"in
|
|
203
|
-
`);return
|
|
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)),!
|
|
205
|
-
`)}let
|
|
206
|
-
`);ce=
|
|
207
|
-
|
|
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
|
|
209
|
-
${
|
|
210
|
-
`))console.log(`${It}\u2502 ${oe}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),
|
|
211
|
-
`))console.log(`${It}\u2502 ${oe}${Oe}`);console.log(`${
|
|
212
|
-
`),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${It}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Q,messageParts:z}},ke=p({id:
|
|
213
|
-
`))console.log(`${It}\u2502 ${Te}${Oe}`);console.log(`${
|
|
196
|
+
`)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Xt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:z,suggestionIndex:Te,showSuggestions:se,argMode:f,argItems:I,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:Zt,handleSubmit:Qt}}import{useCallback as Wt,useRef as Ur,useState as jr}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=jr([]),a=Ur(0),l=Wt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let T of o)if(T.models.some(V=>V.id===h))return T.id;return o[0]?.id}},[o]),d=Wt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let T=t?l(t):o[0]?.id;if(!T){n?.(h.filename,"No model provider available");return}let O=`file-${++a.current}`;r(V=>[...V,{id:O,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let Z=await new F().uploadFile(e.accessToken,e.workspaceId,h,T);r(ae=>ae.map(Y=>Y.id===O?{...Y,status:"uploaded",fileId:Z.id}:Y)),s?.(h.filename)}catch(V){let Z=V instanceof Error?V.message:"Upload failed";r(ae=>ae.map(Y=>Y.id===O?{...Y,status:"error",error:Z}:Y)),n?.(h.filename,Z)}},[e,t,l,o,s,n]),b=Wt(h=>{r(T=>T.filter(O=>O.id!==h))},[]),x=Wt(()=>{r([])},[]),C=Wt(()=>i.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[i]),$=i.some(h=>h.status==="uploading"),m=i.length>0;return{pendingFiles:i,addFile:d,removeFile:b,clearFiles:x,getUploadedFileIds:C,hasUploadingFiles:$,hasFiles:m}}import{jsx as X,jsxs as de}from"react/jsx-runtime";var Br=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Wo,Wo,Bo,Bo,gt,gt,gt,gt],rs=Br.map((e,t)=>`${Wr[t]??gt}${e}${re}`).join(`
|
|
197
|
+
`),Mr=`${gt}EntryDesk${re}`,Jr=500;function Gr(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 Hr(e){let t=Gr(e);return Math.max(...t.split(`
|
|
198
|
+
`).map(o=>o.length))}function Vr(e){let t=Hr(rs);return e>=t?rs:Mr}function is({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:b=!0}){let x=process.stdout.columns??80,C=Vr(x),$=ss(null),m=jn(s,n),{state:h,setState:T,messages:O,setMessages:V,input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,hasPersistedChat:E,setHasPersistedChat:R,credentials:W,setCredentials:_,currentResponse:he,setCurrentResponse:L,fullOutput:p,setFullOutput:ie,addSystemMessage:ke,startNewChat:q}=m,{credentials:A}=Bn(T);go(()=>{A&&!W&&_(A)},[A,W,_]);let{availableConnectors:te,availableModels:ee,availableAgents:me,modelProviders:ce,loading:M}=Wn(W),{currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,activeConnectorIds:B,setActiveConnectorIds:se}=Yn(t,e,i),D=ss(!1);go(()=>{if(!D.current){if(D.current=!0,!t&&!e){let k=ne.getDefaultModel();k&&z(k)}if(!i&&!e){let k=ne.getDefaultConnectorIds();k&&se(k.length>0?k:void 0)}}},[t,e,i,z,se]);let{currentAgentDetails:f}=zn(fe,W),{sandbox:w,setSandbox:I,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:$o,capabilityLabelMap:zt}=qn(r,a,l,d,b),{pendingFiles:We,addFile:wt,removeFile:Ye,clearFiles:Yt,getUploadedFileIds:lt,hasUploadingFiles:So,hasFiles:Ve}=ns({credentials:W,currentModel:Q,modelProviders:ce,onUploadSuccess:k=>{ke(`\u2713 Attached: ${k}`)},onUploadError:(k,N)=>{ke(`\u2717 Failed to upload ${k}: ${N}`)}}),{sendMessage:Xe}=Gn({chatId:Y,credentials:W,currentAgentId:fe,currentModel:Q,activeConnectorIds:B,sandbox:w,webSearch:oe,imageGeneration:Ce,chart:it,localTools:at,fullOutput:p,setMessages:V,setState:T,setCurrentResponse:L,setCredentials:_,setHasPersistedChat:R,getFileIds:lt,clearFiles:Yt}),Xt=Vo(k=>{q(k),L("")},[q]),[kt,mt]=Fr(!1),ct=Vo(async k=>{let N=k.text.trim(),J=uo(N);if(/^https?:\/\//.test(J))return;if(await Dn(N)&&Ln(J)){let ue=await On(N);ue&&(k.preventDefault(),await wt(ue))}},[wt]),xt=Vo(async()=>{if(!(kt||h.status!=="ready")){if(M||ce.length===0){ke("Please wait for resources to load before pasting images.");return}ke("Reading clipboard..."),mt(!0);try{let k=await _n();if(k){let N=`clipboard-${Date.now()}.png`;ke(`Uploading: ${N} (${Math.round(k.buffer.length/1024)}KB)`),await wt({buffer:k.buffer,filename:N,mimeType:k.mime})}else ke("No image found in clipboard. Copy an image first.")}catch(k){let N=k instanceof Error?k.message:"Failed to read clipboard";ke(`Clipboard error: ${N}`)}finally{mt(!1)}}},[wt,ke,kt,h.status,M,ce.length]),{suggestions:bt,suggestionIndex:Ct,showSuggestions:_e,argMode:ye,argItems:Ze,argIndex:$t,selectedConnectorIds:Zt,selectedCapabilities:_t,deleteConfirmMode:Qt,handleInputChange:v,handleSubmit:y}=os({input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:B,setActiveConnectorIds:se,sandbox:w,setSandbox:I,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:$o,availableModels:ee,availableAgents:me,availableConnectors:te,messages:O,hasPersistedChat:E,setHasPersistedChat:R,setMessages:V,addSystemMessage:ke,startNewChat:Xt,sendMessage:Xe,setFullOutput:ie,credentials:W,setCredentials:_,setState:T,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:l,chart:d,fileSystem:b},capabilityLabelMap:zt,hasUploadingFiles:So});if(Go((k,N)=>{(N.ctrl||N.meta)&&k==="v"&&xt()},{isActive:h.status==="ready"&&!ye}),Go((k,N)=>{if(!N.escape)return;let J=Date.now(),G=$.current;$.current=J,!(!G||J-G>Jr)&&(ye||_e||($.current=null,Ve&&Yt(),Z.length>0&&v("")))},{isActive:h.status==="ready"}),Go((k,N)=>{N.return&&(Xt("Started a new chat."),T({status:"ready"}))},{isActive:h.status==="error"}),go(()=>{if(W&&!M&&h.status==="loading")if(!Q&&!fe){let k=ne.getDefaultModel(),N=k&&ee.some(G=>G.id===k),J=N?k:ee[0]?.id;J?(N||ne.setDefaultModel(J),z(J),T({status:"ready"})):me.length===0?T({status:"no-model"}):T({status:"ready"})}else T({status:"ready"})},[W,M,Q,fe,ee,me,h.status,z,T]),go(()=>{o&&W&&h.status==="ready"&&Xe(o)},[W,o]),h.status==="loading")return de(Pe,{flexDirection:"column",children:[X(K,{children:C}),de(Pe,{children:[X(K,{color:"cyan",children:X(Ho,{type:"dots"})}),X(K,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return de(Pe,{flexDirection:"column",children:[X(K,{children:C}),X(K,{color:"yellow",children:"Not logged in"}),X(K,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return de(Pe,{flexDirection:"column",children:[X(K,{children:C}),X(K,{color:"yellow",children:"No workspace selected"}),X(K,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return de(Pe,{flexDirection:"column",children:[X(K,{children:C}),X(K,{color:"yellow",children:"No model or agent specified"}),s&&X(K,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(K,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(K,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return de(Pe,{flexDirection:"column",children:[X(K,{children:C}),de(K,{color:"red",children:["Error: ",h.message]}),X(K,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=fe?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":B&&B.length>0?te.filter(k=>B.includes(k.id)).map(k=>k.name).join(", ")||`${B.length} connector(s)`:"none",u=[];if(fe)if(f?.capabilities)for(let k of f.capabilities)u.push(zt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),oe&&u.push("Web"),Ce&&u.push("Image"),it&&u.push("Chart");at&&u.push("FileSystem");let g=H.getCurrentProfileName(),S=g!=="default";return de(Pe,{flexDirection:"column",children:[de(Pe,{marginBottom:1,flexDirection:"column",children:[X(K,{children:C}),de(Pe,{children:[X(K,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),de(K,{dimColor:!0,children:[" v","1.6.0"]}),S&&de(K,{color:"magenta",children:[" [",g,"]"]}),X(K,{dimColor:!0,children:" (type /help for commands)"})]})]}),O.map((k,N)=>{let J=k.parts&&p?ht(k.parts,!0):k.content,G=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ue=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return de(Pe,{flexDirection:"column",marginBottom:1,children:[de(K,{bold:!0,color:G,children:[ue,":"]}),X(Fo,{text:J})]},N)}),he&&de(Pe,{flexDirection:"column",marginBottom:1,children:[X(K,{bold:!0,color:"blue",children:"Assistant:"}),X(Fo,{text:he})]}),h.status==="ready"&&X(gn,{suggestions:bt,activeIndex:Ct,visible:_e}),h.status==="ready"&&ye&&X(mn,{items:Ze,activeIndex:$t,pageSize:ye==="agent"||ye==="skills"||ye==="model"?5:10,selectedIds:ye==="connectors"?Zt:ye==="capabilities"?_t: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:"}),h.status==="sending"&&!he?de(Pe,{children:[X(K,{color:"cyan",children:X(Ho,{type:"dots"})}),X(K,{children:" Thinking..."})]}):h.status==="ready"&&!ye?de(Pe,{flexDirection:"column",children:[Qt&&X(Pe,{marginBottom:1,children:X(K,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ve&&!Qt&&de(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[X(K,{dimColor:!0,children:"Attachments:"}),We.map((k,N)=>de(K,{children:[k.status==="uploading"?de(K,{color:"yellow",children:[X(Ho,{type:"dots"})," ",k.filename]}):k.status==="error"?de(K,{color:"red",children:["\u2717 ",k.filename]}):de(K,{color:"green",children:["\u2713 ",k.filename]}),N<We.length-1&&X(K,{children:", "})]},k.id))]}),de(Pe,{children:[X(K,{color:"green",children:"> "}),X($n,{value:Z,onChange:v,onSubmit:y,onPaste:ct,leadingOffset:2,multiline:!0})]})]}):null,de(Pe,{marginTop:1,flexDirection:"column",children:[de(Pe,{gap:2,children:[de(K,{children:[X(K,{dimColor:!0,children:"Model: "}),X(K,{color:"magenta",children:fe?f?.model?.name||"loading...":ee.find(k=>k.id===Q)?.name||Q||"none"})]}),de(K,{children:[X(K,{dimColor:!0,children:"Connectors: "}),X(K,{color:"cyan",children:c})]}),de(K,{children:[X(K,{dimColor:!0,children:"Capabilities: "}),X(K,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),de(K,{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 Xr}from"react/jsx-runtime";async function qr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function zr(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 It="\x1B[2m",Oe="\x1B[0m",Ko="\x1B[36m",us="\x1B[33m",yo="\x1B[32m",as="stream-json";function ls(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function wo(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
|
|
199
|
+
`)}function ko(e,t){if(t)return e;let o=e.split(`
|
|
200
|
+
`);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${It}... (${i} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
|
|
201
|
+
`)}function Yr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cs(e,t){if(!e)return"(no result)";if(typeof e!="object")return ko(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(`${us}[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)),ko(n.join(`
|
|
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
|
+
`);return ko(n||JSON.stringify(e,null,2),t)}return ko(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let te=await pe();t=te.accessToken,o=te.workspaceId}catch(te){xe(te)}let s=e.output===as;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${as}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=ne.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await qr());let a=new F;async function l(){if(!i)try{let{models:te}=await a.getModels(t,o),ee=te[0]?.id;if(!ee)return;ne.setDefaultModel(ee),i=ee}catch{}}let d,b,x,C;if(e.continue){let te=await zr(a,t,o,e.continue);te||process.exit(1),d=te.chat.id,b=te.chat.title??void 0,x=te.chat.agentId??void 0,C=te.modelId;let ee=e.agentId||e.model||x||C||i;!ee&&!e.interactive&&(await l(),ee=e.agentId||e.model||x||C||i),!ee&&!e.interactive&&(n||console.log(`Continuing chat: ${te.chat.title||"Untitled"}`),console.error(`
|
|
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: ${te.chat.title||"Untitled"}
|
|
205
|
+
`)}let $=e.agentId||x,m=e.model||C||i||void 0;!$&&!m&&(await l(),m=e.model||C||i||void 0),ls(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),ls(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let h=ne.getCapabilities(),T=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,O=e.webSearch??h?.webSearch??!1,V=e.imageGen??h?.imageGeneration??!1,Z=e.chart??h?.chart??!1,ae=ne.getDefaultConnectorIds(),Y=e.connectors??ae??void 0,Se=ne.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:Se?.fileSystem??!0;if(e.interactive){Kr(Xr(is,{agentId:$,model:m,message:e.message,chatId:d,chatTitle:b??void 0,connectorIds:Y,enableSandbox:T,enableWebSearch:O,enableImageGeneration:V,enableChart:Z,enableFileSystem:j}),{exitOnCtrlC:!1});return}let P=!e.continue&&!m&&!$;(!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 E=e.fullOutput??!1,R=d||ho(),W=j?to():void 0,_=j?oo():void 0,he=[],L=ho(),p=(te,ee,me)=>{let ce={id:R};return te&&(ce.message={id:te.id,createdAt:new Date,role:"user",parts:[{type:"text",text:te.text}]}),$?ce.agentId=$:(m&&(ce.model=m),ce.connectorIds=Y??[],ce.enableSandbox=T,ce.enableWebSearch=O,ce.enableImageGeneration=V,ce.enableChart=Z),W&&(ce.clientTools=W),_&&(ce.clientToolSystemPrompt=_),ee&&ee.length>0&&(ce.clientToolResults=ee),me&&me.length>0&&(ce.previousMessages=me),ce},ie=async te=>{if(!te.body)throw new Error("No response body");let ee=te.body.getReader(),me=new TextDecoder,ce="",M=new Map,Q=[],z=[];for(;;){let{done:fe,value:Te}=await ee.read();if(fe)break;ce+=me.decode(Te,{stream:!0});let B=ce.split(`
|
|
206
|
+
`);ce=B.pop()||"";for(let se of B){let D=se.trimEnd();if(D==="data: [DONE]"){s&&wo("done");continue}if(D.startsWith("data: "))try{let f=JSON.parse(D.slice(6));if(f.type&&z.push(f),s){f.type==="text-delta"&&f.delta!==void 0?wo("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?wo("reasoning-delta",f.delta):wo(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||{};Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${It}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
|
|
207
|
+
|
|
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 I=j&&tt(f.toolName)?`${yo}[LOCAL]${Oe} `:"";console.log(`
|
|
209
|
+
${Ko}\u250C\u2500 ${I}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},I=Yr(w);console.log(`${us}\u2502 Arguments:${Oe}`);for(let oe of I.split(`
|
|
210
|
+
`))console.log(`${It}\u2502 ${oe}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),I=cs(f.result,E);console.log(`${yo}\u2502 Result:${Oe}`);for(let oe of I.split(`
|
|
211
|
+
`))console.log(`${It}\u2502 ${oe}${Oe}`);console.log(`${Ko}\u2514\u2500 ${w?.toolName||"Tool"} completed${Oe}
|
|
212
|
+
`),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${It}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Q,messageParts:z}},ke=p({id:ho(),text:r}),q=await a.chat(t,o,ke),A=await ie(q);for(he=A.messageParts;A.pendingClientTools.length>0;){let te=[];for(let M of A.pendingClientTools){!n&&!s&&console.log(`${yo}\u2502 Executing locally...${Oe}`);let Q=await no(M.toolName,M.args),z=Q.success?JSON.stringify(Q.result):Q.error||"Unknown error";if(te.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:z}],isError:!Q.success}),!n&&!s){let fe=cs(Q.success?Q.result:{error:Q.error},E);console.log(`${yo}\u2502 Result:${Oe}`);for(let Te of fe.split(`
|
|
213
|
+
`))console.log(`${It}\u2502 ${Te}${Oe}`);console.log(`${Ko}\u2514\u2500 ${M.toolName} completed${Oe}
|
|
214
214
|
`)}}let ee=he.map(M=>{if(M.type==="tool-call"){let Q=te.find(fe=>fe.toolCallId===M.toolCallId),z=Q?.content.filter(fe=>fe.type==="text").map(fe=>fe.text).join(`
|
|
215
|
-
`);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Q?.isError?"output-error":"output-available",output:z}}return M}),me=[{id:L,role:"assistant",parts:ee}];L=
|
|
216
|
-
`)}function
|
|
217
|
-
`);if(
|
|
218
|
-
`)}function
|
|
219
|
-
`),t)}if("content"in
|
|
220
|
-
`);return
|
|
221
|
-
`))
|
|
222
|
-
`))
|
|
223
|
-
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let
|
|
224
|
-
`))i.push(`${
|
|
225
|
-
`))i.push(`${
|
|
226
|
-
`))}return
|
|
227
|
-
|
|
228
|
-
`).trim()}async function
|
|
229
|
-
`),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),
|
|
230
|
-
`)}let{messages:x}=await
|
|
231
|
-
`);for(let m of
|
|
232
|
-
`),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${
|
|
215
|
+
`);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Q?.isError?"output-error":"output-available",output:z}}return M}),me=[{id:L,role:"assistant",parts:ee}];L=ho();let ce=p(void 0,te,me);q=await a.chat(t,o,ce),A=await ie(q),he=A.messageParts}s||console.log("")}var Mt="\x1B[2m",Ae="\x1B[0m",pt="\x1B[36m",zo="\x1B[33m",fs="\x1B[32m",ps="stream-json";function ze(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
|
|
216
|
+
`)}function qo(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function xo(e,t){if(t)return e;let o=e.split(`
|
|
217
|
+
`);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),i=o.length-10;return[...s,`... (${i} lines omitted, use --full-output to see all) ...`,...n].join(`
|
|
218
|
+
`)}function Yo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(Yo);let t={};for(let[o,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[o]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[o]=Yo(s):t[o]=s;return t}function ms(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function gs(e,t){if(!e)return"(no result)";if(typeof e!="object")return xo(String(e),t);let o=t?e:Yo(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(`${zo}[stderr]${Ae} ${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(`
|
|
219
|
+
`),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(`
|
|
220
|
+
`);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}function Zr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function hs(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Mt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${pt}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${zo}\u2502 Arguments:${Ae}`);let i=ms(s.args);for(let r of i.split(`
|
|
221
|
+
`))n.push(`${Mt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){n.push(`${fs}\u2502 Result:${Ae}`);let i=gs(s.result,t);for(let r of i.split(`
|
|
222
|
+
`))n.push(`${Mt}\u2502 ${r}${Ae}`);n.push(`${pt}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${pt}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${pt}\u2514\u2500${Ae}`);o.push(n.join(`
|
|
223
|
+
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Zr(s),i=[];if(i.push(`${pt}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${zo}\u2502 Input:${Ae}`);let r=ms(s.input);for(let a of r.split(`
|
|
224
|
+
`))i.push(`${Mt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${fs}\u2502 Output:${Ae}`);let r=gs(s.output,t);for(let a of r.split(`
|
|
225
|
+
`))i.push(`${Mt}\u2502 ${a}${Ae}`);i.push(`${pt}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?i.push(`${pt}\u2514\u2500 (in progress)${Ae}`):i.push(`${pt}\u2514\u2500${Ae}`);o.push(i.join(`
|
|
226
|
+
`))}return o.join(`
|
|
227
|
+
|
|
228
|
+
`).trim()}async function ys(e){let t=e.output===ps;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ps}`),process.exit(1));let o=new F;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 x of l.toReversed())ze("message",x);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(),b=e.fullOutput??!1;for(let x of d){let C=hs(x.parts,b);if(!C)continue;let $=x.role==="user"?"You":"Assistant";console.log(`[${$}] ${qo(x.createdAt)}`),console.log(C),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 pe();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 m=d===0?1:d,{chats:h}=await o.getChats(s,n,20);m>h.length&&(console.error(`Chat number ${m} not found. You have ${h.length} recent chats.`),process.exit(1));let T=h[m-1];r=T.id,a=!0,l=T,t||console.log(`Chat: ${T.title||"Untitled"}
|
|
230
|
+
`)}let{messages:x}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(x));return}if(t){if(l&&ze("chat",l),x.length===0)ze("info","No messages in this chat.");else for(let m of x.toReversed())ze("message",m);ze("done");return}if(x.length===0){console.log("No messages in this chat.");return}let C=x.toReversed(),$=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${x.length} messages
|
|
231
|
+
`);for(let m of C){let h=hs(m.parts,$);if(!h)continue;let T=m.role==="user"?"You":"Assistant";console.log(`[${T}] ${qo(m.createdAt)}`),console.log(h),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
|
+
`),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${qo(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 Qr,Text as Ne}from"ink";import{jsx as je,jsxs as vt}from"react/jsx-runtime";var Pt=["apiUrl","hubUrl"];function Xo(e){return Pt.includes(e)}async function ws(e){let t=e.action||"list",o=e.configKey,s=e.value,n=H.getEffectiveProfileName();if(t==="list"){let i=ne.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: ${Pt.join(", ")}`);return}console.log(`Configuration:
|
|
233
233
|
`);for(let[a,l]of r)console.log(` ${a}=${l}`);console.log(`
|
|
234
|
-
Available keys: ${Pt.join(", ")}`);return}if(t==="get"){
|
|
235
|
-
`);for(let i of
|
|
234
|
+
Available keys: ${Pt.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Xo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${Pt.join(", ")}`),process.exit(1));let i=ne.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)),Xo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${Pt.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),ne.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)),Xo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${Pt.join(", ")}`),process.exit(1)),ne.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ks(){let e=Me();return vt(Qr,{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"}),vt(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),vt(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),vt(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Available keys:"}),vt(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),vt(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 xs(e){try{let t,o;try{let i=await pe();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 F,{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}):
|
|
235
|
+
`);for(let i of n){let r=i.connected?"connected":"disconnected";console.log(` ${i.name} (${r})`),console.log(` Provider: ${i.provider}`),console.log(` ID: ${i.id}`),console.log("")}}catch(t){xe(t)}}function bo(){console.log(`
|
|
236
236
|
EntryDesk CLI - Interact with EntryDesk from your terminal
|
|
237
237
|
|
|
238
238
|
Usage: entrydesk <command> [options]
|
|
@@ -400,11 +400,11 @@ Local Development:
|
|
|
400
400
|
$ entrydesk config set hubUrl http://localhost:3000
|
|
401
401
|
|
|
402
402
|
For more information, visit https://entrydesk.com/docs/cli
|
|
403
|
-
`)}import{render as
|
|
403
|
+
`)}import{render as li}from"ink";import{randomUUID as ei}from"crypto";import{chromium as ti}from"playwright";function oi(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function ni(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:"&&!oi(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function si(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 Zo(e){let{hubUrl:t,auth:o}=Me(),s=ni(t),n=new URL("/login",s),i=ei();n.searchParams.set("cli","true"),n.searchParams.set("state",i);let r;try{r=await ti.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:
|
|
406
|
-
Shutting down...`),
|
|
407
|
-
`);for(let i of
|
|
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",m=>{console.log(`[Browser Console] ${m.type()}: ${m.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(m=>{let h=new URL(m);if(h.host!==d)return!1;let T=h.pathname;if(T==="/login"||T.startsWith("/auth/"))return!1;let O=h.searchParams.get("state");return!(O&&O!==i)},{timeout:o.loginTimeout});let b=new URL("/api/auth/session",s).toString();process.env.DEBUG&&(console.log(`[DEBUG] Fetching session from: ${b}`),console.log(`[DEBUG] Current page URL: ${l.url()}`),console.log(`[DEBUG] SSL ignore enabled: ${o.ignoreSslErrors}`));let x=await l.evaluate(async m=>{try{let h=await fetch(m);if(!h.ok)throw new Error(`Failed to fetch session: ${h.status} ${h.statusText}`);return h.json()}catch(h){throw console.error("[Browser Context] Fetch error:",h),h}},b);if(!x?.accessToken)throw new Error("Failed to get access token from session");let C=si(x.accessToken);if(C&&C*1e3<=Date.now())throw new Error("Access token is expired. Please log in again.");let $=x.user?.email||"";return e?.onLoginSuccess?.($||"unknown"),{accessToken:x.accessToken,email:$,workspaceId:x.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 ri,useInput as ii}from"ink";import ai from"ink-spinner";import bs from"ink-text-input";import{useState as Jt}from"react";import{jsx as ge,jsxs as Ge}from"react/jsx-runtime";function Cs(){let{exit:e}=ri(),[t,o]=Jt("email"),[s,n]=Jt(""),[i,r]=Jt(""),[a,l]=Jt(null),[d,b]=Jt(null);return ii(($,m)=>{m.escape&&e()}),Ge(Ee,{flexDirection:"column",padding:1,children:[ge(Ee,{marginBottom:1,children:ge(Le,{bold:!0,color:"cyan",children:"EntryDesk Login"})}),t==="email"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(bs,{value:s,onChange:n,onSubmit:$=>{if(!$.includes("@")){l("Please enter a valid email address");return}n($),l(null),o("password")},placeholder:"user@example.com"})]}),a&&ge(Ee,{marginTop:1,children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to continue, Esc to cancel"})})]}),t==="password"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(Le,{color:"green",children:s})]}),Ge(Ee,{children:[ge(Le,{children:"Password: "}),ge(bs,{value:i,onChange:r,onSubmit:async $=>{r($),o("loading"),l(null);try{let m=new F,{token:h,refreshToken:T}=await m.login(s,$),{workspaces:O}=await m.getWorkspaces(h),V=O[0];await $e.saveAll({accessToken:h,refreshToken:T,email:s,workspaceId:V?.id}),b(V?.name??null),o("success"),setTimeout(()=>{e()},1500)}catch(m){o("error"),m instanceof Error?m.message.includes("403")||m.message.includes("Invalid")?l("Invalid email or password"):l(m.message):l("Login failed. Please try again.")}},mask:"*",placeholder:"Enter password"})]}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to login, Esc to cancel"})})]}),t==="loading"&&Ge(Ee,{children:[ge(Le,{color:"cyan",children:ge(ai,{type:"dots"})}),ge(Le,{children:" Logging in..."})]}),t==="success"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{color:"green",children:"\u2713"}),ge(Le,{children:" Logged in as "}),ge(Le,{bold:!0,children:s})]}),d&&ge(Ee,{children:Ge(Le,{dimColor:!0,children:["Workspace: ",d]})})]}),t==="error"&&Ge(Ee,{flexDirection:"column",children:[ge(Ee,{children:ge(Le,{color:"red",children:"\u2717 Login failed"})}),a&&ge(Ee,{children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Run `entrydesk login` to try again"})})]})]})}import{jsx as ci}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 F,{token:l,refreshToken:d}=await a.login(e.email,e.password),{workspaces:b}=await a.getWorkspaces(l),x=b[0];await $e.saveAll({accessToken:l,refreshToken:d,email:e.email,workspaceId:x?.id}),e.json?console.log(JSON.stringify({email:e.email,workspaceId:x?.id,workspaceName:x?.name})):(console.log(`Logged in as ${e.email}`),x&&console.log(`Workspace: ${x.name}`));return}if(e.google){console.log("Opening browser for Google OAuth...");let a=await Zo(),l=new F,{workspaces:d}=await l.getWorkspaces(a.accessToken),b=d[0],x=a.workspaceId||b?.id;await $e.saveAll({accessToken:a.accessToken,refreshToken:"",email:a.email,workspaceId:x}),e.json?console.log(JSON.stringify({email:a.email,workspaceId:x,workspaceName:b?.name})):(console.log(`Logged in as ${a.email}`),b&&console.log(`Workspace: ${b.name}`));return}if(e.interactive){li(ci(Cs,{}));return}if(console.log("Opening browser for login..."),process.env.DEBUG){let{getApiUrl:a,getHubUrl:l}=await import("./config-LX73PV6D.js");console.log(`[DEBUG] Hub URL: ${l()}`),console.log(`[DEBUG] API URL: ${a()}`)}let o=await Zo(),s=new F,{workspaces:n}=await s.getWorkspaces(o.accessToken),i=n[0],r=o.workspaceId||i?.id;await $e.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 Ss(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{await new F().revokeToken(t.refreshToken)}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){xe(t)}}import ui from"http";import{Client as di}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as fi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as pi}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as gi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as hi,ListToolsRequestSchema as yi}from"@modelcontextprotocol/sdk/types.js";async function wi(e,t,o){let s=new di({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new fi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Ts(e){let t=new pi({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(yi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(hi,async o=>{let{name:s,arguments:n}=o.params,i=await e.callTool({name:s,arguments:n});return{content:i.content,isError:i.isError}}),t}async function ki(e,t){let o=ui.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=Ts(e),r=new gi({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
|
+
Shutting down...`),o.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{o.close(),await e.close(),process.exit(0)})}async function xi(e){let t=Ts(e),o=new mi;o.onclose=async()=>{await e.close()},await t.connect(o)}async function Is(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 pe();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 wi(s,t,o);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||n.httpPort;await ki(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await xi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function vs(e){try{let t,o;try{let i=await pe();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 F,{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
|
+
`);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 bi(){console.log(`
|
|
408
408
|
Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
|
|
409
409
|
|
|
410
410
|
Commands:
|
|
@@ -419,7 +419,7 @@ Commands:
|
|
|
419
419
|
|
|
420
420
|
Flags:
|
|
421
421
|
--json Output JSON
|
|
422
|
-
`)}function
|
|
422
|
+
`)}function Gt(e,t){if(e)return e;if(t&&H.getProfileCount()===1)return H.getProfileNames()[0];throw new Lt("Profile name is required when multiple profiles exist.")}function Ci(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function Ps(e){try{let t=e.action||"list",o=H.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){bi();return}if(t==="list"){let i=H.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:i.map(r=>({name:r,isCurrent:r===o}))}));return}console.log(`Profiles (${i.length}):`);for(let r of i)console.log(` ${r}${r===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let i=Gt(s,!0),r=ne.getAll(i),a=await $e.getAll(i),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:i,isCurrent:i===o,config:r,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${i}${i===o?" (current)":""}`),console.log(` API URL: ${r.apiUrl??"default"}`),console.log(` Hub URL: ${r.hubUrl??"default"}`),console.log(` Model: ${r.model?.default??"unset"}`);let d=r.connectors?.defaults&&r.connectors.defaults.length>0?r.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${Ci(r.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let i=s||H.DEFAULT_PROFILE;if(H.createProfile(i),e.json){console.log(JSON.stringify({name:i,created:!0}));return}console.log(`Profile created: ${i}`);return}if(t==="use"||t==="switch"){let i=Gt(s,!0);if(H.setCurrentProfile(i),e.json){console.log(JSON.stringify({name:i,current:!0}));return}console.log(`Switched to profile: ${i}`);return}if(t==="delete"||t==="remove"||t==="rm"){let i=Gt(s,!0),r=H.deleteProfile(i);if(e.json){console.log(JSON.stringify({deleted:i,currentProfile:r.currentProfile}));return}console.log(`Profile deleted: ${i}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let i=Gt(s,!0);if(!n)throw new Lt("New profile name is required.");let r=H.renameProfile(i,n);if(e.json){console.log(JSON.stringify({renamed:i,name:n,currentProfile:r.currentProfile}));return}console.log(`Profile renamed: ${i} -> ${n}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="clone"||t==="copy"){let i=Gt(s,!0);if(!n)throw new Lt("Target profile name is required.");let r=ne.getAll(i);if(H.createProfile(n),ne.setAll(r,n),await $e.clear(n),e.json){console.log(JSON.stringify({source:i,name:n,cloned:!0}));return}console.log(`Profile cloned: ${i} -> ${n}`);return}throw new Lt(`Unknown profile command: ${t}`)}catch(t){xe(t)}}function Ht(){console.log(`
|
|
423
423
|
Usage: entrydesk schedules [list|get|create|delete] [options]
|
|
424
424
|
|
|
425
425
|
Commands:
|
|
@@ -445,7 +445,7 @@ Create Options:
|
|
|
445
445
|
|
|
446
446
|
Flags:
|
|
447
447
|
--json Output JSON
|
|
448
|
-
`)}function
|
|
448
|
+
`)}function As(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Vt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,i=parseInt(s[2],10),r=parseInt(s[3],10),a=n*(i*60+r)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function $i(e){console.log(`
|
|
449
449
|
Schedule: ${e.name}
|
|
450
450
|
${"\u2501".repeat(50)}
|
|
451
451
|
ID: ${e.id}
|
|
@@ -457,13 +457,13 @@ Prompt:
|
|
|
457
457
|
${e.prompt.slice(0,200)}${e.prompt.length>200?"...":""}
|
|
458
458
|
|
|
459
459
|
Schedule:
|
|
460
|
-
${
|
|
460
|
+
${As(e.config)}
|
|
461
461
|
|
|
462
|
-
Next Run: ${e.nextRunAt?
|
|
463
|
-
Created: ${
|
|
464
|
-
Updated: ${
|
|
465
|
-
`)}function
|
|
466
|
-
`);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${
|
|
462
|
+
Next Run: ${e.nextRunAt?Vt(e.nextRunAt,e.utcOffset):"-"}
|
|
463
|
+
Created: ${Vt(e.createdAt,e.utcOffset)}
|
|
464
|
+
Updated: ${Vt(e.updatedAt,e.utcOffset)}
|
|
465
|
+
`)}function Si(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function Ns(e){try{if(e.help){Ht();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new F;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Ht(),process.exit(1));let d=await i.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}$i(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Ht(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:Si(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Vt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Ht(),process.exit(1)),await i.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Ht(),process.exit(1));let r=[],a;do{let l=await i.getSchedules(o,s,{nextKey:a,limit:100});r.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
|
|
466
|
+
`);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${As(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?Vt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){xe(t)}}import Ti from"fs";import At from"fs/promises";import Es from"os";import st from"path";import Ii from"archiver";function Qo(){console.log(`
|
|
467
467
|
Usage: entrydesk skills [list|upload|delete] [options]
|
|
468
468
|
|
|
469
469
|
Commands:
|
|
@@ -476,11 +476,16 @@ Options:
|
|
|
476
476
|
--me Only list skills created by me
|
|
477
477
|
--force Overwrite an existing skill with the same name
|
|
478
478
|
--json Output JSON (for list/upload)
|
|
479
|
-
`)}function
|
|
480
|
-
`);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
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
479
|
+
`)}function vi(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Pi(e){let t=await At.realpath(e),o=[process.cwd(),Es.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await At.realpath(i)}catch{return st.resolve(i)}}))).some(i=>vi(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ai(e){let t=await At.mkdtemp(st.join(Es.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ti.createWriteStream(o),r=Ii("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 _s(e){let t,o;try{let a=await pe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new F;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),Qo(),process.exit(1));let l=st.resolve(a),d;try{d=await At.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let b=l,x=null;try{try{await Pi(l)}catch(h){let T=h instanceof Error?h.message:"Invalid upload path.";console.error(T),process.exit(1)}if(d.isDirectory()){let h=await Ai(l);b=h.zipPath,x=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));st.extname(b).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let C=await At.readFile(b),$=new FormData;$.append("file",new Blob([C],{type:"application/zip"}),st.basename(b)),e.force&&$.append("force","true");let m;try{m=await n.uploadSkill(t,o,$)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let T=h;T.response&&T.response.status===409&&(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."),process.exit(1))}throw h}if(e.json){console.log(JSON.stringify(m));return}console.log(`Uploaded skill: ${m.name}`),console.log(` ID: ${m.id}`),console.log(` Description: ${m.description}`);return}finally{x&&await At.rm(x,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),Qo(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),Qo(),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}):
|
|
480
|
+
`);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 Ls(e){try{let t=H.getEffectiveProfileName(),o=await $e.getAll(),s={model:ne.getDefaultModel(),connectors:ne.getDefaultConnectorIds(),capabilities:ne.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 F,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 Wi from"fs";import{Client as Ni}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ei}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function _i(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await pe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Me().apiUrl);let n=new Ni({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new Ei(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function Co(){return _i()}import tn from"fs/promises";import Li from"os";import Kt from"path";var en=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,Nt={green:en?"\x1B[32m":"",yellow:en?"\x1B[33m":"",reset:en?"\x1B[0m":""},Di=10*1024,Ds=8*1024,Os=2*1024,Oi=100,Ri=100;function Ui(){return Kt.join(Li.homedir(),".entrydesk","tool-results")}function ji(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Oi);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 Bi(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=ji(e);return`${o}_${s}.json`}async function Rs(e,t){try{return await tn.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 Us(e,t){try{let o=Ui();await tn.mkdir(o,{recursive:!0});let s=Bi(e),n=Kt.extname(s),i=s.slice(0,-n.length),r=Fi(t),a=Kt.join(o,s);if(await Rs(a,r))return a;for(let b=1;b<=Ri;b++){let x=Kt.join(o,`${i}-${b}${n}`);if(await Rs(x,r))return x}let l=Math.random().toString(36).slice(2,10),d=Kt.join(o,`${i}-${l}${n}`);return await tn.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Nt.yellow}Warning: Could not save result to file: ${s}${Nt.reset}`),null}}function js(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Di)return e;let s=e.slice(0,Ds),n=e.slice(-Os),r=((o-Ds-Os)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(l+=`
|
|
481
|
+
Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
|
|
482
|
+
|
|
483
|
+
${l}
|
|
484
|
+
|
|
485
|
+
${n}`}function Fs(e){console.log(`${Nt.green}Tool execution result saved to: ${e}${Nt.reset}`),console.log()}function Bs(){console.log(`${Nt.green}Tool execution result:${Nt.reset}`)}function Mi(e){return e.split("__")[0]??e}function yt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Et(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?yt("AUTH_MISSING",s,t):yt(o,s,t)}async function Ji(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},i=b=>{s||(s=!0,n(),e(b))},r=setTimeout(()=>{o||i(null)},100),a=b=>{o=!0,clearTimeout(r),t.push(b)},l=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var qt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Gi(e,t){if(e)return e;if(t)try{return Wi.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new qt(`Failed to read input file: ${n}`)}let o=await Ji();if(o)return o;throw new qt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Hi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
|
|
486
|
+
`)}function Vi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
|
|
487
|
+
`)}async function Ki(e,t){let o=await Co().catch(s=>{Et(s,e)});try{let n=(await o.listTools()).tools;if(t){let i=t.toLowerCase();n=n.filter(r=>Mi(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(n,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${i}:
|
|
488
|
+
`);for(let r of n)console.log(Hi(r)),console.log()}}catch(s){Et(s,e)}finally{await o.close().catch(()=>{})}}async function qi(e,t){let o=await Co().catch(s=>{Et(s,t)});try{let n=(await o.listTools()).tools.find(i=>i.name===e);n||yt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Vi(n))}catch(s){Et(s,t)}finally{await o.close().catch(()=>{})}}async function zi(e,t,o){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";yt("INVALID_INPUT",a,o)}let n=await Co().catch(r=>{Et(r,o,"TOOL_CALL_FAILED")}),i=!1;try{let r=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(r,null,2));else{let a=await Us(e,r);a&&Fs(a),Bs();let l=r.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),b=js(d,a);console.log(b)}}r.isError&&(i=!0)}catch(r){Et(r,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}i&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ki(t,e.prefix);break;case"get":e.name||yt("INVALID_INPUT","Tool name is required",t),await qi(e.name,t);break;case"call":{e.name||yt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Gi(e.input,e.inputFile)}catch(s){throw s instanceof qt&&yt("INVALID_INPUT",s.message,t),s}await zi(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
|
|
484
489
|
|
|
485
490
|
Actions:
|
|
486
491
|
list List all available tools
|
|
@@ -488,16 +493,24 @@ Actions:
|
|
|
488
493
|
call <name> Call a tool with JSON input
|
|
489
494
|
|
|
490
495
|
Options:
|
|
491
|
-
--json
|
|
492
|
-
-p, --prefix <name>
|
|
493
|
-
-i, --input <json>
|
|
496
|
+
--json Output in JSON format
|
|
497
|
+
-p, --prefix <name> Filter tools by prefix (for 'list' action)
|
|
498
|
+
-i, --input <json> JSON input for tool call
|
|
499
|
+
-f, --input-file <path> Read JSON input from file
|
|
500
|
+
|
|
501
|
+
Input Priority (for 'call' action):
|
|
502
|
+
1. --input flag (direct JSON string)
|
|
503
|
+
2. --input-file flag (read from file)
|
|
504
|
+
3. stdin (piped input)
|
|
494
505
|
|
|
495
506
|
Examples:
|
|
496
507
|
entrydesk tool list
|
|
497
508
|
entrydesk tool list --prefix agent
|
|
498
509
|
entrydesk tool get agent__search_agents
|
|
499
510
|
entrydesk tool call agent__search_agents --input '{"limit": 5}'
|
|
500
|
-
|
|
511
|
+
entrydesk tool call agent__search_agents --input-file input.json
|
|
512
|
+
echo '{"limit": 5}' | entrydesk tool call agent__search_agents
|
|
513
|
+
`);break}}function Yi(){console.log(`
|
|
501
514
|
Usage: entrydesk usage [options]
|
|
502
515
|
|
|
503
516
|
Options:
|
|
@@ -510,10 +523,10 @@ Examples:
|
|
|
510
523
|
entrydesk usage --limit 10 # Show top 10 users
|
|
511
524
|
entrydesk usage --sort-by operations # Sort by operation count
|
|
512
525
|
entrydesk usage --json # JSON output
|
|
513
|
-
`)}async function
|
|
514
|
-
`);let l=0,d=0;for(let m of
|
|
515
|
-
`);let
|
|
516
|
-
`);for(let m of
|
|
526
|
+
`)}async function Ms(e){if(e.help){Yi();return}let t,o;try{let m=await pe();t=m.accessToken,o=m.workspaceId}catch(m){let h=m instanceof Error?m.message:"Authentication failed";console.error(h),process.exit(1)}let s=new F,n=[],i,r=0,a=100;do{let m=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...m.monthlyUsages),i=m.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:
|
|
527
|
+
`);let l=0,d=0;for(let m of n)l+=parseFloat(m.totalCost),d+=m.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
|
|
528
|
+
`);let b=e.sortBy||"cost",x=[...n].toSorted((m,h)=>b==="cost"?parseFloat(h.totalCost)-parseFloat(m.totalCost):h.operationCount-m.operationCount),C=e.limit&&e.limit>0?e.limit:x.length,$=x.slice(0,C);console.log(`Usage by User (sorted by ${b}, showing ${$.length} of ${n.length}):
|
|
529
|
+
`);for(let m of $){let h=parseFloat(m.totalCost);console.log(` ${m.user.name} (${m.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${m.operationCount.toLocaleString()}`),console.log("")}$.length<n.length&&console.log(`... and ${n.length-$.length} more users`)}function on(){console.log("entrydesk 1.6.0")}function nn(){console.log(`
|
|
517
530
|
Usage: entrydesk workspaces [list|switch|use] [options]
|
|
518
531
|
|
|
519
532
|
Commands:
|
|
@@ -523,6 +536,6 @@ Commands:
|
|
|
523
536
|
|
|
524
537
|
Flags:
|
|
525
538
|
--json Output JSON
|
|
526
|
-
`)}async function
|
|
527
|
-
Available workspaces:`);for(let
|
|
528
|
-
`);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function
|
|
539
|
+
`)}async function Js(e){if(e.help){nn();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await dt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",i=new F;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),nn(),process.exit(1));let{workspaces:l}=await i.getWorkspaces(t),d=l.find(b=>b.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
|
|
540
|
+
Available workspaces:`);for(let b of l)console.error(` ${b.name}: ${b.id}`);process.exit(1)}if(await $e.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),nn(),process.exit(1));let{workspaces:r}=await i.getWorkspaces(t);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${r.length}):
|
|
541
|
+
`);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Gs(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":r==="--google"||r==="-g"?n.google=!0:r==="-i"||r==="--interactive"?n.interactive=!0:r==="--email"?n.email=e[++i]:r==="--password"&&(n.password=e[++i]);break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(l=>l.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as ea}from"react/jsx-runtime";var He=process.argv.slice(2);(He[0]==="--help"||He[0]==="-h")&&(bo(),process.exit(0));(He[0]==="--version"||He[0]==="-v")&&(on(),process.exit(0));var sn=!He[0]||He[0].startsWith("-"),Zi=sn?"chat":He[0],be=Gs(He,Zi,sn);sn&&be.command==="chat"&&(be.interactive=!0);async function Qi(){try{if(be.command!=="profile"){let e=be.profile||H.getCurrentProfileName();H.ensureProfileExists(e),H.setOverrideProfile(e)}switch(be.command){case"login":await $s(be);break;case"logout":await Ss(be);break;case"status":await Ls(be);break;case"workspaces":await Js(be);break;case"agents":await an(be);break;case"models":await vs(be);break;case"connectors":await xs(be);break;case"skills":await _s(be);break;case"schedules":await Ns(be);break;case"chats":await ys(be);break;case"budget":await ln(be);break;case"usage":await Ms(be);break;case"config":be.action==="help"||He[1]==="--help"?Xi(ea(ks,{})):await ws(be);break;case"profile":await Ps(be);break;case"chat":He[1]==="--help"||He[1]==="-h"?bo():await ds(be);break;case"mcp-server":await Is({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ws(be);break;case"version":on();break;default:bo();break}}catch(e){xe(e)}}Qi();
|