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