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