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