@entrydesk/cli 1.7.10 → 1.7.11

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 $e,b as Qe,c as dt,d as pe,e as Dt,f as xe,g as H,h as ne,i as Me,n as B}from"./chunk-7HCPZOK3.js";import{render as Xi}from"ink";function Po(){console.log(`
2
+ import{a as Ce,b as Qe,c as dt,d as fe,e as Dt,f as xe,g as G,h as oe,i as Me,n as B}from"./chunk-7IRMLGCJ.js";import{render as Zi}from"ink";function Po(){console.log(`
3
3
  Usage: entrydesk agents [list|create|update|delete] [options]
4
4
 
5
5
  Commands:
@@ -21,8 +21,8 @@ Create/Update Options:
21
21
 
22
22
  Flags:
23
23
  --json Output JSON
24
- `)}function Ks(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function rn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),Po(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:Ks(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function an(e){try{if(e.help){Po();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="create"){let a=rn(e),l=await i.createAgent(o,s,a);if(e.json){console.log(JSON.stringify(l));return}console.log(`Created agent: ${l.name}`),console.log(` ID: ${l.id}`);return}if(n==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let l=rn(e);await i.updateAgent(o,s,a,l),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),Po(),process.exit(1));let{agents:r}=await i.getAgents(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
25
- `);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){xe(t)}}function qs(){console.log(`
24
+ `)}function qs(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function an(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),Po(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:qs(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function ln(e){try{if(e.help){Po();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="create"){let a=an(e),l=await i.createAgent(o,s,a);if(e.json){console.log(JSON.stringify(l));return}console.log(`Created agent: ${l.name}`),console.log(` ID: ${l.id}`);return}if(n==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let l=an(e);await i.updateAgent(o,s,a,l),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),Po(),process.exit(1));let{agents:r}=await i.getAgents(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
25
+ `);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){xe(t)}}function zs(){console.log(`
26
26
  Usage: entrydesk budget [get|set|clear] [options]
27
27
 
28
28
  Commands:
@@ -32,7 +32,7 @@ Commands:
32
32
 
33
33
  Flags:
34
34
  --json Output JSON
35
- `)}async function ln(e){try{if(e.help){qs();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new B;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){xe(t)}}import{render as Kr}from"ink";import{v4 as yo}from"uuid";import{exec as zs}from"child_process";import Ys from"fs";import et from"fs/promises";import cn from"os";import Ao from"path";import{promisify as Xs}from"util";import{glob as Zs}from"glob";var Qs=Xs(zs),er=`## Filesystem Tool Instructions
35
+ `)}async function cn(e){try{if(e.help){zs();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new B;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){xe(t)}}import{render as qr}from"ink";import{v4 as yo}from"uuid";import{exec as Ys}from"child_process";import Xs from"fs";import et from"fs/promises";import un from"os";import Ao from"path";import{promisify as Zs}from"util";import{glob as Qs}from"glob";var er=Zs(Ys),tr=`## Filesystem Tool Instructions
36
36
 
37
37
  You have access to filesystem tools that allow you to interact with the user's local filesystem.
38
38
 
@@ -56,24 +56,24 @@ You have access to filesystem tools that allow you to interact with the user's l
56
56
  - Search results are limited to prevent overwhelming responses
57
57
  - Execute Command has a default timeout of 30 seconds (max 5 minutes)
58
58
  - The current working directory is: ${process.cwd()}
59
- - The user's home directory is: ${cn.homedir()}
60
- `,tr=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function un(){return{name:"filesystem",systemPrompt:er,tools:tr}}function Ke(e){return e.startsWith("~/")?Ao.join(cn.homedir(),e.slice(2)):e}function oo(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
59
+ - The user's home directory is: ${un.homedir()}
60
+ `,or=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function dn(){return{name:"filesystem",systemPrompt:tr,tools:or}}function Ke(e){return e.startsWith("~/")?Ao.join(un.homedir(),e.slice(2)):e}function oo(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
61
61
 
62
- ... (truncated, ${e.length-t} more characters)`}async function dn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ke(t.path),s=await et.readFile(o,"utf-8");return{success:!0,result:oo(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Ke(n);try{let r=await et.readFile(i,"utf-8");s[n]=oo(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ke(t.path),s=t.content;return await et.mkdir(Ao.dirname(o),{recursive:!0}),await et.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ke(t.path);return await et.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ke(t.path);return{success:!0,result:(await et.readdir(o,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Ke(t.cwd):process.cwd(),n=await Zs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ke(t.path),s=await et.stat(o);return{success:!0,result:{path:o,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let o=Ke(t.source),s=Ke(t.destination);return await et.mkdir(Ao.dirname(s),{recursive:!0}),await et.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Ke(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Ys.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await Qs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:oo(i,5e4),stderr:oo(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function No(e){return e.startsWith("filesystem__")}function fn(){return[un()]}function no(){return fn().flatMap(e=>e.tools)}function so(){return fn().map(e=>e.systemPrompt).filter(Boolean).join(`
62
+ ... (truncated, ${e.length-t} more characters)`}async function fn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ke(t.path),s=await et.readFile(o,"utf-8");return{success:!0,result:oo(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Ke(n);try{let r=await et.readFile(i,"utf-8");s[n]=oo(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ke(t.path),s=t.content;return await et.mkdir(Ao.dirname(o),{recursive:!0}),await et.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ke(t.path);return await et.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ke(t.path);return{success:!0,result:(await et.readdir(o,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Ke(t.cwd):process.cwd(),n=await Qs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ke(t.path),s=await et.stat(o);return{success:!0,result:{path:o,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let o=Ke(t.source),s=Ke(t.destination);return await et.mkdir(Ao.dirname(s),{recursive:!0}),await et.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Ke(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Xs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await er(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:oo(i,5e4),stderr:oo(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function No(e){return e.startsWith("filesystem__")}function pn(){return[dn()]}function no(){return pn().flatMap(e=>e.tools)}function so(){return pn().map(e=>e.systemPrompt).filter(Boolean).join(`
63
63
 
64
- `)}function tt(e){return No(e)}async function ro(e,t){return No(e)?dn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as K,useInput as Ho}from"ink";import Vo from"ink-spinner";import{useCallback as Ko,useEffect as ho,useRef as ss,useState as Br}from"react";import{Box as io,Text as Ot}from"ink";import{jsx as ao,jsxs as Rt}from"react/jsx-runtime";function pn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function mn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),C=Math.max(1,r),x=Math.floor(t/C)*C,b=Math.min(e.length,x+C),$=e.slice(x,b);return Rt(io,{flexDirection:"column",marginBottom:1,children:[ao(Ot,{bold:!0,color:"cyan",children:i}),ao(io,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:$.map((m,h)=>{let D=x+h===t,V=o?.has(m.id),Z=pn(m.name,d),ae=m.description?pn(m.description,Math.max(0,d-l)):"",Y=s?" ".repeat(l):"";return Rt(io,{paddingX:1,flexDirection:"column",children:[Rt(io,{children:[s&&ao(Ot,{color:V?"green":"gray",children:V?"[\u2713] ":"[ ] "}),ao(Ot,{backgroundColor:D?"cyan":void 0,color:D?"black":V?"green":"white",bold:!0,children:Z})]}),ae&&Rt(Ot,{dimColor:!0,children:[Y,"\xB7 ",ae]})]},m.id)})}),Rt(Ot,{dimColor:!0,children:[s?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>C?` \xB7 Showing ${x+1}-${b} of ${e.length}`:""]})]})}import{Box as Eo,Text as Ut}from"ink";import{jsx as jt,jsxs as _o}from"react/jsx-runtime";function gn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:_o(Eo,{flexDirection:"column",marginBottom:1,children:[jt(Eo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return _o(Eo,{paddingX:1,children:[_o(Ut,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),jt(Ut,{dimColor:!0,children:r}),jt(Ut,{children:" - "}),jt(Ut,{color:i?"white":"gray",children:s.description})]},s.name)})}),jt(Ut,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as or,Text as hn,useInput as nr,useStdout as sr}from"ink";import{useCallback as yn,useEffect as wn,useMemo as Lo,useRef as kn,useState as xn}from"react";import{jsx as Ro}from"react/jsx-runtime";function lo(e,t){return e<0?0:e>t?t:e}function Do(e){return Array.from(e)}function co(e){return/\s/.test(e)}function Oo(e,t){let o=t;for(;o>0&&co(e[o-1]??"");)o-=1;for(;o>0&&!co(e[o-1]??"");)o-=1;return o}function bn(e,t){let o=t;for(;o<e.length&&co(e[o]??"");)o+=1;for(;o<e.length&&!co(e[o]??"");)o+=1;return o}function rr(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((r,a)=>{if(r===`
65
- `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Cn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ir=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=xn(()=>Do(e).length),d=kn(null),[C,x]=xn(0),b=kn(null),{stdout:$}=sr(),m=Lo(()=>Do(e),[e]),{lines:h,lineStarts:T,lineLengths:D}=Lo(()=>rr(m),[m]),{row:V,col:Z}=Lo(()=>Cn(a,T,D),[a,T,D]),ae=Math.max(1,($?.columns??80)-i);wn(()=>{d.current!==e?(l(m.length),b.current=null):l(j=>lo(j,m.length)),d.current=e},[e,m.length]),wn(()=>{x(j=>{let P=j;Z<P?P=Z:Z>=P+ae&&(P=Z-ae+1);let E=D[V]??0,R=Z===E?E+1:E,W=Math.max(0,R-ae);return P>W&&(P=W),P<0&&(P=0),P})},[ae,Z,V,D]);let Y=yn((j,P)=>{d.current=j,t(j),l(P),b.current=null},[t]),Se=yn(async(j,P)=>{if(!n)return;let{row:E,col:R}=Cn(a,T,D),W=h[E]??[],_=D[E]??0,he=h.length>1;if(r&&(P.meta&&P.return||P.ctrl&&j==="j"||P.shift&&P.return)){let L=[...m.slice(0,a),`
66
- `,...m.slice(a)].join("");Y(L,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&E>0?l(T[E]-1):l(T[E]+Oo(W,R)),b.current=null):(R===0&&E>0?l(T[E]-1):l(L=>lo(L-1,m.length)),b.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),b.current=null):(R>=_&&E<h.length-1?l(T[E+1]):l(L=>lo(L+1,m.length)),b.current=null);return}if(r&&he&&P.upArrow){let L=b.current??R,p=Math.max(0,E-1),ie=Math.min(L,D[p]??0);l((T[p]??0)+ie),b.current=L;return}if(r&&he&&P.downArrow){let L=b.current??R,p=Math.min(h.length-1,E+1),ie=Math.min(L,D[p]??0);l((T[p]??0)+ie),b.current=L;return}if(P.ctrl){if(j==="a"){l(T[E]??0),b.current=null;return}if(j==="e"){l((T[E]??0)+_),b.current=null;return}if(j==="u"){if(R>0){let L=T[E]??0,p=[...m.slice(0,L),...m.slice(a)].join("");Y(p,L)}return}if(j==="k"){if(R<_){let L=(T[E]??0)+_,p=[...m.slice(0,a),...m.slice(L)].join("");Y(p,a)}return}if(j==="w"){if(R===0&&E>0){let p=[...m.slice(0,a-1),...m.slice(a)].join("");Y(p,a-1);return}let L=Oo(W,R);if(L!==R){let p=(T[E]??0)+L,ie=[...m.slice(0,p),...m.slice(a)].join("");Y(ie,p)}return}if(j==="d"){if(a<m.length){let L=[...m.slice(0,a),...m.slice(a+1)].join("");Y(L,a)}return}return}if(P.meta){j==="b"?(R===0&&E>0?l(T[E]-1):l(T[E]+Oo(W,R)),b.current=null):j==="f"&&(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),b.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let L=[...m.slice(0,a-1),...m.slice(a)].join("");Y(L,a-1);return}if(!(P.tab||P.escape)&&j.length>0){let L=r?j.replace(/\r\n/g,`
64
+ `)}function tt(e){return No(e)}async function ro(e,t){return No(e)?fn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as V,useInput as Vo}from"ink";import Ko from"ink-spinner";import{useCallback as qo,useEffect as ho,useRef as rs,useState as Fr}from"react";import{Box as io,Text as Ot}from"ink";import{jsx as ao,jsxs as Rt}from"react/jsx-runtime";function gn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function mn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),C=Math.max(1,r),k=Math.floor(t/C)*C,b=Math.min(e.length,k+C),S=e.slice(k,b);return Rt(io,{flexDirection:"column",marginBottom:1,children:[ao(Ot,{bold:!0,color:"cyan",children:i}),ao(io,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:S.map((g,h)=>{let D=k+h===t,H=o?.has(g.id),X=gn(g.name,d),ie=g.description?gn(g.description,Math.max(0,d-l)):"",z=s?" ".repeat(l):"";return Rt(io,{paddingX:1,flexDirection:"column",children:[Rt(io,{children:[s&&ao(Ot,{color:H?"green":"gray",children:H?"[\u2713] ":"[ ] "}),ao(Ot,{backgroundColor:D?"cyan":void 0,color:D?"black":H?"green":"white",bold:!0,children:X})]}),ie&&Rt(Ot,{dimColor:!0,children:[z,"\xB7 ",ie]})]},g.id)})}),Rt(Ot,{dimColor:!0,children:[s?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>C?` \xB7 Showing ${k+1}-${b} of ${e.length}`:""]})]})}import{Box as Eo,Text as Ut}from"ink";import{jsx as jt,jsxs as _o}from"react/jsx-runtime";function hn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:_o(Eo,{flexDirection:"column",marginBottom:1,children:[jt(Eo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return _o(Eo,{paddingX:1,children:[_o(Ut,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),jt(Ut,{dimColor:!0,children:r}),jt(Ut,{children:" - "}),jt(Ut,{color:i?"white":"gray",children:s.description})]},s.name)})}),jt(Ut,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as nr,Text as yn,useInput as sr,useStdout as rr}from"ink";import{useCallback as wn,useEffect as kn,useMemo as Lo,useRef as xn,useState as bn}from"react";import{jsx as Ro}from"react/jsx-runtime";function lo(e,t){return e<0?0:e>t?t:e}function Do(e){return Array.from(e)}function co(e){return/\s/.test(e)}function Oo(e,t){let o=t;for(;o>0&&co(e[o-1]??"");)o-=1;for(;o>0&&!co(e[o-1]??"");)o-=1;return o}function Cn(e,t){let o=t;for(;o<e.length&&co(e[o]??"");)o+=1;for(;o<e.length&&!co(e[o]??"");)o+=1;return o}function ir(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((r,a)=>{if(r===`
65
+ `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Sn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ar=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=bn(()=>Do(e).length),d=xn(null),[C,k]=bn(0),b=xn(null),{stdout:S}=rr(),g=Lo(()=>Do(e),[e]),{lines:h,lineStarts:$,lineLengths:D}=Lo(()=>ir(g),[g]),{row:H,col:X}=Lo(()=>Sn(a,$,D),[a,$,D]),ie=Math.max(1,(S?.columns??80)-i);kn(()=>{d.current!==e?(l(g.length),b.current=null):l(j=>lo(j,g.length)),d.current=e},[e,g.length]),kn(()=>{k(j=>{let P=j;X<P?P=X:X>=P+ie&&(P=X-ie+1);let N=D[H]??0,R=X===N?N+1:N,W=Math.max(0,R-ie);return P>W&&(P=W),P<0&&(P=0),P})},[ie,X,H,D]);let z=wn((j,P)=>{d.current=j,t(j),l(P),b.current=null},[t]),$e=wn(async(j,P)=>{if(!n)return;let{row:N,col:R}=Sn(a,$,D),W=h[N]??[],E=D[N]??0,he=h.length>1;if(r&&(P.meta&&P.return||P.ctrl&&j==="j"||P.shift&&P.return)){let _=[...g.slice(0,a),`
66
+ `,...g.slice(a)].join("");z(_,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&N>0?l($[N]-1):l($[N]+Oo(W,R)),b.current=null):(R===0&&N>0?l($[N]-1):l(_=>lo(_-1,g.length)),b.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=E&&N<h.length-1?l($[N+1]):l($[N]+Cn(W,R)),b.current=null):(R>=E&&N<h.length-1?l($[N+1]):l(_=>lo(_+1,g.length)),b.current=null);return}if(r&&he&&P.upArrow){let _=b.current??R,p=Math.max(0,N-1),re=Math.min(_,D[p]??0);l(($[p]??0)+re),b.current=_;return}if(r&&he&&P.downArrow){let _=b.current??R,p=Math.min(h.length-1,N+1),re=Math.min(_,D[p]??0);l(($[p]??0)+re),b.current=_;return}if(P.ctrl){if(j==="a"){l($[N]??0),b.current=null;return}if(j==="e"){l(($[N]??0)+E),b.current=null;return}if(j==="u"){if(R>0){let _=$[N]??0,p=[...g.slice(0,_),...g.slice(a)].join("");z(p,_)}return}if(j==="k"){if(R<E){let _=($[N]??0)+E,p=[...g.slice(0,a),...g.slice(_)].join("");z(p,a)}return}if(j==="w"){if(R===0&&N>0){let p=[...g.slice(0,a-1),...g.slice(a)].join("");z(p,a-1);return}let _=Oo(W,R);if(_!==R){let p=($[N]??0)+_,re=[...g.slice(0,p),...g.slice(a)].join("");z(re,p)}return}if(j==="d"){if(a<g.length){let _=[...g.slice(0,a),...g.slice(a+1)].join("");z(_,a)}return}return}if(P.meta){j==="b"?(R===0&&N>0?l($[N]-1):l($[N]+Oo(W,R)),b.current=null):j==="f"&&(R>=E&&N<h.length-1?l($[N+1]):l($[N]+Cn(W,R)),b.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let _=[...g.slice(0,a-1),...g.slice(a)].join("");z(_,a-1);return}if(!(P.tab||P.escape)&&j.length>0){let _=r?j.replace(/\r\n/g,`
67
67
  `).replace(/\r/g,`
68
- `):j.replace(/\r?\n/g,"");if(!L||(L=L.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!L))return;if((L.length>=ir||L.includes(`
69
- `))&&s){let q=!1,A={text:L,preventDefault:()=>{q=!0}};if(await Promise.resolve(s(A)),q)return}let ie=Do(L),ke=[...m.slice(0,a),...ie,...m.slice(a)].join("");Y(ke,a+ie.length)}},[m,a,n,D,T,h,r,s,o,Y,e]);return nr(Se,{isActive:n}),Ro(or,{flexDirection:"column",children:h.map((j,P)=>{let E=P===V,W=(E&&Z===j.length?[...j," "]:j).slice(C,C+ae),_=W.join("");if(!E)return Ro(hn,{children:_||" "},P);let he=lo(Z-C,Math.max(0,W.length-1)),L=W.slice(0,he).join(""),p=W[he]??" ",ie=W.slice(he+1).join(""),A=`${L}\x1B[7m${p}\x1B[27m${ie}`;return Ro(hn,{children:A},P)})})}import{Box as qe,Text as ft}from"ink";import Fo from"react";import{Text as Be}from"ink";import ar from"react";import{Fragment as ur,jsx as Je,jsxs as vn}from"react/jsx-runtime";var Uo=2,jo=1,Bo=2,lr=1,Sn=3,Tn=4,cr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Je(Be,{color:n,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>r&&i.push(Je(Be,{color:n,children:e.slice(r,l.index)},`t-${r}`));let d=l[0],C=null,x=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Uo*2)C=Je(Be,{bold:!0,color:n,children:d.slice(Uo,-Uo)},x);else if(d.length>jo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(l.index-1,l.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(l.index-2,l.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))C=Je(Be,{italic:!0,color:n,children:d.slice(jo,-jo)},x);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Bo*2)C=Je(Be,{strikethrough:!0,color:n,children:d.slice(Bo,-Bo)},x);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>lr){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(C=Je(Be,{color:s,children:b[2]},x))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let $=b[1],m=b[2];C=vn(Be,{color:n,children:[$,vn(Be,{color:o,children:[" (",m,")"]})]},x)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Sn+Tn-1?C=Je(Be,{underline:!0,color:n,children:d.slice(Sn,-Tn)},x):d.match(/^https?:\/\//)&&(C=Je(Be,{color:o,children:d},x))}catch{C=null}i.push(C??Je(Be,{color:n,children:d},x)),r=a.lastIndex}return r<e.length&&i.push(Je(Be,{color:n,children:e.slice(r)},`t-${r}`)),Je(ur,{children:i.filter(d=>d!==null)})},Bt=ar.memo(cr);import{Fragment as yr,jsx as we,jsxs as Nn}from"react/jsx-runtime";var dr=1,An=1,fr=1,pr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],C=!1,x=!0,b=[],$="";function m(h){h&&(d.push(h),x=!1)}return o.forEach((h,T)=>{let D=`line-${T}`;if(C){let P=h.match(n);P&&P[1].startsWith($[0])&&P[1].length>=$.length?(m(we(In,{content:b},D)),C=!1,b=[],$=""):b.push(h);return}let V=h.match(n),Z=h.match(s),ae=h.match(i),Y=h.match(r),Se=h.match(a),j=h.match(l);if(V)C=!0,$=V[1];else if(Se)m(we(qe,{children:we(ft,{dimColor:!0,children:"---"})},D));else if(Z){let P=Z[1].length,E=Z[2],R=P<=2?"cyan":"blue";m(we(qe,{children:we(ft,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:we(Bt,{text:E,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},D))}else if(j){let P=j[1];m(we(qe,{paddingLeft:1,children:Nn(ft,{dimColor:!0,children:["> ",we(Bt,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},D))}else if(ae){let P=ae[1],E=ae[2],R=ae[3];m(we(Pn,{itemText:R,type:"ul",marker:E,leadingWhitespace:P},D))}else if(Y){let P=Y[1],E=Y[2],R=Y[3];m(we(Pn,{itemText:R,type:"ol",marker:E,leadingWhitespace:P},D))}else h.trim().length===0?x||(d.push(we(qe,{height:dr},`spacer-${T}`)),x=!0):m(we(qe,{children:we(ft,{wrap:"wrap",children:we(Bt,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},D))}),C&&m(we(In,{content:b},"line-eof")),we(yr,{children:d})},gr=({content:e})=>{let t=e.join(`
70
- `);return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},In=Fo.memo(gr),hr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return Nn(qe,{paddingLeft:r+fr,flexDirection:"row",children:[we(qe,{width:i,children:we(ft,{children:n})}),we(qe,{flexGrow:pr,children:we(ft,{wrap:"wrap",children:we(Bt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Pn=Fo.memo(hr),Wo=Fo.memo(mr);import{execFile as wr}from"child_process";import kr from"fs";import St from"fs/promises";import En from"os";import fo from"path";import{promisify as xr}from"util";var uo=xr(wr);async function br(){let e=fo.join(En.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
68
+ `):j.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=ar||_.includes(`
69
+ `))&&s){let K=!1,A={text:_,preventDefault:()=>{K=!0}};if(await Promise.resolve(s(A)),K)return}let re=Do(_),ke=[...g.slice(0,a),...re,...g.slice(a)].join("");z(ke,a+re.length)}},[g,a,n,D,$,h,r,s,o,z,e]);return sr($e,{isActive:n}),Ro(nr,{flexDirection:"column",children:h.map((j,P)=>{let N=P===H,W=(N&&X===j.length?[...j," "]:j).slice(C,C+ie),E=W.join("");if(!N)return Ro(yn,{children:E||" "},P);let he=lo(X-C,Math.max(0,W.length-1)),_=W.slice(0,he).join(""),p=W[he]??" ",re=W.slice(he+1).join(""),A=`${_}\x1B[7m${p}\x1B[27m${re}`;return Ro(yn,{children:A},P)})})}import{Box as qe,Text as ft}from"ink";import Fo from"react";import{Text as Be}from"ink";import lr from"react";import{Fragment as dr,jsx as Je,jsxs as vn}from"react/jsx-runtime";var Uo=2,jo=1,Bo=2,cr=1,Tn=3,In=4,ur=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Je(Be,{color:n,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>r&&i.push(Je(Be,{color:n,children:e.slice(r,l.index)},`t-${r}`));let d=l[0],C=null,k=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Uo*2)C=Je(Be,{bold:!0,color:n,children:d.slice(Uo,-Uo)},k);else if(d.length>jo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(l.index-1,l.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(l.index-2,l.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))C=Je(Be,{italic:!0,color:n,children:d.slice(jo,-jo)},k);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Bo*2)C=Je(Be,{strikethrough:!0,color:n,children:d.slice(Bo,-Bo)},k);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>cr){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(C=Je(Be,{color:s,children:b[2]},k))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let S=b[1],g=b[2];C=vn(Be,{color:n,children:[S,vn(Be,{color:o,children:[" (",g,")"]})]},k)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Tn+In-1?C=Je(Be,{underline:!0,color:n,children:d.slice(Tn,-In)},k):d.match(/^https?:\/\//)&&(C=Je(Be,{color:o,children:d},k))}catch{C=null}i.push(C??Je(Be,{color:n,children:d},k)),r=a.lastIndex}return r<e.length&&i.push(Je(Be,{color:n,children:e.slice(r)},`t-${r}`)),Je(dr,{children:i.filter(d=>d!==null)})},Bt=lr.memo(ur);import{Fragment as wr,jsx as we,jsxs as En}from"react/jsx-runtime";var fr=1,Nn=1,pr=1,gr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return we(qe,{paddingLeft:Nn,flexDirection:"column",children:we(ft,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],C=!1,k=!0,b=[],S="";function g(h){h&&(d.push(h),k=!1)}return o.forEach((h,$)=>{let D=`line-${$}`;if(C){let P=h.match(n);P&&P[1].startsWith(S[0])&&P[1].length>=S.length?(g(we(Pn,{content:b},D)),C=!1,b=[],S=""):b.push(h);return}let H=h.match(n),X=h.match(s),ie=h.match(i),z=h.match(r),$e=h.match(a),j=h.match(l);if(H)C=!0,S=H[1];else if($e)g(we(qe,{children:we(ft,{dimColor:!0,children:"---"})},D));else if(X){let P=X[1].length,N=X[2],R=P<=2?"cyan":"blue";g(we(qe,{children:we(ft,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:we(Bt,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},D))}else if(j){let P=j[1];g(we(qe,{paddingLeft:1,children:En(ft,{dimColor:!0,children:["> ",we(Bt,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},D))}else if(ie){let P=ie[1],N=ie[2],R=ie[3];g(we(An,{itemText:R,type:"ul",marker:N,leadingWhitespace:P},D))}else if(z){let P=z[1],N=z[2],R=z[3];g(we(An,{itemText:R,type:"ol",marker:N,leadingWhitespace:P},D))}else h.trim().length===0?k||(d.push(we(qe,{height:fr},`spacer-${$}`)),k=!0):g(we(qe,{children:we(ft,{wrap:"wrap",children:we(Bt,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},D))}),C&&g(we(Pn,{content:b},"line-eof")),we(wr,{children:d})},hr=({content:e})=>{let t=e.join(`
70
+ `);return we(qe,{paddingLeft:Nn,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},Pn=Fo.memo(hr),yr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return En(qe,{paddingLeft:r+pr,flexDirection:"row",children:[we(qe,{width:i,children:we(ft,{children:n})}),we(qe,{flexGrow:gr,children:we(ft,{wrap:"wrap",children:we(Bt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},An=Fo.memo(yr),Wo=Fo.memo(mr);import{execFile as kr}from"child_process";import xr from"fs";import $t from"fs/promises";import _n from"os";import fo from"path";import{promisify as br}from"util";var uo=br(kr);async function Cr(){let e=fo.join(_n.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
71
71
  set imageData to the clipboard as "PNGf"
72
72
  set fileRef to open for access POSIX file "${e}" with write permission
73
73
  set eof fileRef to 0
74
74
  write imageData to fileRef
75
75
  close access fileRef
76
- `;return await uo("osascript",["-e",t]),(await St.stat(e)).size===0?void 0:{buffer:await St.readFile(e),mime:"image/png"}}catch{return}finally{try{kr.existsSync(e)&&await St.unlink(e)}catch{}}}async function Cr(){try{let e=`
76
+ `;return await uo("osascript",["-e",t]),(await $t.stat(e)).size===0?void 0:{buffer:await $t.readFile(e),mime:"image/png"}}catch{return}finally{try{xr.existsSync(e)&&await $t.unlink(e)}catch{}}}async function Sr(){try{let e=`
77
77
  Add-Type -AssemblyName System.Windows.Forms
78
78
  $img = [System.Windows.Forms.Clipboard]::GetImage()
79
79
  if ($img) {
@@ -81,44 +81,44 @@ You have access to filesystem tools that allow you to interact with the user's l
81
81
  $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
82
82
  [System.Convert]::ToBase64String($ms.ToArray())
83
83
  }
84
- `,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await uo("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function _n(){let e=En.platform();if(e==="darwin")return br();if(e==="win32")return Cr();if(e==="linux")return $r()}var Sr=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Ln(e){let t=fo.extname(e).toLowerCase();return Sr.has(t)}function Tr(e){let t=fo.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function po(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function Dn(e){let t=po(e);if(/^https?:\/\//.test(t))return!1;try{return await St.access(t),!0}catch{return!1}}async function On(e){let t=po(e);try{if(!(await St.stat(t)).isFile())return;let s=await St.readFile(t),n=Tr(t),i=fo.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Fe="\x1B[2m",re="\x1B[0m",Ie="\x1B[36m",Tt="\x1B[32m",Rn="\x1B[31m",gt="\x1B[38;2;59;91;204m",Mo="\x1B[38;2;126;200;248m",Jo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as Un}from"uuid";function jn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||Un()),[C,x]=ot(t),[b,$]=ot(!!e),[m,h]=ot(null),[T,D]=ot(""),[V,Z]=ot(!1),ae=Se=>{i(j=>[...j,{role:"system",content:Se}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:l,setChatId:d,currentChatTitle:C,setCurrentChatTitle:x,hasPersistedChat:b,setHasPersistedChat:$,credentials:m,setCredentials:h,currentResponse:T,setCurrentResponse:D,fullOutput:V,setFullOutput:Z,addSystemMessage:ae,startNewChat:Se=>{let j=Un();d(j),x(void 0),$(!1),i([]),Se&&ae(Se)}}}import{useEffect as vr,useState as Bn}from"react";function Fn(e){let[t,o]=Bn(null),[s,n]=Bn(!0);return vr(()=>{let i=!1;async function r(){try{let a=await pe();if(i)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof Qe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),n(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Ir,useState as Ft}from"react";function Wn(e){let[t,o]=Ft([]),[s,n]=Ft([]),[i,r]=Ft([]),[a,l]=Ft([]),[d,C]=Ft(!1);return Ir(()=>{if(!e)return;let x=!1;C(!0);async function b(){if(e)try{let $=new B,[m,h,T,D]=await Promise.all([$.getConnectors(e.accessToken,e.workspaceId),$.getModels(e.accessToken,e.workspaceId),$.getAgents(e.accessToken,e.workspaceId),$.getModelProviders(e.accessToken,e.workspaceId)]);if(x)return;o(m.connectors),n(h.models),r(T.agents),l(D.providers??[])}catch{}finally{x||C(!1)}}return b(),()=>{x=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import vt from"fs";import Jn from"path";import{useCallback as Pr}from"react";import{v4 as Ar}from"uuid";function Mn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
84
+ `,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await uo("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function Ln(){let e=_n.platform();if(e==="darwin")return Cr();if(e==="win32")return Sr();if(e==="linux")return $r()}var Tr=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Dn(e){let t=fo.extname(e).toLowerCase();return Tr.has(t)}function Ir(e){let t=fo.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function po(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function On(e){let t=po(e);if(/^https?:\/\//.test(t))return!1;try{return await $t.access(t),!0}catch{return!1}}async function Rn(e){let t=po(e);try{if(!(await $t.stat(t)).isFile())return;let s=await $t.readFile(t),n=Ir(t),i=fo.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Fe="\x1B[2m",se="\x1B[0m",ve="\x1B[36m",Tt="\x1B[32m",Un="\x1B[31m",mt="\x1B[38;2;59;91;204m",Mo="\x1B[38;2;126;200;248m",Jo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as jn}from"uuid";function Bn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||jn()),[C,k]=ot(t),[b,S]=ot(!!e),[g,h]=ot(null),[$,D]=ot(""),[H,X]=ot(!1),ie=$e=>{i(j=>[...j,{role:"system",content:$e}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:l,setChatId:d,currentChatTitle:C,setCurrentChatTitle:k,hasPersistedChat:b,setHasPersistedChat:S,credentials:g,setCredentials:h,currentResponse:$,setCurrentResponse:D,fullOutput:H,setFullOutput:X,addSystemMessage:ie,startNewChat:$e=>{let j=jn();d(j),k(void 0),S(!1),i([]),$e&&ie($e)}}}import{useEffect as vr,useState as Fn}from"react";function Wn(e){let[t,o]=Fn(null),[s,n]=Fn(!0);return vr(()=>{let i=!1;async function r(){try{let a=await fe();if(i)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof Qe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),n(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Pr,useState as Ft}from"react";function Mn(e){let[t,o]=Ft([]),[s,n]=Ft([]),[i,r]=Ft([]),[a,l]=Ft([]),[d,C]=Ft(!1);return Pr(()=>{if(!e)return;let k=!1;C(!0);async function b(){if(e)try{let S=new B,[g,h,$,D]=await Promise.all([S.getConnectors(e.accessToken,e.workspaceId),S.getModels(e.accessToken,e.workspaceId),S.getAgents(e.accessToken,e.workspaceId),S.getModelProviders(e.accessToken,e.workspaceId)]);if(k)return;o(g.connectors),n(h.models),r($.agents),l(D.providers??[])}catch{}finally{k||C(!1)}}return b(),()=>{k=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import It from"fs";import Gn from"path";import{useCallback as Ar}from"react";import{v4 as Nr}from"uuid";function Jn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
85
85
  `);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function ht(e,t=!1){let o=[];for(let s of e)if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="reasoning"&&s.text)t?o.push(`${Fe}[Thinking]
86
- ${s.text}${re}`):o.push(`${Fe}[Thinking...]${re}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${Ie}\u250C\u2500 Tool: ${s.toolName}${re}`),s.args){let i=JSON.stringify(s.args,null,t?2:void 0),r=t||i.length<=100?i:i.slice(0,100)+"...";n.push(`${Fe}\u2502 Args: ${r}${re}`)}s.result!==void 0?(n.push(`${Tt}\u2502 Result: ${Mn(s.result,t)}${re}`),n.push(`${Ie}\u2514\u2500 completed${re}`)):n.push(`${Ie}\u2514\u2500${re}`),o.push(n.join(`
87
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${Ie}\u250C\u2500 Tool: ${n}${re}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Fe}\u2502 Input: ${a}${re}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Tt}\u2502 Output: ${Mn(s.output,t)}${re}`),i.push(`${Ie}\u2514\u2500 completed${re}`)):s.state==="error"?i.push(`${Ie}\u2514\u2500 failed${re}`):i.push(`${Ie}\u2514\u2500${re}`),o.push(i.join(`
86
+ ${s.text}${se}`):o.push(`${Fe}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${ve}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let i=JSON.stringify(s.args,null,t?2:void 0),r=t||i.length<=100?i:i.slice(0,100)+"...";n.push(`${Fe}\u2502 Args: ${r}${se}`)}s.result!==void 0?(n.push(`${Tt}\u2502 Result: ${Jn(s.result,t)}${se}`),n.push(`${ve}\u2514\u2500 completed${se}`)):n.push(`${ve}\u2514\u2500${se}`),o.push(n.join(`
87
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${ve}\u250C\u2500 Tool: ${n}${se}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Fe}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Tt}\u2502 Output: ${Jn(s.output,t)}${se}`),i.push(`${ve}\u2514\u2500 completed${se}`)):s.state==="error"?i.push(`${ve}\u2514\u2500 failed${se}`):i.push(`${ve}\u2514\u2500${se}`),o.push(i.join(`
88
88
  `))}return o.join(`
89
89
 
90
- `).trim()}var mo=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=`
90
+ `).trim()}var go=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let s=o.toolName.replace(/__/g," "),n=`
91
91
 
92
- ${Ie}\u250C\u2500 Tool: ${s}${re}`;if(o.args){let i=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
93
- ${Fe}\u2502 Input: ${i}${re}`}if(o.output){let i=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
94
- ${Tt}\u2502 Output: ${i}${re}`}else if(o.status==="executing"){let i=o.startedAt??Date.now(),r=Math.floor((Date.now()-i)/1e3);n+=`
95
- ${Ie}\u2502${re} (executing... ${r}s)`}else o.status==="preparing"&&(n+=`
96
- ${Ie}\u2502${re} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,s]of this.pendingToolCalls){let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
92
+ ${ve}\u250C\u2500 Tool: ${s}${se}`;if(o.args){let i=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
93
+ ${Fe}\u2502 Input: ${i}${se}`}if(o.output){let i=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
94
+ ${Tt}\u2502 Output: ${i}${se}`}else if(o.status==="executing"){let i=o.startedAt??Date.now(),r=Math.floor((Date.now()-i)/1e3);n+=`
95
+ ${ve}\u2502${se} (executing... ${r}s)`}else o.status==="preparing"&&(n+=`
96
+ ${ve}\u2502${se} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,s]of this.pendingToolCalls){let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
97
97
 
98
- ${Ie}\u250C\u2500 Tool: ${n}${re}`,i&&(t+=`
99
- ${Fe}\u2502 Input: ${i}${re}`),t+=`
100
- ${Ie}\u2514\u2500 completed${re}
98
+ ${ve}\u250C\u2500 Tool: ${n}${se}`,i&&(t+=`
99
+ ${Fe}\u2502 Input: ${i}${se}`),t+=`
100
+ ${ve}\u2514\u2500 completed${se}
101
101
  `,this.pendingToolCalls.delete(o)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.args=(o.args||"")+t.inputTextDelta,o.status="executing",o.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output="",o.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output=(o.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,o){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"",r=(s.output||"").length>200?(s.output||"").slice(0,200)+"...":s.output||"";return o+=`
102
102
 
103
- ${Ie}\u250C\u2500 Tool: ${n}${re}`,i&&(o+=`
104
- ${Fe}\u2502 Input: ${i}${re}`),o+=`
105
- ${Tt}\u2502 Output: ${r}${re}`,o+=`
106
- ${Ie}\u2514\u2500 completed${re}
103
+ ${ve}\u250C\u2500 Tool: ${n}${se}`,i&&(o+=`
104
+ ${Fe}\u2502 Input: ${i}${se}`),o+=`
105
+ ${Tt}\u2502 Output: ${r}${se}`,o+=`
106
+ ${ve}\u2514\u2500 completed${se}
107
107
  `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),i=t.errorText||"Unknown error",r=i.length>200?i.slice(0,200)+"...":i;return o+=`
108
108
 
109
- ${Ie}\u250C\u2500 Tool: ${n}${re}`,o+=`
110
- ${Rn}\u2502 Error: ${r}${re}`,o+=`
111
- ${Ie}\u2514\u2500 failed${re}
112
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Wt=Jn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function le(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
109
+ ${ve}\u250C\u2500 Tool: ${n}${se}`,o+=`
110
+ ${Un}\u2502 Error: ${r}${se}`,o+=`
111
+ ${ve}\u2514\u2500 failed${se}
112
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Wt=Gn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
113
113
  DATA: ${JSON.stringify(t,null,2)}`),s+=`
114
- `;try{vt.appendFileSync(Wt,s)}catch{}}function Nr(){try{if(vt.existsSync(Wt)&&vt.unlinkSync(Wt),process.env.DEBUG){let e=Jn.dirname(Wt);vt.existsSync(e)||vt.mkdirSync(e,{recursive:!0}),vt.writeFileSync(Wt,`=== Debug session started at ${new Date().toISOString()} ===
115
- `)}}catch{}}function go(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Gn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:C,setMessages:x,setState:b,setCurrentResponse:$,setCredentials:m,setHasPersistedChat:h,getFileIds:T,clearFiles:D}){let V=d?no():void 0,Z=d?so():void 0;return{sendMessage:Pr(async(Y,Se,j)=>{Nr(),le("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:V?.length});let P=Se||t?.accessToken,E=j||t?.workspaceId;if(!P||!E)try{let _=await pe();P=_.accessToken,E=_.workspaceId,m(_)}catch(_){if(_ instanceof Qe){if(_.code==="not-logged-in"){b({status:"not-logged-in"});return}if(_.code==="no-workspace"){b({status:"no-workspace"});return}}let he=_ instanceof Error?_.message:"Authentication failed";b({status:"error",message:he});return}else try{let _=await dt();_!==P&&(P=_,m({accessToken:_,workspaceId:E}))}catch(_){if(_ instanceof Qe&&_.code==="not-logged-in"){b({status:"not-logged-in"});return}let he=_ instanceof Error?_.message:"Authentication failed";b({status:"error",message:he});return}x(_=>[..._,{role:"user",content:Y}]),b({status:"sending"}),$("");let R=null,W=null;try{let _=new B,he=T?.()??[],L={id:e,message:{id:Ar(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};he.length>0&&(L.fileIds=he),o?L.agentId=o:(s&&(L.model=s),L.connectorIds=n??[],L.enableSandbox=i,L.enableWebSearch=r,L.enableImageGeneration=a,L.enableChart=l),V&&(L.clientTools=V),Z&&(L.clientToolSystemPrompt=Z);let p=await _.chat(P,E,L);if(!p.ok){let F=await p.text();throw new Error(`API error ${p.status}: ${F}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let ie=new TextDecoder,ke="",q="",A="",te="",ee="",me="",ce="",M=new mo,Q=[],z=[],fe=[],Te=()=>{let F=M.hasExecuting();F&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}$(q+M.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:se}=await R.read();if(F)break;ke+=ie.decode(se,{stream:!0});let O=ke.split(`
116
- `);ke=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(le(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":te=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,$(`${Fe}[Thinking...]${re}
117
- ${A}`)),w.providerMetadata?.anthropic?.signature&&(ee=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let v={type:"reasoning",id:te,text:A,state:"done"};ee&&(v.providerMetadata={anthropic:{signature:ee}}),z.push(v),le("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$("");break;case"text-delta":w.delta&&(M.hasPending()&&(q=M.flushPending(q)),q+=w.delta,me+=w.delta,$(q));break;case"tool-input-start":{let v=M.handleToolInputStart(w);v&&$(q+v),Te();break}case"tool-input-delta":{let v=M.handleToolInputDelta(w);v&&$(q+v),Te();break}case"tool-call":case"tool-input-available":{if(le(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?tt(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let v=go(w.args??w.input);z.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:v}),le("Added tool to messageParts",{messagePartsCount:z.length})}if(d&&w.toolCallId&&w.toolName&&tt(w.toolName)){let v=go(w.args??w.input);Q.push({toolCallId:w.toolCallId,toolName:w.toolName,args:v}),le("Added to pendingClientTools",{pendingCount:Q.length,pendingClientTools:Q}),$(q+M.buildToolDisplay()+`
118
- [Executing ${w.toolName} locally...]`)}else le("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?tt(w.toolName):!1});break}case"tool-output-start":{let v=M.handleToolOutputStart(w);v&&$(q+v),Te();break}case"tool-output-delta":{let v=M.handleToolOutputDelta(w);v&&$(q+v),Te();break}case"tool-output-end":{let v=M.handleToolOutputEnd(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let v=M.handleToolError(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"start":w.messageId&&(ce=w.messageId,le("Captured messageId from start event",{messageId:ce}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(me){let F=z.findIndex(O=>O.type!=="reasoning"),se=F===-1?z.length:F;z.splice(se,0,{type:"text",text:me}),le("Added accumulated text to messageParts",{textLength:me.length,insertIndex:se})}for(le("=== Initial stream ended ===",{pendingClientToolsCount:Q.length,pendingClientTools:Q,messagePartsCount:z.length,messageParts:z.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Q.length>0;){le("=== Starting pending tools execution loop ===",{pendingCount:Q.length});let F=[];for(let f of Q){le(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),M.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),M.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),$(q+M.buildToolDisplay()),Te();let w=await ro(f.toolName,f.args);le(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let v=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:v}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let oe=M.handleToolOutputEnd({toolCallId:f.toolCallId},q);oe&&(q=oe.fullResponse)}else{let oe=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},q);oe&&(q=oe.fullResponse)}$(q+M.buildToolDisplay()),Te()}Q.length=0;for(let f of F){let w=z.find(v=>(v.type==="tool-input-available"||v.type==="tool-call")&&v.toolCallId===f.toolCallId);if(w){let v=[];for(let U of f.content)U.type==="text"?v.push(U.text):U.type==="image"?v.push("[Image]"):U.type==="audio"?v.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&v.push("[Resource]");let oe=v.join(`
119
- `);fe.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:oe,isError:f.isError})}}if(le("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let se={id:e,clientToolResults:F};o?se.agentId=o:(s&&(se.model=s),se.connectorIds=n??[],se.enableSandbox=i,se.enableWebSearch=r,se.enableImageGeneration=a,se.enableChart=l),V&&(se.clientTools=V),Z&&(se.clientToolSystemPrompt=Z),le("=== Sending continuation request ===",{chatId:e,hasAgentId:!!se.agentId,hasModel:!!se.model,clientToolResultsCount:F.length});let O=await _.chat(P,E,se);if(le("=== 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(le("=== Processing continuation stream ==="),R=O.body.getReader(),z.length=0,me="",A="",te="",ee="";;){let{done:f,value:w}=await R.read();if(f){le("=== Continuation stream done ===");break}ke+=ie.decode(w,{stream:!0});let v=ke.split(`
120
- `);ke=v.pop()||"";for(let oe of v)if(oe.trim()!=="data: [DONE]"&&oe.startsWith("data: "))try{let U=JSON.parse(oe.slice(6));switch(le(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":te=U.id||"0",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,$(`${Fe}[Thinking...]${re}
121
- ${A}`)),U.providerMetadata?.anthropic?.signature&&(ee=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Ce={type:"reasoning",id:te,text:A,state:"done"};ee&&(Ce.providerMetadata={anthropic:{signature:ee}}),z.push(Ce),le("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$(q);break;case"text-delta":U.delta&&(q+=U.delta,me+=U.delta,$(q));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Ce=go(U.args??U.input);z.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Ce})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Ce=go(U.args??U.input);Q.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Ce}),le("Continuation: Added to pendingClientTools",{pendingCount:Q.length})}break;case"finish":le("Continuation finish event",U);break}}catch{}}if(me){let f=z.findIndex(v=>v.type!=="reasoning"),w=f===-1?z.length:f;z.splice(w,0,{type:"text",text:me})}le("=== Continuation stream processing complete ===",{pendingClientToolsCount:Q.length,messagePartsCount:z.length,fullResponseLength:q.length})}if(d&&V&&V.length>0){let F=[];for(let O of fe)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 z)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let se=ht(F,C);le("=== Using formatted parts for local tools ===",{executedToolsCount:fe.length,textPartsCount:z.filter(O=>O.type==="text").length,contentLength:se.length}),x(O=>[...O,{role:"assistant",content:se,parts:F}])}else{le("=== Fetching message from API ===",{fullResponseLength:q.length,fullResponsePreview:q.slice(0,200)});try{let{messages:F}=await _.getMessages(P,E,e,10);le("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let se=F.find(O=>O.role==="assistant");if(se){let O=se.parts,f=ht(O,C);le("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),x(w=>[...w,{role:"assistant",content:f,parts:O}])}else le("=== No assistant message found, using fallback ==="),x(O=>[...O,{role:"assistant",content:q}])}catch(F){le("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),x(se=>[...se,{role:"assistant",content:q}])}}le("=== Message handling complete ==="),$(""),b({status:"ready"}),h(!0),he.length>0&&D?.()}catch(_){le("=== ERROR ===",{message:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0});let he=_ instanceof Error?_.message:"Failed to send message";b({status:"error",message:he})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,o,s,n,i,r,a,l,d,V,Z,C,x,b,$,m,h,T,D])}}import{useState as Mt}from"react";var Hn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},Vn=new Map(Object.values(Hn).map(e=>[e.apiKey,e.name]));function Kn(){return Object.values(Hn)}function qn(e,t,o,s,n){let[i,r]=Mt(e),[a,l]=Mt(t),[d,C]=Mt(o),[x,b]=Mt(s),[$,m]=Mt(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:C,chart:x,setChart:b,fileSystem:$,setFileSystem:m,capabilityLabelMap:Vn}}import{useEffect as Er,useState as _r}from"react";function zn(e,t){let[o,s]=_r(null);return Er(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new B().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Go}from"react";function Yn(e,t,o){let[s,n]=Go(e),[i,r]=Go(t),[a,l]=Go(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Dr,useInput as Or}from"ink";import{useCallback as nt,useRef as Rr,useState as De}from"react";import{spawn as Lr}from"child_process";function Xn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let i=Lr(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Zn=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function Qn(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Zn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Zn}function es(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(s){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"chats":case"c":return{type:"chats"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:t}}}var ts=`Available commands:
114
+ `;try{It.appendFileSync(Wt,s)}catch{}}function Er(){try{if(It.existsSync(Wt)&&It.unlinkSync(Wt),process.env.DEBUG){let e=Gn.dirname(Wt);It.existsSync(e)||It.mkdirSync(e,{recursive:!0}),It.writeFileSync(Wt,`=== Debug session started at ${new Date().toISOString()} ===
115
+ `)}}catch{}}function mo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Hn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:C,setMessages:k,setState:b,setCurrentResponse:S,setCredentials:g,setHasPersistedChat:h,getFileIds:$,clearFiles:D}){let H=d?no():void 0,X=d?so():void 0;return{sendMessage:Ar(async(z,$e,j)=>{Er(),ae("=== sendMessage called ===",{text:z,localTools:d,clientToolsCount:H?.length});let P=$e||t?.accessToken,N=j||t?.workspaceId;if(!P||!N)try{let E=await fe();P=E.accessToken,N=E.workspaceId,g(E)}catch(E){if(E instanceof Qe){if(E.code==="not-logged-in"){b({status:"not-logged-in"});return}if(E.code==="no-workspace"){b({status:"no-workspace"});return}}let he=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:he});return}else try{let E=await dt();E!==P&&(P=E,g({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof Qe&&E.code==="not-logged-in"){b({status:"not-logged-in"});return}let he=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:he});return}k(E=>[...E,{role:"user",content:z}]),b({status:"sending"}),S("");let R=null,W=null;try{let E=new B,he=$?.()??[],_={id:e,message:{id:Nr(),createdAt:new Date,role:"user",parts:[{type:"text",text:z}]}};he.length>0&&(_.fileIds=he),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=i,_.enableWebSearch=r,_.enableImageGeneration=a,_.enableChart=l),H&&(_.clientTools=H),X&&(_.clientToolSystemPrompt=X);let p=await E.chat(P,N,_);if(!p.ok){let F=await p.text();throw new Error(`API error ${p.status}: ${F}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let re=new TextDecoder,ke="",K="",A="",ee="",Q="",pe="",le="",M=new go,Z=[],q=[],de=[],Te=()=>{let F=M.hasExecuting();F&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}S(K+M.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:ne}=await R.read();if(F)break;ke+=re.decode(ne,{stream:!0});let O=ke.split(`
116
+ `);ke=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,S(`${Fe}[Thinking...]${se}
117
+ ${A}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let T={type:"reasoning",id:ee,text:A,state:"done"};Q&&(T.providerMetadata={anthropic:{signature:Q}}),q.push(T),ae("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S("");break;case"text-delta":w.delta&&(M.hasPending()&&(K=M.flushPending(K)),K+=w.delta,pe+=w.delta,S(K));break;case"tool-input-start":{let T=M.handleToolInputStart(w);T&&S(K+T),Te();break}case"tool-input-delta":{let T=M.handleToolInputDelta(w);T&&S(K+T),Te();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?tt(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let T=mo(w.args??w.input);q.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added tool to messageParts",{messagePartsCount:q.length})}if(d&&w.toolCallId&&w.toolName&&tt(w.toolName)){let T=mo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),S(K+M.buildToolDisplay()+`
118
+ [Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?tt(w.toolName):!1});break}case"tool-output-start":{let T=M.handleToolOutputStart(w);T&&S(K+T),Te();break}case"tool-output-delta":{let T=M.handleToolOutputDelta(w);T&&S(K+T),Te();break}case"tool-output-end":{let T=M.handleToolOutputEnd(w,K);T&&(K=T.fullResponse,S(K+T.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let T=M.handleToolError(w,K);T&&(K=T.fullResponse,S(K+T.toolDisplay)),Te();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let F=q.findIndex(O=>O.type!=="reasoning"),ne=F===-1?q.length:F;q.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:q.length,messageParts:q.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let F=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),M.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),M.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),S(K+M.buildToolDisplay()),Te();let w=await ro(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let T=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:T}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=M.handleToolOutputEnd({toolCallId:f.toolCallId},K);te&&(K=te.fullResponse)}else{let te=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},K);te&&(K=te.fullResponse)}S(K+M.buildToolDisplay()),Te()}Z.length=0;for(let f of F){let w=q.find(T=>(T.type==="tool-input-available"||T.type==="tool-call")&&T.toolCallId===f.toolCallId);if(w){let T=[];for(let U of f.content)U.type==="text"?T.push(U.text):U.type==="image"?T.push("[Image]"):U.type==="audio"?T.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&T.push("[Resource]");let te=T.join(`
119
+ `);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let ne={id:e,clientToolResults:F};o?ne.agentId=o:(s&&(ne.model=s),ne.connectorIds=n??[],ne.enableSandbox=i,ne.enableWebSearch=r,ne.enableImageGeneration=a,ne.enableChart=l),H&&(ne.clientTools=H),X&&(ne.clientToolSystemPrompt=X),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:F.length});let O=await E.chat(P,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),R=O.body.getReader(),q.length=0,pe="",A="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}ke+=re.decode(w,{stream:!0});let T=ke.split(`
120
+ `);ke=T.pop()||"";for(let te of T)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let U=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":ee=U.id||"0",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,S(`${Fe}[Thinking...]${se}
121
+ ${A}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Se={type:"reasoning",id:ee,text:A,state:"done"};Q&&(Se.providerMetadata={anthropic:{signature:Q}}),q.push(Se),ae("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S(K);break;case"text-delta":U.delta&&(K+=U.delta,pe+=U.delta,S(K));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Se=mo(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Se})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Se=mo(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Se}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(T=>T.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:K.length})}if(d&&H&&H.length>0){let F=[];for(let O of de)F.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of q)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=ht(F,C);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(O=>O.type==="text").length,contentLength:ne.length}),k(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:K.length,fullResponsePreview:K.slice(0,200)});try{let{messages:F}=await E.getMessages(P,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=ht(O,C);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),k(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),k(O=>[...O,{role:"assistant",content:K}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),k(ne=>[...ne,{role:"assistant",content:K}])}}ae("=== Message handling complete ==="),S(""),b({status:"ready"}),h(!0),he.length>0&&D?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let he=E instanceof Error?E.message:"Failed to send message";b({status:"error",message:he})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,o,s,n,i,r,a,l,d,H,X,C,k,b,S,g,h,$,D])}}import{useState as Mt}from"react";var Vn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},Kn=new Map(Object.values(Vn).map(e=>[e.apiKey,e.name]));function qn(){return Object.values(Vn)}function zn(e,t,o,s,n){let[i,r]=Mt(e),[a,l]=Mt(t),[d,C]=Mt(o),[k,b]=Mt(s),[S,g]=Mt(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:C,chart:k,setChart:b,fileSystem:S,setFileSystem:g,capabilityLabelMap:Kn}}import{useEffect as _r,useState as Lr}from"react";function Yn(e,t){let[o,s]=Lr(null);return _r(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new B().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Go}from"react";function Xn(e,t,o){let[s,n]=Go(e),[i,r]=Go(t),[a,l]=Go(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Or,useInput as Rr}from"ink";import{useCallback as nt,useRef as Ur,useState as De}from"react";import{spawn as Dr}from"child_process";function Zn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let i=Dr(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Qn=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function es(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Qn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Qn}function ts(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(s){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"chats":case"c":return{type:"chats"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:t}}}var os=`Available commands:
122
122
  /help, /h, /? Show this help message
123
123
  /clear, /cls, /new Start a new chat
124
124
  /model [name], /m Show current model or switch to [name]
@@ -142,96 +142,96 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
142
142
 
143
143
  Keyboard shortcuts:
144
144
  Ctrl+O Toggle full output mode
145
- Ctrl+C Exit`;function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:C,setCurrentAgentDetails:x,activeConnectorIds:b,setActiveConnectorIds:$,sandbox:m,setSandbox:h,webSearch:T,setWebSearch:D,imageGeneration:V,setImageGeneration:Z,chart:ae,setChart:Y,fileSystem:Se,setFileSystem:j,availableModels:P,availableAgents:E,availableConnectors:R,messages:W,hasPersistedChat:_,setHasPersistedChat:he,setMessages:L,addSystemMessage:p,startNewChat:ie,sendMessage:ke,setFullOutput:q,credentials:A,setCredentials:te,setState:ee,defaultCapabilities:me,capabilityLabelMap:ce,hasUploadingFiles:M=!1}){let{exit:Q}=Dr(),[z,fe]=De([]),[Te,F]=De(0),[se,O]=De(!1),[f,w]=De(null),[v,oe]=De([]),[U,Ce]=De(0),[rt,it]=De(new Set),[Re,at]=De(new Set),[To,Xt]=De([]),[We,wt]=De([]),[Ye,Zt]=De([]),[lt,vo]=De([]),[Ve,Xe]=De(null),[Qt,kt]=De(""),mt=Rr(!1),[ct,xt]=De(!1),bt=nt(async()=>{if(!A)return[];let I=new B,y=[],c;do{let u=await I.listAvailableSkills(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.skills),c=u.nextKey}while(c);return wt(y),y},[A]),Ct=nt(async()=>{if(!A)return[];let I=new B,y=[],c;do{let u=await I.getSchedules(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.schedules),c=u.nextKey}while(c);return Zt(y),y},[A]),_e=nt(async I=>{if(I==="model"){if(P.length===0){p("No models available.");return}let y=P.map(u=>({id:u.id,name:u.name,description:u.description}));oe(y);let c=r?y.findIndex(u=>u.id===r):-1;Ce(c>=0?c:0),w("model")}else if(I==="agent"){if(E.length===0){p("No agents available.");return}let y=E.map(u=>({id:u.id,name:u.name,description:u.description}));oe(y);let c=l?y.findIndex(u=>u.id===l):-1;Ce(c>=0?c:0),w("agent")}else if(I==="skills"){let y=We;if(y.length===0)try{y=await bt()}catch{p("Failed to load skills.");return}if(y.length===0){p("No skills available.");return}let c=y.map(u=>({id:u.id,name:u.name,description:u.description}));oe(c),Ce(0),w("skills")}else if(I==="schedules"){let y=Ye;if(y.length===0)try{y=await Ct()}catch{p("Failed to load schedules.");return}if(y.length===0){p("No schedules found.");return}let c=y.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));oe(c),Ce(0),w("schedules")}else if(I==="connectors"){if(R.length===0){p("No connectors available.");return}let y=R.map(c=>({id:c.id,name:c.name}));oe(y),Ce(0),it(new Set(b||[])),w("connectors")}else if(I==="capabilities"){let y=Kn().map(u=>({id:u.id,name:u.name,description:u.description}));oe(y),Ce(0);let c=new Set;m&&c.add("sandbox"),T&&c.add("webSearch"),V&&c.add("imageGeneration"),ae&&c.add("chart"),Se&&c.add("fileSystem"),at(c),w("capabilities")}else if(I==="chats"){if(!A){p("Not authenticated.");return}try{let y=new B,{chats:c}=await y.getChats(A.accessToken,A.workspaceId,20);if(c.length===0){p("No chats available.");return}Xt(c);let u=c.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));oe(u);let g=u.findIndex(S=>S.id===o);Ce(g>=0?g:0),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let y=H.getProfileNames(),c=H.getCurrentProfileName(),u=y.map(S=>({id:S,name:S,description:S===c?"(current)":void 0}));oe(u);let g=u.findIndex(S=>S.id===c);Ce(g>=0?g:0),w("profile")}O(!1),fe([])},[P,E,We,Ye,R,b,r,l,bt,Ct,m,T,V,ae,Se,A,o,p]),ye=nt(I=>{let y=ne.getAll(I);a(y.model?.default),d(void 0),x(null);let c=y.connectors?.defaults;$(c&&c.length>0?c:void 0);let u=y.capabilities;h(u?.sandbox??me.sandbox),D(u?.webSearch??me.webSearch),Z(u?.imageGeneration??me.imageGeneration),Y(u?.chart??me.chart);let g=y.localTools;j(g?.fileSystem??me.fileSystem)},[a,d,x,$,h,D,Z,Y,j,me]),Ze=nt(async()=>{try{let I=await pe();te({accessToken:I.accessToken,workspaceId:I.workspaceId}),ee({status:"ready"})}catch(I){if(te(null),I instanceof Qe){if(I.code==="not-logged-in"){ee({status:"not-logged-in"});return}if(I.code==="no-workspace"){ee({status:"no-workspace"});return}}let y=I instanceof Error?I.message:"Failed to authenticate";ee({status:"error",message:y})}},[te,ee]),$t=nt(async I=>{switch(I.type){case"help":return p(ts),!0;case"clear":return ie("Started a new chat."),!0;case"model":{if(I.value){let y=I.value.toLowerCase(),c=P.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id);else{let u=P.map(g=>g.name).join(", ");p(`Model "${I.value}" not found.
146
- Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return E.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=I.value.toLowerCase(),c=E.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=E.map(g=>g.name).join(", ");p(`Agent "${I.value}" not found.
147
- Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return _e("skills"),!0;let y=I.value.toLowerCase();return(We.length?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));p(g?`Skill: ${g.name}
148
- ${g.description}
149
- Provider: ${g.provider}
150
- Author: ${g.author.name}
151
- ID: ${g.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return _e("schedules"),!0;let y=I.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
152
- Agent: ${g.agent.name}
153
- Status: ${g.isActive?"Active":"Paused"}
154
- Repeat: ${S(g.config)}
155
- Next Run: ${k}
156
- ID: ${g.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(l){let c=C?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(g=>` - ${g.name}`).join(`
145
+ Ctrl+C Exit`;function Ho(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function ns({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:C,setCurrentAgentDetails:k,activeConnectorIds:b,setActiveConnectorIds:S,sandbox:g,setSandbox:h,webSearch:$,setWebSearch:D,imageGeneration:H,setImageGeneration:X,chart:ie,setChart:z,fileSystem:$e,setFileSystem:j,availableModels:P,availableAgents:N,availableConnectors:R,messages:W,hasPersistedChat:E,setHasPersistedChat:he,setMessages:_,addSystemMessage:p,startNewChat:re,sendMessage:ke,setFullOutput:K,credentials:A,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:M=!1}){let{exit:Z}=Or(),[q,de]=De([]),[Te,F]=De(0),[ne,O]=De(!1),[f,w]=De(null),[T,te]=De([]),[U,Se]=De(0),[rt,it]=De(new Set),[Re,at]=De(new Set),[To,Xt]=De([]),[We,wt]=De([]),[Ye,Zt]=De([]),[lt,Io]=De([]),[Ve,Xe]=De(null),[Qt,kt]=De(""),gt=Ur(!1),[ct,xt]=De(!1),bt=nt(async()=>{if(!A)return[];let v=new B,y=[],c;do{let u=await v.listAvailableSkills(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.skills),c=u.nextKey}while(c);return wt(y),y},[A]),Ct=nt(async()=>{if(!A)return[];let v=new B,y=[],c;do{let u=await v.getSchedules(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.schedules),c=u.nextKey}while(c);return Zt(y),y},[A]),_e=nt(async v=>{if(v==="model"){if(P.length===0){p("No models available.");return}let y=P.map(u=>({id:u.id,name:u.name,description:u.description}));te(y);let c=r?y.findIndex(u=>u.id===r):-1;Se(c>=0?c:0),w("model")}else if(v==="agent"){if(N.length===0){p("No agents available.");return}let y=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(y);let c=l?y.findIndex(u=>u.id===l):-1;Se(c>=0?c:0),w("agent")}else if(v==="skills"){let y=We;if(y.length===0)try{y=await bt()}catch{p("Failed to load skills.");return}if(y.length===0){p("No skills available.");return}let c=y.map(u=>({id:u.id,name:u.name,description:u.description}));te(c),Se(0),w("skills")}else if(v==="schedules"){let y=Ye;if(y.length===0)try{y=await Ct()}catch{p("Failed to load schedules.");return}if(y.length===0){p("No schedules found.");return}let c=y.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(c),Se(0),w("schedules")}else if(v==="connectors"){if(R.length===0){p("No connectors available.");return}let y=R.map(c=>({id:c.id,name:c.name}));te(y),Se(0),it(new Set(b||[])),w("connectors")}else if(v==="capabilities"){let y=qn().map(u=>({id:u.id,name:u.name,description:u.description}));te(y),Se(0);let c=new Set;g&&c.add("sandbox"),$&&c.add("webSearch"),H&&c.add("imageGeneration"),ie&&c.add("chart"),$e&&c.add("fileSystem"),at(c),w("capabilities")}else if(v==="chats"){if(!A){p("Not authenticated.");return}try{let y=new B,{chats:c}=await y.getChats(A.accessToken,A.workspaceId,20);if(c.length===0){p("No chats available.");return}Xt(c);let u=c.map(I=>({id:I.id,name:I.title||"Untitled",description:new Date(I.createdAt).toLocaleDateString()}));te(u);let m=u.findIndex(I=>I.id===o);Se(m>=0?m:0),w("chats")}catch{p("Failed to load chats.")}}else if(v==="profile"){let y=G.getProfileNames(),c=G.getCurrentProfileName(),u=y.map(I=>({id:I,name:I,description:I===c?"(current)":void 0}));te(u);let m=u.findIndex(I=>I.id===c);Se(m>=0?m:0),w("profile")}O(!1),de([])},[P,N,We,Ye,R,b,r,l,bt,Ct,g,$,H,ie,$e,A,o,p]),ye=nt(v=>{let y=oe.getAll(v);a(y.model?.default),d(void 0),k(null);let c=y.connectors?.defaults;S(c&&c.length>0?c:void 0);let u=y.capabilities;h(u?.sandbox??pe.sandbox),D(u?.webSearch??pe.webSearch),X(u?.imageGeneration??pe.imageGeneration),z(u?.chart??pe.chart);let m=y.localTools;j(m?.fileSystem??pe.fileSystem)},[a,d,k,S,h,D,X,z,j,pe]),Ze=nt(async()=>{try{let v=await fe();ee({accessToken:v.accessToken,workspaceId:v.workspaceId}),Q({status:"ready"})}catch(v){if(ee(null),v instanceof Qe){if(v.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(v.code==="no-workspace"){Q({status:"no-workspace"});return}}let y=v instanceof Error?v.message:"Failed to authenticate";Q({status:"error",message:y})}},[ee,Q]),St=nt(async v=>{switch(v.type){case"help":return p(os),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(v.value){let y=v.value.toLowerCase(),c=P.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),k(null),oe.setDefaultModel(c.id);else{let u=P.map(m=>m.name).join(", ");p(`Model "${v.value}" not found.
146
+ Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!v.value)return N.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=v.value.toLowerCase(),c=N.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=N.map(m=>m.name).join(", ");p(`Agent "${v.value}" not found.
147
+ Available: ${u||"none"}`)}return!0}case"skills":{if(!v.value)return _e("skills"),!0;let y=v.value.toLowerCase();return(We.length?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let m=u.find(I=>I.id.toLowerCase()===y||I.name.toLowerCase().includes(y));p(m?`Skill: ${m.name}
148
+ ${m.description}
149
+ Provider: ${m.provider}
150
+ Author: ${m.author.name}
151
+ ID: ${m.id}`:`Skill "${v.value}" not found.`)}),!0}case"schedules":{if(!v.value)return _e("schedules"),!0;let y=v.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let m=u.find(I=>I.id.toLowerCase()===y||I.name.toLowerCase().includes(y));if(m){let I=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
152
+ Agent: ${m.agent.name}
153
+ Status: ${m.isActive?"Active":"Paused"}
154
+ Repeat: ${Ho(m.config)}
155
+ Next Run: ${I}
156
+ ID: ${m.id}`)}else p(`Schedule "${v.value}" not found.`)}),!0}case"connectors":{if(l){let c=C?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(m=>` - ${m.name}`).join(`
157
157
  `);p(`Agent connectors:
158
158
  ${u}`)}return!0}let y=R.filter(c=>b?.includes(c.id));if(y.length===0)p("No active connectors.");else{let c=y.map(u=>` - ${u.name}`).join(`
159
159
  `);p(`Active connectors:
160
- ${c}`)}return!0}case"capabilities":{if(l){let u=(C?.capabilities||[]).map(g=>ce.get(g)??g);return p(u.length>0?`Agent capabilities:
161
- ${u.map(g=>` - ${g}`).join(`
162
- `)}`:"No agent capabilities."),!0}let y=[];return m&&y.push("Sandbox"),T&&y.push("Web Search"),V&&y.push("Image Generation"),ae&&y.push("Chart"),Se&&y.push("FileSystem"),p(y.length>0?`Active capabilities:
160
+ ${c}`)}return!0}case"capabilities":{if(l){let u=(C?.capabilities||[]).map(m=>le.get(m)??m);return p(u.length>0?`Agent capabilities:
161
+ ${u.map(m=>` - ${m}`).join(`
162
+ `)}`:"No agent capabilities."),!0}let y=[];return g&&y.push("Sandbox"),$&&y.push("Web Search"),H&&y.push("Image Generation"),ie&&y.push("Chart"),$e&&y.push("FileSystem"),p(y.length>0?`Active capabilities:
163
163
  ${y.map(c=>` - ${c}`).join(`
164
- `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!I.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let g=u.map(S=>` ${S.id===A.workspaceId?"* ":" "}${S.name}
165
- ID: ${S.id}`);p(`Workspaces:
166
- ${g.join(`
167
- `)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=I.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),g=u.find(k=>k.id===c);if(!g)return p(`Workspace not found: ${c}`),!0;let{TokenStorage:S}=await import("./token-storage-HJFI4DTN.js");await S.saveWorkspaceId(c),p(`Switched to workspace: ${g.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!I.value){try{let g=await y.getBudget(A.accessToken,A.workspaceId);g.budget===null?p("No budget set for this workspace."):p(`Current budget: $${g.budget}`)}catch(g){p(`Failed to get budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let c=I.value.toLowerCase();if(c==="clear"||c==="null"){try{await y.updateBudget(A.accessToken,A.workspaceId,null),p("Budget cleared.")}catch(g){p(`Failed to clear budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await y.updateBudget(A.accessToken,A.workspaceId,c),p(`Budget set to: $${c}`)}catch(g){p(`Failed to set budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let y=new B;try{let c=[],u,g=0,S=10;do{let ve=await y.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...ve.monthlyUsages),u=ve.nextKey,g++,g>=S){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let k=0,N=0;for(let ve of c)k+=parseFloat(ve.totalCost),N+=ve.operationCount;let J=[...c].toSorted((ve,ut)=>parseFloat(ut.totalCost)-parseFloat(ve.totalCost)),G=10,ue=J.slice(0,G),Ue=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${N.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ue.length} Users by Cost:`,...ue.map(ve=>` ${ve.user.name}: $${parseFloat(ve.totalCost).toFixed(2)} (${ve.operationCount.toLocaleString()} ops)`)];c.length>G&&(Ue.push("",`... and ${c.length-G} more users`),Ue.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Ue.join(`
168
- `))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=H.getCurrentProfileName(),c=r?P.find(k=>k.id===r)?.name||r:null,u=l?E.find(k=>k.id===l)?.name||l:null,g=b?R.filter(k=>b.includes(k.id)).map(k=>k.name):[],S=[];return m&&S.push("Sandbox"),T&&S.push("Web Search"),V&&S.push("Image Gen"),ae&&S.push("Chart"),Se&&S.push("FileSystem"),$e.getEmail().then(k=>{let N=[`Profile: ${y}${y!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(N.join(`
169
- `))}).catch(()=>{let k=[`Profile: ${y}`,"Not logged in",_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(k.join(`
170
- `))}),!0}case"profile":{let y=I.value?I.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],g=y[2],S=H.getProfileNames(),k=H.getCurrentProfileName(),N=H.getOverrideProfile(),J=(G,ue=!1)=>{if(G)return G;if(ue&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let G=[`Profiles (${S.length}):`];for(let ue of S){let Ue=ue===k?" (current)":"";G.push(` ${ue}${Ue}`)}return p(G.join(`
171
- `)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let G=J(u,!0),ue=ne.getAll(G),Ue=await $e.getAll(G),ve=!!Ue?.accessToken,ut=ue.capabilities?Object.entries(ue.capabilities).filter(([,Io])=>Io).map(([Io])=>Io):[],Hs=ue.connectors?.defaults&&ue.connectors.defaults.length>0?ue.connectors.defaults.join(", "):"unset",Vs=[`Profile: ${G}${G===k?" (current)":""}`,`API URL: ${ue.apiUrl??"default"}`,`Hub URL: ${ue.hubUrl??"default"}`,`Model: ${ue.model?.default??"unset"}`,`Connectors: ${Hs}`,`Capabilities: ${ut.length>0?ut.join(", "):"none"}`,ve?`Logged in as: ${Ue?.email??"unknown"}`:"Not logged in",ve&&Ue?.workspaceId?`Workspace ID: ${Ue.workspaceId}`:null].filter(Boolean);return p(Vs.join(`
172
- `)),!0}if(c==="create"){let G=u||H.DEFAULT_PROFILE;return H.createProfile(G),p(`Profile created: ${G}`),!0}if(c==="use"||c==="switch"){let G=J(u,!0);return H.setOverrideProfile(G),H.setCurrentProfile(G),ye(G),await Ze(),ie(`Switched to profile: ${G} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let G=J(u,!0),ue=G===k,Ue=H.deleteProfile(G),ve=`Profile deleted: ${G}`;if(ue)H.setOverrideProfile(Ue.currentProfile),ye(Ue.currentProfile),await Ze(),ie(`${ve}
173
- Switched to profile: ${Ue.currentProfile} (new chat)`);else if(N===G){let ut=H.getCurrentProfileName();H.setOverrideProfile(ut),ye(ut),await Ze(),ie(`${ve}
174
- Switched to profile: ${ut} (new chat)`)}else p(ve);return!0}if(c==="rename"||c==="move"||c==="mv"){let G=J(u,!0);if(!g)throw new Error("New profile name is required.");let ue=H.renameProfile(G,g);return p(`Profile renamed: ${G} -> ${g}`),N===G?(H.setOverrideProfile(g),ye(g)):ue.currentProfile===g&&ye(g),!0}if(c==="clone"||c==="copy"){let G=J(u,!0);if(!g)throw new Error("Target profile name is required.");let ue=ne.getAll(G);return H.createProfile(g),ne.setAll(ue,g),await $e.clear(g),p(`Profile cloned: ${G} -> ${g}`),!0}p(`Unknown profile command: ${c}`)}catch(G){let ue=G instanceof Error?G.message:"Unknown error";p(`Profile error: ${ue}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=_||W.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",g=l?`?agentId=${encodeURIComponent(l)}`:"",S=`${y}${u}${g}`;try{await Xn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
175
- URL: ${S}`)}return!0}case"share":{if(!A)return p("Not authenticated."),!0;if(!(_||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new B().createChatShare(A.accessToken,A.workspaceId,o,"public"),S=`${Me().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${S}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return A?_?(xt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Q(),!0;case"unknown":return p(`Unknown command: ${I.input}
176
- Type /help for available commands.`),!0;default:return!1}},[p,P,E,R,We,Ye,r,l,b,m,T,V,ae,Se,o,n,Q,_e,ie,ce,C,_,W,bt,Ct,L,a,d,x,a,ye,Ze]),eo=nt(I=>{if(mt.current=!1,ct){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&xt(!1));return}if(t(I),kt(I),Ve!==null&&Xe(null),f&&(w(null),oe([])),I.startsWith("/")&&!I.includes(" ")){let y=Qn(I);fe(y),F(0),O(y.length>0)}else O(!1),fe([])},[f,Ve,ct,t]),Lt=nt((I,y=!1)=>{if(I>=0&&I<z.length){let c=z[I];O(!1),fe([]),c.name==="model"?(t("/model "),_e("model")):c.name==="agent"?(t("/agent "),_e("agent")):c.name==="skills"?(t("/skills "),_e("skills")):c.name==="schedules"?(t("/schedules "),_e("schedules")):c.name==="connectors"?(t("/connectors "),_e("connectors")):c.name==="capabilities"?(t("/capabilities "),_e("capabilities")):c.name==="chats"?(t("/chats "),_e("chats")):c.name==="profile"?(t("/profile "),_e("profile")):y?(t(""),$t({type:c.name})):t(`/${c.name}`)}},[z,_e,t,$t]),to=nt(async I=>{mt.current=!1;let y=I.trim();if(!y||ct)return;if(f==="model"&&v.length>0){let u=v[U];u&&(l?ie(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),x(null)),w(null),oe([]),t("");return}if(f==="agent"&&v.length>0){let u=v[U];u&&(u.id!==l?ie(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),oe([]),t("");return}if(f==="skills"&&v.length>0){let u=v[U];if(u){let g=We.find(S=>S.id===u.id);g&&p(`Skill: ${g.name}
177
- ${g.description}
178
- Provider: ${g.provider}
179
- Author: ${g.author.name}
180
- ID: ${g.id}`)}w(null),oe([]),t("");return}if(f==="schedules"&&v.length>0){let u=v[U];if(u){let g=Ye.find(S=>S.id===u.id);if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
181
- Agent: ${g.agent.name}
182
- Status: ${g.isActive?"Active":"Paused"}
183
- Repeat: ${S(g.config)}
184
- Next Run: ${k}
185
- ID: ${g.id}`)}}w(null),oe([]),t("");return}if(f==="connectors"){let u=Array.from(rt);$(u.length>0?u:void 0),ne.setDefaultConnectorIds(u);let g=R.filter(S=>rt.has(S.id)).map(S=>S.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),oe([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),g=Re.has("webSearch"),S=Re.has("imageGeneration"),k=Re.has("chart"),N=Re.has("fileSystem");h(u),D(g),Z(S),Y(k),j(N),ne.setCapabilities({sandbox:u,webSearch:g,imageGeneration:S,chart:k}),ne.setLocalTools({fileSystem:N});let J=[];u&&J.push("Sandbox"),g&&J.push("Web Search"),S&&J.push("Image Generation"),k&&J.push("Chart"),N&&J.push("FileSystem"),p(J.length>0?`Active capabilities: ${J.join(", ")}`:"All capabilities disabled."),w(null),oe([]),t("");return}if(f==="profile"&&v.length>0){let u=v[U];if(u){let g=H.getCurrentProfileName();u.id!==g?(H.setOverrideProfile(u.id),H.setCurrentProfile(u.id),ye(u.id),Ze(),ie(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),oe([]),t("");return}if(se&&z.length>0){Lt(Te,!0);return}Xe(null),kt(""),vo(u=>u.length>0&&u[u.length-1]===y?u:[...u,y]);let c=es(y);if(c){await $t(c),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),ke(y)},[ke,$t,se,z,Te,Lt,f,v,U,rt,Re,R,We,Ye,p,t,l,ie,a,d,x,$,h,D,Z,Y,j,M,ye,Ze,ct,A,_,o]);return Or((I,y)=>{if(y.ctrl&&I==="c"){if(e.length>0){eo(""),mt.current=!0,p("Press Ctrl+C again to exit.");return}if(mt.current){Q();return}Q();return}if(y.ctrl&&I==="o"){q(c=>!c);return}if(ct){if(y.escape||y.return||I==="n"||I==="N"){xt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){xt(!1),t(""),A&&_&&new B().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&v.length>0){if(y.upArrow){Ce(c=>c<=0?v.length-1:c-1);return}if(y.downArrow){Ce(c=>c>=v.length-1?0:c+1);return}if(y.escape){w(null),oe([]),t("");return}if(y.return){if(f==="model"){let c=v[U];c&&(l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id))}else if(f==="agent"){let c=v[U];c&&(c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0))}else if(f==="skills"){let c=v[U];if(c){let u=We.find(g=>g.id===c.id);u&&p(`Skill: ${u.name}
164
+ `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!v.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let m=u.map(I=>` ${I.id===A.workspaceId?"* ":" "}${I.name}
165
+ ID: ${I.id}`);p(`Workspaces:
166
+ ${m.join(`
167
+ `)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=v.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),m=u.find(I=>I.id===c);if(!m)return p(`Workspace not found: ${c}`),!0;await Ce.saveWorkspaceId(c),p(`Switched to workspace: ${m.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!v.value){try{let m=await y.getBudget(A.accessToken,A.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let c=v.value.toLowerCase();if(c==="clear"||c==="null"){try{await y.updateBudget(A.accessToken,A.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await y.updateBudget(A.accessToken,A.workspaceId,c),p(`Budget set to: $${c}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let y=new B;try{let c=[],u,m=0,I=10;do{let Ie=await y.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...Ie.monthlyUsages),u=Ie.nextKey,m++,m>=I){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let x=0,L=0;for(let Ie of c)x+=parseFloat(Ie.totalCost),L+=Ie.operationCount;let ge=[...c].toSorted((Ie,ut)=>parseFloat(ut.totalCost)-parseFloat(Ie.totalCost)),J=10,ce=ge.slice(0,J),Ue=[`Total Cost: $${x.toFixed(2)}`,`Total Operations: ${L.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Ie=>` ${Ie.user.name}: $${parseFloat(Ie.totalCost).toFixed(2)} (${Ie.operationCount.toLocaleString()} ops)`)];c.length>J&&(Ue.push("",`... and ${c.length-J} more users`),Ue.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Ue.join(`
168
+ `))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=G.getCurrentProfileName(),c=r?P.find(x=>x.id===r)?.name||r:null,u=l?N.find(x=>x.id===l)?.name||l:null,m=b?R.filter(x=>b.includes(x.id)).map(x=>x.name):[],I=[];return g&&I.push("Sandbox"),$&&I.push("Web Search"),H&&I.push("Image Gen"),ie&&I.push("Chart"),$e&&I.push("FileSystem"),Ce.getEmail().then(x=>{let L=[`Profile: ${y}${y!=="default"?" (non-default)":""}`,x?`Logged in as: ${x}`:"Not logged in",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(L.join(`
169
+ `))}).catch(()=>{let x=[`Profile: ${y}`,"Not logged in",E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(x.join(`
170
+ `))}),!0}case"profile":{let y=v.value?v.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],m=y[2],I=G.getProfileNames(),x=G.getCurrentProfileName(),L=G.getOverrideProfile(),ge=(J,ce=!1)=>{if(J)return J;if(ce&&I.length===1)return I[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let J=[`Profiles (${I.length}):`];for(let ce of I){let Ue=ce===x?" (current)":"";J.push(` ${ce}${Ue}`)}return p(J.join(`
171
+ `)),!0}if(c==="current")return p(`Current profile: ${x}`),!0;if(c==="show"){let J=ge(u,!0),ce=oe.getAll(J),Ue=await Ce.getAll(J),Ie=!!Ue?.accessToken,ut=ce.capabilities?Object.entries(ce.capabilities).filter(([,vo])=>vo).map(([vo])=>vo):[],Vs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Ks=[`Profile: ${J}${J===x?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Vs}`,`Capabilities: ${ut.length>0?ut.join(", "):"none"}`,Ie?`Logged in as: ${Ue?.email??"unknown"}`:"Not logged in",Ie&&Ue?.workspaceId?`Workspace ID: ${Ue.workspaceId}`:null].filter(Boolean);return p(Ks.join(`
172
+ `)),!0}if(c==="create"){let J=u||G.DEFAULT_PROFILE;return G.createProfile(J),p(`Profile created: ${J}`),!0}if(c==="use"||c==="switch"){let J=ge(u,!0);return G.setOverrideProfile(J),G.setCurrentProfile(J),ye(J),await Ze(),re(`Switched to profile: ${J} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let J=ge(u,!0),ce=J===x,Ue=G.deleteProfile(J),Ie=`Profile deleted: ${J}`;if(ce)G.setOverrideProfile(Ue.currentProfile),ye(Ue.currentProfile),await Ze(),re(`${Ie}
173
+ Switched to profile: ${Ue.currentProfile} (new chat)`);else if(L===J){let ut=G.getCurrentProfileName();G.setOverrideProfile(ut),ye(ut),await Ze(),re(`${Ie}
174
+ Switched to profile: ${ut} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let J=ge(u,!0);if(!m)throw new Error("New profile name is required.");let ce=G.renameProfile(J,m);return p(`Profile renamed: ${J} -> ${m}`),L===J?(G.setOverrideProfile(m),ye(m)):ce.currentProfile===m&&ye(m),!0}if(c==="clone"||c==="copy"){let J=ge(u,!0);if(!m)throw new Error("Target profile name is required.");let ce=oe.getAll(J);return G.createProfile(m),oe.setAll(ce,m),await Ce.clear(m),p(`Profile cloned: ${J} -> ${m}`),!0}p(`Unknown profile command: ${c}`)}catch(J){let ce=J instanceof Error?J.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=E||W.some(x=>x.role!=="system")?`/chat/${o}`:"/chat/new",m=l?`?agentId=${encodeURIComponent(l)}`:"",I=`${y}${u}${m}`;try{await Zn(I),p(`Opened in browser: ${I}`)}catch(x){p(`Failed to open browser: ${x instanceof Error?x.message:"Unknown error"}
175
+ URL: ${I}`)}return!0}case"share":{if(!A)return p("Not authenticated."),!0;if(!(E||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new B().createChatShare(A.accessToken,A.workspaceId,o,"public"),I=`${Me().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${I}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return A?E?(xt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${v.input}
176
+ Type /help for available commands.`),!0;default:return!1}},[p,P,N,R,We,Ye,r,l,b,g,$,H,ie,$e,o,n,Z,_e,re,le,C,E,W,bt,Ct,_,a,d,k,a,ye,Ze]),eo=nt(v=>{if(gt.current=!1,ct){(v===""||v.startsWith("/"))&&(t(v),v.startsWith("/")&&xt(!1));return}if(t(v),kt(v),Ve!==null&&Xe(null),f&&(w(null),te([])),v.startsWith("/")&&!v.includes(" ")){let y=es(v);de(y),F(0),O(y.length>0)}else O(!1),de([])},[f,Ve,ct,t]),Lt=nt((v,y=!1)=>{if(v>=0&&v<q.length){let c=q[v];O(!1),de([]),c.name==="model"?(t("/model "),_e("model")):c.name==="agent"?(t("/agent "),_e("agent")):c.name==="skills"?(t("/skills "),_e("skills")):c.name==="schedules"?(t("/schedules "),_e("schedules")):c.name==="connectors"?(t("/connectors "),_e("connectors")):c.name==="capabilities"?(t("/capabilities "),_e("capabilities")):c.name==="chats"?(t("/chats "),_e("chats")):c.name==="profile"?(t("/profile "),_e("profile")):y?(t(""),St({type:c.name})):t(`/${c.name}`)}},[q,_e,t,St]),to=nt(async v=>{gt.current=!1;let y=v.trim();if(!y||ct)return;if(f==="model"&&T.length>0){let u=T[U];u&&(l?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),k(null)),w(null),te([]),t("");return}if(f==="agent"&&T.length>0){let u=T[U];u&&(u.id!==l?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&T.length>0){let u=T[U];if(u){let m=We.find(I=>I.id===u.id);m&&p(`Skill: ${m.name}
177
+ ${m.description}
178
+ Provider: ${m.provider}
179
+ Author: ${m.author.name}
180
+ ID: ${m.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&T.length>0){let u=T[U];if(u){let m=Ye.find(I=>I.id===u.id);if(m){let I=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
181
+ Agent: ${m.agent.name}
182
+ Status: ${m.isActive?"Active":"Paused"}
183
+ Repeat: ${Ho(m.config)}
184
+ Next Run: ${I}
185
+ ID: ${m.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(rt);S(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let m=R.filter(I=>rt.has(I.id)).map(I=>I.name);p(m.length>0?`Active connectors: ${m.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),m=Re.has("webSearch"),I=Re.has("imageGeneration"),x=Re.has("chart"),L=Re.has("fileSystem");h(u),D(m),X(I),z(x),j(L),oe.setCapabilities({sandbox:u,webSearch:m,imageGeneration:I,chart:x}),oe.setLocalTools({fileSystem:L});let ge=[];u&&ge.push("Sandbox"),m&&ge.push("Web Search"),I&&ge.push("Image Generation"),x&&ge.push("Chart"),L&&ge.push("FileSystem"),p(ge.length>0?`Active capabilities: ${ge.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&T.length>0){let u=T[U];if(u){let m=G.getCurrentProfileName();u.id!==m?(G.setOverrideProfile(u.id),G.setCurrentProfile(u.id),ye(u.id),Ze(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&q.length>0){Lt(Te,!0);return}Xe(null),kt(""),Io(u=>u.length>0&&u[u.length-1]===y?u:[...u,y]);let c=ts(y);if(c){await St(c),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),ke(y)},[ke,St,ne,q,Te,Lt,f,T,U,rt,Re,R,We,Ye,p,t,l,re,a,d,k,S,h,D,X,z,j,M,ye,Ze,ct,A,E,o]);return Rr((v,y)=>{if(y.ctrl&&v==="c"){if(e.length>0){eo(""),gt.current=!0,p("Press Ctrl+C again to exit.");return}if(gt.current){Z();return}Z();return}if(y.ctrl&&v==="o"){K(c=>!c);return}if(ct){if(y.escape||y.return||v==="n"||v==="N"){xt(!1),t(""),p("Chat deletion cancelled.");return}if(v==="y"||v==="Y"){xt(!1),t(""),A&&E&&new B().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&T.length>0){if(y.upArrow){Se(c=>c<=0?T.length-1:c-1);return}if(y.downArrow){Se(c=>c>=T.length-1?0:c+1);return}if(y.escape){w(null),te([]),t("");return}if(y.return){if(f==="model"){let c=T[U];c&&(l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),k(null),oe.setDefaultModel(c.id))}else if(f==="agent"){let c=T[U];c&&(c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0))}else if(f==="skills"){let c=T[U];if(c){let u=We.find(m=>m.id===c.id);u&&p(`Skill: ${u.name}
186
186
  ${u.description}
187
187
  Provider: ${u.provider}
188
188
  Author: ${u.author.name}
189
- ID: ${u.id}`)}}else if(f==="schedules"){let c=v[U];if(c){let u=Ye.find(g=>g.id===c.id);if(u){let g=k=>{if(k.type==="no-repeat")return"No repeat";let{interval:N}=k;switch(N.unit){case"minutes":return`Every ${N.every} min`;case"hours":return`Every ${N.every} hr`;case"days":return`Every ${N.every} day at ${String(N.time.hour).padStart(2,"0")}:${String(N.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${N.every} week`;case"months":return`Every ${N.every} month`;default:return"Unknown"}},S=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
189
+ ID: ${u.id}`)}}else if(f==="schedules"){let c=T[U];if(c){let u=Ye.find(m=>m.id===c.id);if(u){let m=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
190
190
  Agent: ${u.agent.name}
191
191
  Status: ${u.isActive?"Active":"Paused"}
192
- Repeat: ${g(u.config)}
193
- Next Run: ${S}
194
- ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);$(c.length>0?c:void 0),ne.setDefaultConnectorIds(c);let u=R.filter(g=>rt.has(g.id)).map(g=>g.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Re.has("sandbox"),u=Re.has("webSearch"),g=Re.has("imageGeneration"),S=Re.has("chart"),k=Re.has("fileSystem");h(c),D(u),Z(g),Y(S),j(k),ne.setCapabilities({sandbox:c,webSearch:u,imageGeneration:g,chart:S}),ne.setLocalTools({fileSystem:k});let N=[];c&&N.push("Sandbox"),u&&N.push("Web Search"),g&&N.push("Image Generation"),S&&N.push("Chart"),k&&N.push("FileSystem"),p(N.length>0?`Active capabilities: ${N.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=v[U];if(c){let u=To.find(g=>g.id===c.id);u&&A&&(s(u.id),i(u.title||void 0),he(!0),new B().getMessages(A.accessToken,A.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(N=>N.role==="user"||N.role==="assistant").map(N=>({role:N.role,content:ht(N.parts,!1),parts:N.parts})).filter(N=>N.content).toReversed();L(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=v[U];if(c){let u=H.getCurrentProfileName();c.id!==u?(H.setOverrideProfile(c.id),H.setCurrentProfile(c.id),ye(c.id),Ze(),ie(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),oe([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let c=v[U];c&&(f==="connectors"?it:at)(g=>{let S=new Set(g);return S.has(c.id)?S.delete(c.id):S.add(c.id),S});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set(v.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set);return}return}if(se&&z.length>0){if(y.upArrow){F(c=>c<=0?z.length-1:c-1);return}if(y.downArrow){F(c=>c>=z.length-1?0:c+1);return}if(y.escape){O(!1),fe([]);return}if(y.tab){Lt(Te);return}}if(y.upArrow){if(e.includes(`
192
+ Repeat: ${Ho(u.config)}
193
+ Next Run: ${m}
194
+ ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);S(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=R.filter(m=>rt.has(m.id)).map(m=>m.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Re.has("sandbox"),u=Re.has("webSearch"),m=Re.has("imageGeneration"),I=Re.has("chart"),x=Re.has("fileSystem");h(c),D(u),X(m),z(I),j(x),oe.setCapabilities({sandbox:c,webSearch:u,imageGeneration:m,chart:I}),oe.setLocalTools({fileSystem:x});let L=[];c&&L.push("Sandbox"),u&&L.push("Web Search"),m&&L.push("Image Generation"),I&&L.push("Chart"),x&&L.push("FileSystem"),p(L.length>0?`Active capabilities: ${L.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=T[U];if(c){let u=To.find(m=>m.id===c.id);u&&A&&(s(u.id),i(u.title||void 0),he(!0),new B().getMessages(A.accessToken,A.workspaceId,u.id,20).then(({messages:I})=>{let x=I.filter(L=>L.role==="user"||L.role==="assistant").map(L=>({role:L.role,content:ht(L.parts,!1),parts:L.parts})).filter(L=>L.content).toReversed();_(x),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=T[U];if(c){let u=G.getCurrentProfileName();c.id!==u?(G.setOverrideProfile(c.id),G.setCurrentProfile(c.id),ye(c.id),Ze(),re(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),te([]),t("");return}if(v===" "&&(f==="connectors"||f==="capabilities")){let c=T[U];c&&(f==="connectors"?it:at)(m=>{let I=new Set(m);return I.has(c.id)?I.delete(c.id):I.add(c.id),I});return}if(v==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set(T.map(u=>u.id)));return}if(v==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set);return}return}if(ne&&q.length>0){if(y.upArrow){F(c=>c<=0?q.length-1:c-1);return}if(y.downArrow){F(c=>c>=q.length-1?0:c+1);return}if(y.escape){O(!1),de([]);return}if(y.tab){Lt(Te);return}}if(y.upArrow){if(e.includes(`
195
195
  `)||lt.length===0)return;if(Ve===null){kt(e);let u=lt.length-1;Xe(u),t(lt[u]);return}let c=Math.max(0,Ve-1);Xe(c),t(lt[c]);return}if(y.downArrow){if(e.includes(`
196
- `)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:z,suggestionIndex:Te,showSuggestions:se,argMode:f,argItems:v,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as Ur,useState as jr}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=jr([]),a=Ur(0),l=Jt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let T of o)if(T.models.some(V=>V.id===h))return T.id;return o[0]?.id}},[o]),d=Jt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let T=t?l(t):o[0]?.id;if(!T){n?.(h.filename,"No model provider available");return}let D=`file-${++a.current}`;r(V=>[...V,{id:D,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let Z=await new B().uploadFile(e.accessToken,e.workspaceId,h,T);r(ae=>ae.map(Y=>Y.id===D?{...Y,status:"uploaded",fileId:Z.id}:Y)),s?.(h.filename)}catch(V){let Z=V instanceof Error?V.message:"Upload failed";r(ae=>ae.map(Y=>Y.id===D?{...Y,status:"error",error:Z}:Y)),n?.(h.filename,Z)}},[e,t,l,o,s,n]),C=Jt(h=>{r(T=>T.filter(D=>D.id!==h))},[]),x=Jt(()=>{r([])},[]),b=Jt(()=>i.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[i]),$=i.some(h=>h.status==="uploading"),m=i.length>0;return{pendingFiles:i,addFile:d,removeFile:C,clearFiles:x,getUploadedFileIds:b,hasUploadingFiles:$,hasFiles:m}}import{jsx as X,jsxs as de}from"react/jsx-runtime";var Fr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Jo,Jo,Mo,Mo,gt,gt,gt,gt],rs=Fr.map((e,t)=>`${Wr[t]??gt}${e}${re}`).join(`
197
- `),Mr=`${gt}EntryDesk${re}`,Jr=500;function Gr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Hr(e){let t=Gr(e);return Math.max(...t.split(`
198
- `).map(o=>o.length))}function Vr(e){let t=Hr(rs);return e>=t?rs:Mr}function is({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:C=!0}){let x=process.stdout.columns??80,b=Vr(x),$=ss(null),m=jn(s,n),{state:h,setState:T,messages:D,setMessages:V,input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,hasPersistedChat:E,setHasPersistedChat:R,credentials:W,setCredentials:_,currentResponse:he,setCurrentResponse:L,fullOutput:p,setFullOutput:ie,addSystemMessage:ke,startNewChat:q}=m,{credentials:A}=Fn(T);ho(()=>{A&&!W&&_(A)},[A,W,_]);let{availableConnectors:te,availableModels:ee,availableAgents:me,modelProviders:ce,loading:M}=Wn(W),{currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,activeConnectorIds:F,setActiveConnectorIds:se}=Yn(t,e,i),O=ss(!1);ho(()=>{if(!O.current){if(O.current=!0,!t&&!e){let k=ne.getDefaultModel();k&&z(k)}if(!i&&!e){let k=ne.getDefaultConnectorIds();k&&se(k.length>0?k:void 0)}}},[t,e,i,z,se]);let{currentAgentDetails:f}=zn(fe,W),{sandbox:w,setSandbox:v,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,capabilityLabelMap:Xt}=qn(r,a,l,d,C),{pendingFiles:We,addFile:wt,removeFile:Ye,clearFiles:Zt,getUploadedFileIds:lt,hasUploadingFiles:vo,hasFiles:Ve}=ns({credentials:W,currentModel:Q,modelProviders:ce,onUploadSuccess:k=>{ke(`\u2713 Attached: ${k}`)},onUploadError:(k,N)=>{ke(`\u2717 Failed to upload ${k}: ${N}`)}}),{sendMessage:Xe}=Gn({chatId:Y,credentials:W,currentAgentId:fe,currentModel:Q,activeConnectorIds:F,sandbox:w,webSearch:oe,imageGeneration:Ce,chart:it,localTools:at,fullOutput:p,setMessages:V,setState:T,setCurrentResponse:L,setCredentials:_,setHasPersistedChat:R,getFileIds:lt,clearFiles:Zt}),Qt=Ko(k=>{q(k),L("")},[q]),[kt,mt]=Br(!1),ct=Ko(async k=>{let N=k.text.trim(),J=po(N);if(/^https?:\/\//.test(J))return;if(await Dn(N)&&Ln(J)){let ue=await On(N);ue&&(k.preventDefault(),await wt(ue))}},[wt]),xt=Ko(async()=>{if(!(kt||h.status!=="ready")){if(M||ce.length===0){ke("Please wait for resources to load before pasting images.");return}ke("Reading clipboard..."),mt(!0);try{let k=await _n();if(k){let N=`clipboard-${Date.now()}.png`;ke(`Uploading: ${N} (${Math.round(k.buffer.length/1024)}KB)`),await wt({buffer:k.buffer,filename:N,mimeType:k.mime})}else ke("No image found in clipboard. Copy an image first.")}catch(k){let N=k instanceof Error?k.message:"Failed to read clipboard";ke(`Clipboard error: ${N}`)}finally{mt(!1)}}},[wt,ke,kt,h.status,M,ce.length]),{suggestions:bt,suggestionIndex:Ct,showSuggestions:_e,argMode:ye,argItems:Ze,argIndex:$t,selectedConnectorIds:eo,selectedCapabilities:Lt,deleteConfirmMode:to,handleInputChange:I,handleSubmit:y}=os({input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:se,sandbox:w,setSandbox:v,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,availableModels:ee,availableAgents:me,availableConnectors:te,messages:D,hasPersistedChat:E,setHasPersistedChat:R,setMessages:V,addSystemMessage:ke,startNewChat:Qt,sendMessage:Xe,setFullOutput:ie,credentials:W,setCredentials:_,setState:T,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:l,chart:d,fileSystem:C},capabilityLabelMap:Xt,hasUploadingFiles:vo});if(Ho((k,N)=>{(N.ctrl||N.meta)&&k==="v"&&xt()},{isActive:h.status==="ready"&&!ye}),Ho((k,N)=>{if(!N.escape)return;let J=Date.now(),G=$.current;$.current=J,!(!G||J-G>Jr)&&(ye||_e||($.current=null,Ve&&Zt(),Z.length>0&&I("")))},{isActive:h.status==="ready"}),Ho((k,N)=>{N.return&&(Qt("Started a new chat."),T({status:"ready"}))},{isActive:h.status==="error"}),ho(()=>{if(W&&!M&&h.status==="loading")if(!Q&&!fe){let k=ne.getDefaultModel(),N=k&&ee.some(G=>G.id===k),J=N?k:ee[0]?.id;J?(N||ne.setDefaultModel(J),z(J),T({status:"ready"})):me.length===0?T({status:"no-model"}):T({status:"ready"})}else T({status:"ready"})},[W,M,Q,fe,ee,me,h.status,z,T]),ho(()=>{o&&W&&h.status==="ready"&&Xe(o)},[W,o]),h.status==="loading")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),de(Pe,{children:[X(K,{color:"cyan",children:X(Vo,{type:"dots"})}),X(K,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"Not logged in"}),X(K,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"No workspace selected"}),X(K,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"No model or agent specified"}),s&&X(K,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(K,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(K,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),de(K,{color:"red",children:["Error: ",h.message]}),X(K,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=fe?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":F&&F.length>0?te.filter(k=>F.includes(k.id)).map(k=>k.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(fe)if(f?.capabilities)for(let k of f.capabilities)u.push(Xt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),oe&&u.push("Web"),Ce&&u.push("Image"),it&&u.push("Chart");at&&u.push("FileSystem");let g=H.getCurrentProfileName(),S=g!=="default";return de(Pe,{flexDirection:"column",children:[de(Pe,{marginBottom:1,flexDirection:"column",children:[X(K,{children:b}),de(Pe,{children:[X(K,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),de(K,{dimColor:!0,children:[" v","1.7.10"]}),S&&de(K,{color:"magenta",children:[" [",g,"]"]}),X(K,{dimColor:!0,children:" (type /help for commands)"})]})]}),D.map((k,N)=>{let J=k.parts&&p?ht(k.parts,!0):k.content,G=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ue=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return de(Pe,{flexDirection:"column",marginBottom:1,children:[de(K,{bold:!0,color:G,children:[ue,":"]}),X(Wo,{text:J})]},N)}),he&&de(Pe,{flexDirection:"column",marginBottom:1,children:[X(K,{bold:!0,color:"blue",children:"Assistant:"}),X(Wo,{text:he})]}),h.status==="ready"&&X(gn,{suggestions:bt,activeIndex:Ct,visible:_e}),h.status==="ready"&&ye&&X(mn,{items:Ze,activeIndex:$t,pageSize:ye==="agent"||ye==="skills"||ye==="model"?5:10,selectedIds:ye==="connectors"?eo:ye==="capabilities"?Lt:void 0,multiSelect:ye==="connectors"||ye==="capabilities",visible:!0,title:ye==="model"?"Select model:":ye==="agent"?"Select agent:":ye==="skills"?"Select skill:":ye==="connectors"?"Select connectors:":ye==="capabilities"?"Select capabilities:":"Select chat:"}),h.status==="sending"&&!he?de(Pe,{children:[X(K,{color:"cyan",children:X(Vo,{type:"dots"})}),X(K,{children:" Thinking..."})]}):h.status==="ready"&&!ye?de(Pe,{flexDirection:"column",children:[to&&X(Pe,{marginBottom:1,children:X(K,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ve&&!to&&de(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[X(K,{dimColor:!0,children:"Attachments:"}),We.map((k,N)=>de(K,{children:[k.status==="uploading"?de(K,{color:"yellow",children:[X(Vo,{type:"dots"})," ",k.filename]}):k.status==="error"?de(K,{color:"red",children:["\u2717 ",k.filename]}):de(K,{color:"green",children:["\u2713 ",k.filename]}),N<We.length-1&&X(K,{children:", "})]},k.id))]}),de(Pe,{children:[X(K,{color:"green",children:"> "}),X($n,{value:Z,onChange:I,onSubmit:y,onPaste:ct,leadingOffset:2,multiline:!0})]})]}):null,de(Pe,{marginTop:1,flexDirection:"column",children:[de(Pe,{gap:2,children:[de(K,{children:[X(K,{dimColor:!0,children:"Model: "}),X(K,{color:"magenta",children:fe?f?.model?.name||"loading...":ee.find(k=>k.id===Q)?.name||Q||"none"})]}),de(K,{children:[X(K,{dimColor:!0,children:"Connectors: "}),X(K,{color:"cyan",children:c})]}),de(K,{children:[X(K,{dimColor:!0,children:"Capabilities: "}),X(K,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),de(K,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Xr}from"react/jsx-runtime";async function qr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function zr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=n[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,o,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var It="\x1B[2m",Oe="\x1B[0m",qo="\x1B[36m",us="\x1B[33m",wo="\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 ko(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
196
+ `)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:q,suggestionIndex:Te,showSuggestions:ne,argMode:f,argItems:T,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as jr,useState as Br}from"react";function ss({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=Br([]),a=jr(0),l=Jt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let $ of o)if($.models.some(H=>H.id===h))return $.id;return o[0]?.id}},[o]),d=Jt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let $=t?l(t):o[0]?.id;if(!$){n?.(h.filename,"No model provider available");return}let D=`file-${++a.current}`;r(H=>[...H,{id:D,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let X=await new B().uploadFile(e.accessToken,e.workspaceId,h,$);r(ie=>ie.map(z=>z.id===D?{...z,status:"uploaded",fileId:X.id}:z)),s?.(h.filename)}catch(H){let X=H instanceof Error?H.message:"Upload failed";r(ie=>ie.map(z=>z.id===D?{...z,status:"error",error:X}:z)),n?.(h.filename,X)}},[e,t,l,o,s,n]),C=Jt(h=>{r($=>$.filter(D=>D.id!==h))},[]),k=Jt(()=>{r([])},[]),b=Jt(()=>i.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[i]),S=i.some(h=>h.status==="uploading"),g=i.length>0;return{pendingFiles:i,addFile:d,removeFile:C,clearFiles:k,getUploadedFileIds:b,hasUploadingFiles:S,hasFiles:g}}import{jsx as Y,jsxs as ue}from"react/jsx-runtime";var Wr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Mr=[Jo,Jo,Mo,Mo,mt,mt,mt,mt],is=Wr.map((e,t)=>`${Mr[t]??mt}${e}${se}`).join(`
197
+ `),Jr=`${mt}EntryDesk${se}`,Gr=500;function Hr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Vr(e){let t=Hr(e);return Math.max(...t.split(`
198
+ `).map(o=>o.length))}function Kr(e){let t=Vr(is);return e>=t?is:Jr}function as({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:C=!0}){let k=process.stdout.columns??80,b=Kr(k),S=rs(null),g=Bn(s,n),{state:h,setState:$,messages:D,setMessages:H,input:X,setInput:ie,chatId:z,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:P,hasPersistedChat:N,setHasPersistedChat:R,credentials:W,setCredentials:E,currentResponse:he,setCurrentResponse:_,fullOutput:p,setFullOutput:re,addSystemMessage:ke,startNewChat:K}=g,{credentials:A}=Wn($);ho(()=>{A&&!W&&E(A)},[A,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:M}=Mn(W),{currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,activeConnectorIds:F,setActiveConnectorIds:ne}=Xn(t,e,i),O=rs(!1);ho(()=>{if(!O.current){if(O.current=!0,!t&&!e){let x=oe.getDefaultModel();x&&q(x)}if(!i&&!e){let x=oe.getDefaultConnectorIds();x&&ne(x.length>0?x:void 0)}}},[t,e,i,q,ne]);let{currentAgentDetails:f}=Yn(de,W),{sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:Se,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,capabilityLabelMap:Xt}=zn(r,a,l,d,C),{pendingFiles:We,addFile:wt,removeFile:Ye,clearFiles:Zt,getUploadedFileIds:lt,hasUploadingFiles:Io,hasFiles:Ve}=ss({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:x=>{ke(`\u2713 Attached: ${x}`)},onUploadError:(x,L)=>{ke(`\u2717 Failed to upload ${x}: ${L}`)}}),{sendMessage:Xe}=Hn({chatId:z,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:F,sandbox:w,webSearch:te,imageGeneration:Se,chart:it,localTools:at,fullOutput:p,setMessages:H,setState:$,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:R,getFileIds:lt,clearFiles:Zt}),Qt=qo(x=>{K(x),_("")},[K]),[kt,gt]=Fr(!1),ct=qo(async x=>{let L=x.text.trim(),ge=po(L);if(/^https?:\/\//.test(ge))return;if(await On(L)&&Dn(ge)){let ce=await Rn(L);ce&&(x.preventDefault(),await wt(ce))}},[wt]),xt=qo(async()=>{if(!(kt||h.status!=="ready")){if(M||le.length===0){ke("Please wait for resources to load before pasting images.");return}ke("Reading clipboard..."),gt(!0);try{let x=await Ln();if(x){let L=`clipboard-${Date.now()}.png`;ke(`Uploading: ${L} (${Math.round(x.buffer.length/1024)}KB)`),await wt({buffer:x.buffer,filename:L,mimeType:x.mime})}else ke("No image found in clipboard. Copy an image first.")}catch(x){let L=x instanceof Error?x.message:"Failed to read clipboard";ke(`Clipboard error: ${L}`)}finally{gt(!1)}}},[wt,ke,kt,h.status,M,le.length]),{suggestions:bt,suggestionIndex:Ct,showSuggestions:_e,argMode:ye,argItems:Ze,argIndex:St,selectedConnectorIds:eo,selectedCapabilities:Lt,deleteConfirmMode:to,handleInputChange:v,handleSubmit:y}=ns({input:X,setInput:ie,chatId:z,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:P,currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:ne,sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:Se,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:D,hasPersistedChat:N,setHasPersistedChat:R,setMessages:H,addSystemMessage:ke,startNewChat:Qt,sendMessage:Xe,setFullOutput:re,credentials:W,setCredentials:E,setState:$,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:l,chart:d,fileSystem:C},capabilityLabelMap:Xt,hasUploadingFiles:Io});if(Vo((x,L)=>{(L.ctrl||L.meta)&&x==="v"&&xt()},{isActive:h.status==="ready"&&!ye}),Vo((x,L)=>{if(!L.escape)return;let ge=Date.now(),J=S.current;S.current=ge,!(!J||ge-J>Gr)&&(ye||_e||(S.current=null,Ve&&Zt(),X.length>0&&v("")))},{isActive:h.status==="ready"}),Vo((x,L)=>{L.return&&(Qt("Started a new chat."),$({status:"ready"}))},{isActive:h.status==="error"}),ho(()=>{if(W&&!M&&h.status==="loading")if(!Z&&!de){let x=oe.getDefaultModel(),L=x&&Q.some(J=>J.id===x),ge=L?x:Q[0]?.id;ge?(L||oe.setDefaultModel(ge),q(ge),$({status:"ready"})):pe.length===0?$({status:"no-model"}):$({status:"ready"})}else $({status:"ready"})},[W,M,Z,de,Q,pe,h.status,q,$]),ho(()=>{o&&W&&h.status==="ready"&&Xe(o)},[W,o]),h.status==="loading")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),ue(Pe,{children:[Y(V,{color:"cyan",children:Y(Ko,{type:"dots"})}),Y(V,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"Not logged in"}),Y(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No workspace selected"}),Y(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No model or agent specified"}),s&&Y(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),Y(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),Y(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return ue(Pe,{flexDirection:"column",children:[Y(V,{children:b}),ue(V,{color:"red",children:["Error: ",h.message]}),Y(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(x=>x.name).join(", "):"none":"loading...":F&&F.length>0?ee.filter(x=>F.includes(x.id)).map(x=>x.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let x of f.capabilities)u.push(Xt.get(x)??x);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),Se&&u.push("Image"),it&&u.push("Chart");at&&u.push("FileSystem");let m=G.getCurrentProfileName(),I=m!=="default";return ue(Pe,{flexDirection:"column",children:[ue(Pe,{marginBottom:1,flexDirection:"column",children:[Y(V,{children:b}),ue(Pe,{children:[Y(V,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.7.11"]}),I&&ue(V,{color:"magenta",children:[" [",m,"]"]}),Y(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),D.map((x,L)=>{let ge=x.parts&&p?ht(x.parts,!0):x.content,J=x.role==="user"?"green":x.role==="system"?"yellow":"blue",ce=x.role==="user"?"You":x.role==="system"?"System":"Assistant";return ue(Pe,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:J,children:[ce,":"]}),Y(Wo,{text:ge})]},L)}),he&&ue(Pe,{flexDirection:"column",marginBottom:1,children:[Y(V,{bold:!0,color:"blue",children:"Assistant:"}),Y(Wo,{text:he})]}),h.status==="ready"&&Y(hn,{suggestions:bt,activeIndex:Ct,visible:_e}),h.status==="ready"&&ye&&Y(mn,{items:Ze,activeIndex:St,pageSize:ye==="agent"||ye==="skills"||ye==="model"?5:10,selectedIds:ye==="connectors"?eo:ye==="capabilities"?Lt:void 0,multiSelect:ye==="connectors"||ye==="capabilities",visible:!0,title:ye==="model"?"Select model:":ye==="agent"?"Select agent:":ye==="skills"?"Select skill:":ye==="connectors"?"Select connectors:":ye==="capabilities"?"Select capabilities:":"Select chat:"}),h.status==="sending"&&!he?ue(Pe,{children:[Y(V,{color:"cyan",children:Y(Ko,{type:"dots"})}),Y(V,{children:" Thinking..."})]}):h.status==="ready"&&!ye?ue(Pe,{flexDirection:"column",children:[to&&Y(Pe,{marginBottom:1,children:Y(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ve&&!to&&ue(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[Y(V,{dimColor:!0,children:"Attachments:"}),We.map((x,L)=>ue(V,{children:[x.status==="uploading"?ue(V,{color:"yellow",children:[Y(Ko,{type:"dots"})," ",x.filename]}):x.status==="error"?ue(V,{color:"red",children:["\u2717 ",x.filename]}):ue(V,{color:"green",children:["\u2713 ",x.filename]}),L<We.length-1&&Y(V,{children:", "})]},x.id))]}),ue(Pe,{children:[Y(V,{color:"green",children:"> "}),Y($n,{value:X,onChange:v,onSubmit:y,onPaste:ct,leadingOffset:2,multiline:!0})]})]}):null,ue(Pe,{marginTop:1,flexDirection:"column",children:[ue(Pe,{gap:2,children:[ue(V,{children:[Y(V,{dimColor:!0,children:"Model: "}),Y(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(x=>x.id===Z)?.name||Z||"none"})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Connectors: "}),Y(V,{color:"cyan",children:c})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Capabilities: "}),Y(V,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(V,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Zr}from"react/jsx-runtime";async function zr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function Yr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=n[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,o,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var vt="\x1B[2m",Oe="\x1B[0m",zo="\x1B[36m",ds="\x1B[33m",wo="\x1B[32m",ls="stream-json";function cs(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function ko(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
199
199
  `)}function xo(e,t){if(t)return e;let o=e.split(`
200
- `);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${It}... (${i} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
201
- `)}function Yr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cs(e,t){if(!e)return"(no result)";if(typeof e!="object")return xo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${us}[stderr]${Oe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),xo(n.join(`
200
+ `);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${vt}... (${i} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
201
+ `)}function Xr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function us(e,t){if(!e)return"(no result)";if(typeof e!="object")return xo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${ds}[stderr]${Oe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),xo(n.join(`
202
202
  `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
203
- `);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let te=await pe();t=te.accessToken,o=te.workspaceId}catch(te){xe(te)}let s=e.output===as;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${as}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=ne.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await qr());let a=new B;async function l(){if(!i)try{let{models:te}=await a.getModels(t,o),ee=te[0]?.id;if(!ee)return;ne.setDefaultModel(ee),i=ee}catch{}}let d,C,x,b;if(e.continue){let te=await zr(a,t,o,e.continue);te||process.exit(1),d=te.chat.id,C=te.chat.title??void 0,x=te.chat.agentId??void 0,b=te.modelId;let ee=e.agentId||e.model||x||b||i;!ee&&!e.interactive&&(await l(),ee=e.agentId||e.model||x||b||i),!ee&&!e.interactive&&(n||console.log(`Continuing chat: ${te.chat.title||"Untitled"}`),console.error(`
204
- Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${te.chat.title||"Untitled"}
205
- `)}let $=e.agentId||x,m=e.model||b||i||void 0;!$&&!m&&(await l(),m=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 h=ne.getCapabilities(),T=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,D=e.webSearch??h?.webSearch??!1,V=e.imageGen??h?.imageGeneration??!1,Z=e.chart??h?.chart??!1,ae=ne.getDefaultConnectorIds(),Y=e.connectors??ae??void 0,Se=ne.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:Se?.fileSystem??!0;if(e.interactive){Kr(Xr(is,{agentId:$,model:m,message:e.message,chatId:d,chatTitle:C??void 0,connectorIds:Y,enableSandbox:T,enableWebSearch:D,enableImageGeneration:V,enableChart:Z,enableFileSystem:j}),{exitOnCtrlC:!1});return}let P=!e.continue&&!m&&!$;(!r||P)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let E=e.fullOutput??!1,R=d||yo(),W=j?no():void 0,_=j?so():void 0,he=[],L=yo(),p=(te,ee,me)=>{let ce={id:R};return te&&(ce.message={id:te.id,createdAt:new Date,role:"user",parts:[{type:"text",text:te.text}]}),$?ce.agentId=$:(m&&(ce.model=m),ce.connectorIds=Y??[],ce.enableSandbox=T,ce.enableWebSearch=D,ce.enableImageGeneration=V,ce.enableChart=Z),W&&(ce.clientTools=W),_&&(ce.clientToolSystemPrompt=_),ee&&ee.length>0&&(ce.clientToolResults=ee),me&&me.length>0&&(ce.previousMessages=me),ce},ie=async te=>{if(!te.body)throw new Error("No response body");let ee=te.body.getReader(),me=new TextDecoder,ce="",M=new Map,Q=[],z=[];for(;;){let{done:fe,value:Te}=await ee.read();if(fe)break;ce+=me.decode(Te,{stream:!0});let F=ce.split(`
206
- `);ce=F.pop()||"";for(let se of F){let O=se.trimEnd();if(O==="data: [DONE]"){s&&ko("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&z.push(f),s){f.type==="text-delta"&&f.delta!==void 0?ko("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ko("reasoning-delta",f.delta):ko(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),j&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&tt(f.toolName)){let w=f.args||f.input||{};Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${It}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
207
-
208
- `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let v=j&&tt(f.toolName)?`${wo}[LOCAL]${Oe} `:"";console.log(`
209
- ${qo}\u250C\u2500 ${v}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},v=Yr(w);console.log(`${us}\u2502 Arguments:${Oe}`);for(let oe of v.split(`
210
- `))console.log(`${It}\u2502 ${oe}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),v=cs(f.result,E);console.log(`${wo}\u2502 Result:${Oe}`);for(let oe of v.split(`
211
- `))console.log(`${It}\u2502 ${oe}${Oe}`);console.log(`${qo}\u2514\u2500 ${w?.toolName||"Tool"} completed${Oe}
212
- `),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${It}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Q,messageParts:z}},ke=p({id:yo(),text:r}),q=await a.chat(t,o,ke),A=await ie(q);for(he=A.messageParts;A.pendingClientTools.length>0;){let te=[];for(let M of A.pendingClientTools){!n&&!s&&console.log(`${wo}\u2502 Executing locally...${Oe}`);let Q=await ro(M.toolName,M.args),z=Q.success?JSON.stringify(Q.result):Q.error||"Unknown error";if(te.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:z}],isError:!Q.success}),!n&&!s){let fe=cs(Q.success?Q.result:{error:Q.error},E);console.log(`${wo}\u2502 Result:${Oe}`);for(let Te of fe.split(`
213
- `))console.log(`${It}\u2502 ${Te}${Oe}`);console.log(`${qo}\u2514\u2500 ${M.toolName} completed${Oe}
214
- `)}}let ee=he.map(M=>{if(M.type==="tool-call"){let Q=te.find(fe=>fe.toolCallId===M.toolCallId),z=Q?.content.filter(fe=>fe.type==="text").map(fe=>fe.text).join(`
215
- `);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Q?.isError?"output-error":"output-available",output:z}}return M}),me=[{id:L,role:"assistant",parts:ee}];L=yo();let ce=p(void 0,te,me);q=await a.chat(t,o,ce),A=await ie(q),he=A.messageParts}s||console.log("")}var Gt="\x1B[2m",Ae="\x1B[0m",pt="\x1B[36m",Yo="\x1B[33m",fs="\x1B[32m",ps="stream-json";function ze(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
216
- `)}function zo(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function bo(e,t){if(t)return e;let o=e.split(`
203
+ `);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}async function fs(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){xe(ee)}let s=e.output===ls;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${ls}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=oe.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await zr());let a=new B;async function l(){if(!i)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),i=Q}catch{}}let d,C,k,b;if(e.continue){let ee=await Yr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,C=ee.chat.title??void 0,k=ee.chat.agentId??void 0,b=ee.modelId;let Q=e.agentId||e.model||k||b||i;!Q&&!e.interactive&&(await l(),Q=e.agentId||e.model||k||b||i),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
204
+ Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
205
+ `)}let S=e.agentId||k,g=e.model||b||i||void 0;!S&&!g&&(await l(),g=e.model||b||i||void 0),cs(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),cs(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let h=oe.getCapabilities(),$=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,D=e.webSearch??h?.webSearch??!1,H=e.imageGen??h?.imageGeneration??!1,X=e.chart??h?.chart??!1,ie=oe.getDefaultConnectorIds(),z=e.connectors??ie??void 0,$e=oe.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:$e?.fileSystem??!0;if(e.interactive){qr(Zr(as,{agentId:S,model:g,message:e.message,chatId:d,chatTitle:C??void 0,connectorIds:z,enableSandbox:$,enableWebSearch:D,enableImageGeneration:H,enableChart:X,enableFileSystem:j}),{exitOnCtrlC:!1});return}let P=!e.continue&&!g&&!S;(!r||P)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||yo(),W=j?no():void 0,E=j?so():void 0,he=[],_=yo(),p=(ee,Q,pe)=>{let le={id:R};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),S?le.agentId=S:(g&&(le.model=g),le.connectorIds=z??[],le.enableSandbox=$,le.enableWebSearch=D,le.enableImageGeneration=H,le.enableChart=X),W&&(le.clientTools=W),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},re=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",M=new Map,Z=[],q=[];for(;;){let{done:de,value:Te}=await Q.read();if(de)break;le+=pe.decode(Te,{stream:!0});let F=le.split(`
206
+ `);le=F.pop()||"";for(let ne of F){let O=ne.trimEnd();if(O==="data: [DONE]"){s&&ko("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&q.push(f),s){f.type==="text-delta"&&f.delta!==void 0?ko("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ko("reasoning-delta",f.delta):ko(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),j&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&tt(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${vt}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
207
+
208
+ `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let T=j&&tt(f.toolName)?`${wo}[LOCAL]${Oe} `:"";console.log(`
209
+ ${zo}\u250C\u2500 ${T}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},T=Xr(w);console.log(`${ds}\u2502 Arguments:${Oe}`);for(let te of T.split(`
210
+ `))console.log(`${vt}\u2502 ${te}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),T=us(f.result,N);console.log(`${wo}\u2502 Result:${Oe}`);for(let te of T.split(`
211
+ `))console.log(`${vt}\u2502 ${te}${Oe}`);console.log(`${zo}\u2514\u2500 ${w?.toolName||"Tool"} completed${Oe}
212
+ `),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${vt}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:q}},ke=p({id:yo(),text:r}),K=await a.chat(t,o,ke),A=await re(K);for(he=A.messageParts;A.pendingClientTools.length>0;){let ee=[];for(let M of A.pendingClientTools){!n&&!s&&console.log(`${wo}\u2502 Executing locally...${Oe}`);let Z=await ro(M.toolName,M.args),q=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:q}],isError:!Z.success}),!n&&!s){let de=us(Z.success?Z.result:{error:Z.error},N);console.log(`${wo}\u2502 Result:${Oe}`);for(let Te of de.split(`
213
+ `))console.log(`${vt}\u2502 ${Te}${Oe}`);console.log(`${zo}\u2514\u2500 ${M.toolName} completed${Oe}
214
+ `)}}let Q=he.map(M=>{if(M.type==="tool-call"){let Z=ee.find(de=>de.toolCallId===M.toolCallId),q=Z?.content.filter(de=>de.type==="text").map(de=>de.text).join(`
215
+ `);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Z?.isError?"output-error":"output-available",output:q}}return M}),pe=[{id:_,role:"assistant",parts:Q}];_=yo();let le=p(void 0,ee,pe);K=await a.chat(t,o,le),A=await re(K),he=A.messageParts}s||console.log("")}var Gt="\x1B[2m",Ae="\x1B[0m",pt="\x1B[36m",Xo="\x1B[33m",ps="\x1B[32m",gs="stream-json";function ze(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
216
+ `)}function Yo(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function bo(e,t){if(t)return e;let o=e.split(`
217
217
  `);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),i=o.length-10;return[...s,`... (${i} lines omitted, use --full-output to see all) ...`,...n].join(`
218
- `)}function Xo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(Xo);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]=Xo(s):t[o]=s;return t}function ms(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function gs(e,t){if(!e)return"(no result)";if(typeof e!="object")return bo(String(e),t);let o=t?e:Xo(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(`${Yo}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),bo(n.join(`
218
+ `)}function Zo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(Zo);let t={};for(let[o,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[o]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[o]=Zo(s):t[o]=s;return t}function ms(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function hs(e,t){if(!e)return"(no result)";if(typeof e!="object")return bo(String(e),t);let o=t?e:Zo(e);if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${Xo}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),bo(n.join(`
219
219
  `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
220
- `);return bo(n||JSON.stringify(e,null,2),t)}return bo(JSON.stringify(e,null,2),t)}function Zr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function hs(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Gt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${pt}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Yo}\u2502 Arguments:${Ae}`);let i=ms(s.args);for(let r of i.split(`
221
- `))n.push(`${Gt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){n.push(`${fs}\u2502 Result:${Ae}`);let i=gs(s.result,t);for(let r of i.split(`
220
+ `);return bo(n||JSON.stringify(e,null,2),t)}return bo(JSON.stringify(e,null,2),t)}function Qr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function ys(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Gt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${pt}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Xo}\u2502 Arguments:${Ae}`);let i=ms(s.args);for(let r of i.split(`
221
+ `))n.push(`${Gt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){n.push(`${ps}\u2502 Result:${Ae}`);let i=hs(s.result,t);for(let r of i.split(`
222
222
  `))n.push(`${Gt}\u2502 ${r}${Ae}`);n.push(`${pt}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${pt}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${pt}\u2514\u2500${Ae}`);o.push(n.join(`
223
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Zr(s),i=[];if(i.push(`${pt}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${Yo}\u2502 Input:${Ae}`);let r=ms(s.input);for(let a of r.split(`
224
- `))i.push(`${Gt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${fs}\u2502 Output:${Ae}`);let r=gs(s.output,t);for(let a of r.split(`
223
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Qr(s),i=[];if(i.push(`${pt}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${Xo}\u2502 Input:${Ae}`);let r=ms(s.input);for(let a of r.split(`
224
+ `))i.push(`${Gt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${ps}\u2502 Output:${Ae}`);let r=hs(s.output,t);for(let a of r.split(`
225
225
  `))i.push(`${Gt}\u2502 ${a}${Ae}`);i.push(`${pt}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?i.push(`${pt}\u2514\u2500 (in progress)${Ae}`):i.push(`${pt}\u2514\u2500${Ae}`);o.push(i.join(`
226
226
  `))}return o.join(`
227
227
 
228
- `).trim()}async function ys(e){let t=e.output===ps;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ps}`),process.exit(1));let o=new B;if(e.shareId){let r;try{r=await dt()}catch{}try{let a=await o.getSharedChat(e.shareId,r),{messages:l}=await o.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(ze("chat",a),l.length===0)ze("info","No messages in this shared chat.");else for(let x of l.toReversed())ze("message",x);ze("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
229
- `),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),C=e.fullOutput??!1;for(let x of d){let b=hs(x.parts,C);if(!b)continue;let $=x.role==="user"?"You":"Assistant";console.log(`[${$}] ${zo(x.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await pe();s=r.accessToken,n=r.workspaceId}catch(r){xe(r)}if(e.chatId){let r=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let m=d===0?1:d,{chats:h}=await o.getChats(s,n,20);m>h.length&&(console.error(`Chat number ${m} not found. You have ${h.length} recent chats.`),process.exit(1));let T=h[m-1];r=T.id,a=!0,l=T,t||console.log(`Chat: ${T.title||"Untitled"}
230
- `)}let{messages:x}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(x));return}if(t){if(l&&ze("chat",l),x.length===0)ze("info","No messages in this chat.");else for(let m of x.toReversed())ze("message",m);ze("done");return}if(x.length===0){console.log("No messages in this chat.");return}let b=x.toReversed(),$=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${x.length} messages
231
- `);for(let m of b){let h=hs(m.parts,$);if(!h)continue;let T=m.role==="user"?"You":"Assistant";console.log(`[${T}] ${zo(m.createdAt)}`),console.log(h),console.log("")}return}let{chats:i}=await o.getChats(s,n,20);if(t){for(let r of i)ze("chat",r);ze("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
232
- `),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${zo(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Qr,Text as Ne}from"ink";import{jsx as je,jsxs as Pt}from"react/jsx-runtime";var At=["apiUrl","hubUrl"];function Zo(e){return At.includes(e)}async function ws(e){let t=e.action||"list",o=e.configKey,s=e.value,n=H.getEffectiveProfileName();if(t==="list"){let i=ne.getAll(),r=Object.entries(i);if(e.json){console.log(JSON.stringify(i));return}if(console.log(`Profile: ${n}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${At.join(", ")}`);return}console.log(`Configuration:
228
+ `).trim()}async function ws(e){let t=e.output===gs;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${gs}`),process.exit(1));let o=new B;if(e.shareId){let r;try{r=await dt()}catch{}try{let a=await o.getSharedChat(e.shareId,r),{messages:l}=await o.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(ze("chat",a),l.length===0)ze("info","No messages in this shared chat.");else for(let k of l.toReversed())ze("message",k);ze("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
229
+ `),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),C=e.fullOutput??!1;for(let k of d){let b=ys(k.parts,C);if(!b)continue;let S=k.role==="user"?"You":"Assistant";console.log(`[${S}] ${Yo(k.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await fe();s=r.accessToken,n=r.workspaceId}catch(r){xe(r)}if(e.chatId){let r=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let g=d===0?1:d,{chats:h}=await o.getChats(s,n,20);g>h.length&&(console.error(`Chat number ${g} not found. You have ${h.length} recent chats.`),process.exit(1));let $=h[g-1];r=$.id,a=!0,l=$,t||console.log(`Chat: ${$.title||"Untitled"}
230
+ `)}let{messages:k}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(k));return}if(t){if(l&&ze("chat",l),k.length===0)ze("info","No messages in this chat.");else for(let g of k.toReversed())ze("message",g);ze("done");return}if(k.length===0){console.log("No messages in this chat.");return}let b=k.toReversed(),S=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${k.length} messages
231
+ `);for(let g of b){let h=ys(g.parts,S);if(!h)continue;let $=g.role==="user"?"You":"Assistant";console.log(`[${$}] ${Yo(g.createdAt)}`),console.log(h),console.log("")}return}let{chats:i}=await o.getChats(s,n,20);if(t){for(let r of i)ze("chat",r);ze("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
232
+ `),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${Yo(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as ei,Text as Ne}from"ink";import{jsx as je,jsxs as Pt}from"react/jsx-runtime";var At=["apiUrl","hubUrl"];function Qo(e){return At.includes(e)}async function ks(e){let t=e.action||"list",o=e.configKey,s=e.value,n=G.getEffectiveProfileName();if(t==="list"){let i=oe.getAll(),r=Object.entries(i);if(e.json){console.log(JSON.stringify(i));return}if(console.log(`Profile: ${n}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${At.join(", ")}`);return}console.log(`Configuration:
233
233
  `);for(let[a,l]of r)console.log(` ${a}=${l}`);console.log(`
234
- Available keys: ${At.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1));let i=ne.get(o);e.json?console.log(JSON.stringify({[o]:i??null})):console.log(i||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),ne.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),ne.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ks(){let e=Me();return Pt(Qr,{flexDirection:"column",children:[je(Ne,{bold:!0,children:"entrydesk config"}),je(Ne,{children:" "}),je(Ne,{children:"Manage CLI configuration"}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Usage:"}),je(Ne,{children:" entrydesk config List all configuration"}),Pt(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Available keys:"}),Pt(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Pt(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Examples:"}),je(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),je(Ne,{children:" entrydesk config get apiUrl"}),je(Ne,{children:" entrydesk config unset apiUrl"})]})}async function xs(e){try{let t,o;try{let i=await pe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
234
+ Available keys: ${At.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1));let i=oe.get(o);e.json?console.log(JSON.stringify({[o]:i??null})):console.log(i||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function xs(){let e=Me();return Pt(ei,{flexDirection:"column",children:[je(Ne,{bold:!0,children:"entrydesk config"}),je(Ne,{children:" "}),je(Ne,{children:"Manage CLI configuration"}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Usage:"}),je(Ne,{children:" entrydesk config List all configuration"}),Pt(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Available keys:"}),Pt(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Pt(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Examples:"}),je(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),je(Ne,{children:" entrydesk config get apiUrl"}),je(Ne,{children:" entrydesk config unset apiUrl"})]})}async function bs(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
235
235
  `);for(let i of n){let r=i.connected?"connected":"disconnected";console.log(` ${i.name} (${r})`),console.log(` Provider: ${i.provider}`),console.log(` ID: ${i.id}`),console.log("")}}catch(t){xe(t)}}function Co(){console.log(`
236
236
  EntryDesk CLI - Interact with EntryDesk from your terminal
237
237
 
@@ -400,11 +400,11 @@ Local Development:
400
400
  $ entrydesk config set hubUrl http://localhost:3000
401
401
 
402
402
  For more information, visit https://entrydesk.com/docs/cli
403
- `)}import{render as li}from"ink";import{randomUUID as ei}from"crypto";import{chromium as ti}from"playwright";function oi(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function ni(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid hub URL. Please check ENTRYDESK_HUB_URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Hub URL must use http or https.");if(t.username||t.password)throw new Error("Hub URL must not include credentials.");if(!t.hostname)throw new Error("Hub URL must include a hostname.");if(t.protocol==="http:"&&!oi(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function si(e){try{let t=e.split(".");if(t.length<2)return null;let o=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-o.length%4)%4,n=o.padEnd(o.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i).exp??null}catch{return null}}async function Qo(e){let{hubUrl:t,auth:o}=Me(),s=ni(t),n=new URL("/login",s),i=ei();n.searchParams.set("cli","true"),n.searchParams.set("state",i);let r;try{r=await ti.launch({headless:!1,args:["--disable-blink-features=AutomationControlled"]})}catch(a){throw a instanceof Error&&a.message.includes("Executable")?new Error(`Chromium browser is not installed. Please run:
403
+ `)}import{render as ci}from"ink";import{randomUUID as ti}from"crypto";import{chromium as oi}from"playwright";function ni(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function si(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid hub URL. Please check ENTRYDESK_HUB_URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Hub URL must use http or https.");if(t.username||t.password)throw new Error("Hub URL must not include credentials.");if(!t.hostname)throw new Error("Hub URL must include a hostname.");if(t.protocol==="http:"&&!ni(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function ri(e){try{let t=e.split(".");if(t.length<2)return null;let o=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-o.length%4)%4,n=o.padEnd(o.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i).exp??null}catch{return null}}async function en(e){let{hubUrl:t,auth:o}=Me(),s=si(t),n=new URL("/login",s),i=ti();n.searchParams.set("cli","true"),n.searchParams.set("state",i);let r;try{r=await oi.launch({headless:!1,args:["--disable-blink-features=AutomationControlled"]})}catch(a){throw a instanceof Error&&a.message.includes("Executable")?new Error(`Chromium browser is not installed. Please run:
404
404
  npm install -g playwright
405
- npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",m=>{console.log(`[Browser Console] ${m.type()}: ${m.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(m=>{let h=new URL(m);if(h.host!==d)return!1;let T=h.pathname;if(T==="/login"||T.startsWith("/auth/"))return!1;let D=h.searchParams.get("state");return!(D&&D!==i)},{timeout:o.loginTimeout});let C=new URL("/api/auth/session",s).toString();process.env.DEBUG&&(console.log(`[DEBUG] Fetching session from: ${C}`),console.log(`[DEBUG] Current page URL: ${l.url()}`),console.log(`[DEBUG] SSL ignore enabled: ${o.ignoreSslErrors}`));let x=await l.evaluate(async m=>{try{let h=await fetch(m);if(!h.ok)throw new Error(`Failed to fetch session: ${h.status} ${h.statusText}`);return h.json()}catch(h){throw console.error("[Browser Context] Fetch error:",h),h}},C);if(!x?.accessToken)throw new Error("Failed to get access token from session");let b=si(x.accessToken);if(b&&b*1e3<=Date.now())throw new Error("Access token is expired. Please log in again.");let $=x.user?.email||"";return e?.onLoginSuccess?.($||"unknown"),{accessToken:x.accessToken,email:$,workspaceId:x.currentWorkspaceId}}catch(a){let l;throw a instanceof Error?(l=a,l.message.includes("fetch failed")&&(l=new Error(`Network request failed. This might be due to SSL certificate issues. Current SSL ignore setting: ${o.ignoreSslErrors}. Original error: ${l.message}`))):l=new Error("Browser authentication failed."),e?.onError?.(l),l}finally{await r.close()}}import{Box as Ee,Text as Le,useApp as ri,useInput as ii}from"ink";import ai from"ink-spinner";import bs from"ink-text-input";import{useState as Ht}from"react";import{jsx as ge,jsxs as Ge}from"react/jsx-runtime";function Cs(){let{exit:e}=ri(),[t,o]=Ht("email"),[s,n]=Ht(""),[i,r]=Ht(""),[a,l]=Ht(null),[d,C]=Ht(null);return ii(($,m)=>{m.escape&&e()}),Ge(Ee,{flexDirection:"column",padding:1,children:[ge(Ee,{marginBottom:1,children:ge(Le,{bold:!0,color:"cyan",children:"EntryDesk Login"})}),t==="email"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(bs,{value:s,onChange:n,onSubmit:$=>{if(!$.includes("@")){l("Please enter a valid email address");return}n($),l(null),o("password")},placeholder:"user@example.com"})]}),a&&ge(Ee,{marginTop:1,children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to continue, Esc to cancel"})})]}),t==="password"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(Le,{color:"green",children:s})]}),Ge(Ee,{children:[ge(Le,{children:"Password: "}),ge(bs,{value:i,onChange:r,onSubmit:async $=>{r($),o("loading"),l(null);try{let m=new B,{token:h,refreshToken:T}=await m.login(s,$),{workspaces:D}=await m.getWorkspaces(h),V=D[0];await $e.saveAll({accessToken:h,refreshToken:T,email:s,workspaceId:V?.id}),C(V?.name??null),o("success"),setTimeout(()=>{e()},1500)}catch(m){o("error"),m instanceof Error?m.message.includes("403")||m.message.includes("Invalid")?l("Invalid email or password"):l(m.message):l("Login failed. Please try again.")}},mask:"*",placeholder:"Enter password"})]}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to login, Esc to cancel"})})]}),t==="loading"&&Ge(Ee,{children:[ge(Le,{color:"cyan",children:ge(ai,{type:"dots"})}),ge(Le,{children:" Logging in..."})]}),t==="success"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{color:"green",children:"\u2713"}),ge(Le,{children:" Logged in as "}),ge(Le,{bold:!0,children:s})]}),d&&ge(Ee,{children:Ge(Le,{dimColor:!0,children:["Workspace: ",d]})})]}),t==="error"&&Ge(Ee,{flexDirection:"column",children:[ge(Ee,{children:ge(Le,{color:"red",children:"\u2717 Login failed"})}),a&&ge(Ee,{children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Run `entrydesk login` to try again"})})]})]})}import{jsx as ci}from"react/jsx-runtime";async function $s(e){if(!!(e.email||e.password)){(!e.email||!e.password)&&(console.error("Usage: entrydesk login --email <email> --password <password>"),console.error(" entrydesk login"),console.error(" entrydesk login --google"),console.error(" entrydesk login -i (interactive mode)"),process.exit(1));let a=new B,{token:l,refreshToken:d}=await a.login(e.email,e.password),{workspaces:C}=await a.getWorkspaces(l),x=C[0];await $e.saveAll({accessToken:l,refreshToken:d,email:e.email,workspaceId:x?.id}),e.json?console.log(JSON.stringify({email:e.email,workspaceId:x?.id,workspaceName:x?.name})):(console.log(`Logged in as ${e.email}`),x&&console.log(`Workspace: ${x.name}`));return}if(e.google){console.log("Opening browser for Google OAuth...");let a=await Qo(),l=new B,{workspaces:d}=await l.getWorkspaces(a.accessToken),C=d[0],x=a.workspaceId||C?.id;await $e.saveAll({accessToken:a.accessToken,refreshToken:"",email:a.email,workspaceId:x}),e.json?console.log(JSON.stringify({email:a.email,workspaceId:x,workspaceName:C?.name})):(console.log(`Logged in as ${a.email}`),C&&console.log(`Workspace: ${C.name}`));return}if(e.interactive){li(ci(Cs,{}));return}if(console.log("Opening browser for login..."),process.env.DEBUG){let{getApiUrl:a,getHubUrl:l}=await import("./config-QNEVFNPV.js");console.log(`[DEBUG] Hub URL: ${l()}`),console.log(`[DEBUG] API URL: ${a()}`)}let o=await Qo(),s=new B,{workspaces:n}=await s.getWorkspaces(o.accessToken),i=n[0],r=o.workspaceId||i?.id;await $e.saveAll({accessToken:o.accessToken,refreshToken:"",email:o.email,workspaceId:r}),e.json?console.log(JSON.stringify({email:o.email,workspaceId:r,workspaceName:i?.name})):(console.log(`Logged in as ${o.email}`),i&&console.log(`Workspace: ${i.name}`))}async function Ss(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{await new B().revokeToken(t.refreshToken)}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){xe(t)}}import ui from"http";import{Client as di}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as fi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as pi}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as gi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as hi,ListToolsRequestSchema as yi}from"@modelcontextprotocol/sdk/types.js";async function wi(e,t,o){let s=new di({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new fi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Ts(e){let t=new pi({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(yi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(hi,async o=>{let{name:s,arguments:n}=o.params,i=await e.callTool({name:s,arguments:n}),r=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&r.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:r,structuredContent:i.structuredContent,isError:i.isError}}),t}async function ki(e,t){let o=ui.createServer(async(s,n)=>{if(s.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),n.writeHead(204),n.end();return}if(s.url!=="/mcp"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Not found"}));return}let i=Ts(e),r=new gi({sessionIdGenerator:void 0});if(n.setHeader("Access-Control-Allow-Origin","*"),n.on("close",()=>{r.close(),i.close()}),await i.connect(r),s.method==="POST"){let a="";s.on("data",l=>{a+=l.toString()}),s.on("end",async()=>{try{let l=JSON.parse(a);await r.handleRequest(s,n,l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Invalid JSON"}))}})}else await r.handleRequest(s,n)});o.listen(t,()=>{console.error(`EntryDesk MCP server running at http://localhost:${t}/mcp`),console.error("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{console.error(`
406
- Shutting down...`),o.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{o.close(),await e.close(),process.exit(0)})}async function xi(e){let t=Ts(e),o=new mi;o.onclose=async()=>{await e.close()},await t.connect(o)}async function vs(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{console.error("[entrydesk-mcp] Starting MCP server...");let t,o;try{let r=await pe();t=r.accessToken,o=r.workspaceId}catch(r){let a=r instanceof Error?r.message:"Authentication failed";console.error(a),process.exit(1)}let{apiUrl:s,mcp:n}=Me();console.error(`[entrydesk-mcp] Connecting to ${s}...`),console.error(`[entrydesk-mcp] Workspace: ${o}`);let i=await wi(s,t,o);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||n.httpPort;await ki(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await xi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Is(e){try{let t,o;try{let i=await pe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
407
- `);for(let i of n)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){xe(t)}}function bi(){console.log(`
405
+ npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",g=>{console.log(`[Browser Console] ${g.type()}: ${g.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(g=>{let h=new URL(g);if(h.host!==d)return!1;let $=h.pathname;if($==="/login"||$.startsWith("/auth/"))return!1;let D=h.searchParams.get("state");return!(D&&D!==i)},{timeout:o.loginTimeout});let C=new URL("/api/auth/session",s).toString();process.env.DEBUG&&(console.log(`[DEBUG] Fetching session from: ${C}`),console.log(`[DEBUG] Current page URL: ${l.url()}`),console.log(`[DEBUG] SSL ignore enabled: ${o.ignoreSslErrors}`));let k=await l.evaluate(async g=>{try{let h=await fetch(g);if(!h.ok)throw new Error(`Failed to fetch session: ${h.status} ${h.statusText}`);return h.json()}catch(h){throw console.error("[Browser Context] Fetch error:",h),h}},C);if(!k?.accessToken)throw new Error("Failed to get access token from session");let b=ri(k.accessToken);if(b&&b*1e3<=Date.now())throw new Error("Access token is expired. Please log in again.");let S=k.user?.email||"";return e?.onLoginSuccess?.(S||"unknown"),{accessToken:k.accessToken,email:S,workspaceId:k.currentWorkspaceId}}catch(a){let l;throw a instanceof Error?(l=a,l.message.includes("fetch failed")&&(l=new Error(`Network request failed. This might be due to SSL certificate issues. Current SSL ignore setting: ${o.ignoreSslErrors}. Original error: ${l.message}`))):l=new Error("Browser authentication failed."),e?.onError?.(l),l}finally{await r.close()}}import{Box as Ee,Text as Le,useApp as ii,useInput as ai}from"ink";import li from"ink-spinner";import Cs from"ink-text-input";import{useState as Ht}from"react";import{jsx as me,jsxs as Ge}from"react/jsx-runtime";function Ss(){let{exit:e}=ii(),[t,o]=Ht("email"),[s,n]=Ht(""),[i,r]=Ht(""),[a,l]=Ht(null),[d,C]=Ht(null);return ai((S,g)=>{g.escape&&e()}),Ge(Ee,{flexDirection:"column",padding:1,children:[me(Ee,{marginBottom:1,children:me(Le,{bold:!0,color:"cyan",children:"EntryDesk Login"})}),t==="email"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{children:"Email: "}),me(Cs,{value:s,onChange:n,onSubmit:S=>{if(!S.includes("@")){l("Please enter a valid email address");return}n(S),l(null),o("password")},placeholder:"user@example.com"})]}),a&&me(Ee,{marginTop:1,children:me(Le,{color:"red",children:a})}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Press Enter to continue, Esc to cancel"})})]}),t==="password"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{children:"Email: "}),me(Le,{color:"green",children:s})]}),Ge(Ee,{children:[me(Le,{children:"Password: "}),me(Cs,{value:i,onChange:r,onSubmit:async S=>{r(S),o("loading"),l(null);try{let g=new B,{token:h,refreshToken:$}=await g.login(s,S),{workspaces:D}=await g.getWorkspaces(h),H=D[0];await Ce.saveAll({accessToken:h,refreshToken:$,email:s,workspaceId:H?.id}),C(H?.name??null),o("success"),setTimeout(()=>{e()},1500)}catch(g){o("error"),g instanceof Error?g.message.includes("403")||g.message.includes("Invalid")?l("Invalid email or password"):l(g.message):l("Login failed. Please try again.")}},mask:"*",placeholder:"Enter password"})]}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Press Enter to login, Esc to cancel"})})]}),t==="loading"&&Ge(Ee,{children:[me(Le,{color:"cyan",children:me(li,{type:"dots"})}),me(Le,{children:" Logging in..."})]}),t==="success"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[me(Le,{color:"green",children:"\u2713"}),me(Le,{children:" Logged in as "}),me(Le,{bold:!0,children:s})]}),d&&me(Ee,{children:Ge(Le,{dimColor:!0,children:["Workspace: ",d]})})]}),t==="error"&&Ge(Ee,{flexDirection:"column",children:[me(Ee,{children:me(Le,{color:"red",children:"\u2717 Login failed"})}),a&&me(Ee,{children:me(Le,{color:"red",children:a})}),me(Ee,{marginTop:1,children:me(Le,{dimColor:!0,children:"Run `entrydesk login` to try again"})})]})]})}import{jsx as ui}from"react/jsx-runtime";async function $s(e){if(!!(e.email||e.password)){(!e.email||!e.password)&&(console.error("Usage: entrydesk login --email <email> --password <password>"),console.error(" entrydesk login"),console.error(" entrydesk login --google"),console.error(" entrydesk login -i (interactive mode)"),process.exit(1));let a=new B,{token:l,refreshToken:d}=await a.login(e.email,e.password),{workspaces:C}=await a.getWorkspaces(l),k=C[0];await Ce.saveAll({accessToken:l,refreshToken:d,email:e.email,workspaceId:k?.id}),e.json?console.log(JSON.stringify({email:e.email,workspaceId:k?.id,workspaceName:k?.name})):(console.log(`Logged in as ${e.email}`),k&&console.log(`Workspace: ${k.name}`));return}if(e.google){console.log("Opening browser for Google OAuth...");let a=await en(),l=new B,{workspaces:d}=await l.getWorkspaces(a.accessToken),C=d[0],k=a.workspaceId||C?.id;await Ce.saveAll({accessToken:a.accessToken,refreshToken:"",email:a.email,workspaceId:k}),e.json?console.log(JSON.stringify({email:a.email,workspaceId:k,workspaceName:C?.name})):(console.log(`Logged in as ${a.email}`),C&&console.log(`Workspace: ${C.name}`));return}if(e.interactive){ci(ui(Ss,{}));return}if(console.log("Opening browser for login..."),process.env.DEBUG){let{getApiUrl:a,getHubUrl:l}=await import("./config-MDF3SS7Z.js");console.log(`[DEBUG] Hub URL: ${l()}`),console.log(`[DEBUG] API URL: ${a()}`)}let o=await en(),s=new B,{workspaces:n}=await s.getWorkspaces(o.accessToken),i=n[0],r=o.workspaceId||i?.id;await Ce.saveAll({accessToken:o.accessToken,refreshToken:"",email:o.email,workspaceId:r}),e.json?console.log(JSON.stringify({email:o.email,workspaceId:r,workspaceName:i?.name})):(console.log(`Logged in as ${o.email}`),i&&console.log(`Workspace: ${i.name}`))}async function Ts(e){try{let t=await Ce.getAll();if(!t){console.log("Not logged in");return}try{await new B().revokeToken(t.refreshToken)}catch{}await Ce.clear(),console.log("Logged out successfully")}catch(t){xe(t)}}import di from"http";import{Client as fi}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as pi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as gi}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as hi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as yi,ListToolsRequestSchema as wi}from"@modelcontextprotocol/sdk/types.js";async function ki(e,t,o){let s=new fi({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new pi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Is(e){let t=new gi({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(wi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(yi,async o=>{let{name:s,arguments:n}=o.params,i=await e.callTool({name:s,arguments:n}),r=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&r.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:r,structuredContent:i.structuredContent,isError:i.isError}}),t}async function xi(e,t){let o=di.createServer(async(s,n)=>{if(s.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),n.writeHead(204),n.end();return}if(s.url!=="/mcp"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Not found"}));return}let i=Is(e),r=new hi({sessionIdGenerator:void 0});if(n.setHeader("Access-Control-Allow-Origin","*"),n.on("close",()=>{r.close(),i.close()}),await i.connect(r),s.method==="POST"){let a="";s.on("data",l=>{a+=l.toString()}),s.on("end",async()=>{try{let l=JSON.parse(a);await r.handleRequest(s,n,l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Invalid JSON"}))}})}else await r.handleRequest(s,n)});o.listen(t,()=>{console.error(`EntryDesk MCP server running at http://localhost:${t}/mcp`),console.error("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{console.error(`
406
+ Shutting down...`),o.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{o.close(),await e.close(),process.exit(0)})}async function bi(e){let t=Is(e),o=new mi;o.onclose=async()=>{await e.close()},await t.connect(o)}async function vs(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{console.error("[entrydesk-mcp] Starting MCP server...");let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let a=r instanceof Error?r.message:"Authentication failed";console.error(a),process.exit(1)}let{apiUrl:s,mcp:n}=Me();console.error(`[entrydesk-mcp] Connecting to ${s}...`),console.error(`[entrydesk-mcp] Workspace: ${o}`);let i=await ki(s,t,o);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||n.httpPort;await xi(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await bi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Ps(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
407
+ `);for(let i of n)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){xe(t)}}function Ci(){console.log(`
408
408
  Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
409
409
 
410
410
  Commands:
@@ -419,7 +419,7 @@ Commands:
419
419
 
420
420
  Flags:
421
421
  --json Output JSON
422
- `)}function Vt(e,t){if(e)return e;if(t&&H.getProfileCount()===1)return H.getProfileNames()[0];throw new Dt("Profile name is required when multiple profiles exist.")}function Ci(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function Ps(e){try{let t=e.action||"list",o=H.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){bi();return}if(t==="list"){let i=H.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:i.map(r=>({name:r,isCurrent:r===o}))}));return}console.log(`Profiles (${i.length}):`);for(let r of i)console.log(` ${r}${r===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let i=Vt(s,!0),r=ne.getAll(i),a=await $e.getAll(i),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:i,isCurrent:i===o,config:r,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${i}${i===o?" (current)":""}`),console.log(` API URL: ${r.apiUrl??"default"}`),console.log(` Hub URL: ${r.hubUrl??"default"}`),console.log(` Model: ${r.model?.default??"unset"}`);let d=r.connectors?.defaults&&r.connectors.defaults.length>0?r.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${Ci(r.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let i=s||H.DEFAULT_PROFILE;if(H.createProfile(i),e.json){console.log(JSON.stringify({name:i,created:!0}));return}console.log(`Profile created: ${i}`);return}if(t==="use"||t==="switch"){let i=Vt(s,!0);if(H.setCurrentProfile(i),e.json){console.log(JSON.stringify({name:i,current:!0}));return}console.log(`Switched to profile: ${i}`);return}if(t==="delete"||t==="remove"||t==="rm"){let i=Vt(s,!0),r=H.deleteProfile(i);if(e.json){console.log(JSON.stringify({deleted:i,currentProfile:r.currentProfile}));return}console.log(`Profile deleted: ${i}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let i=Vt(s,!0);if(!n)throw new Dt("New profile name is required.");let r=H.renameProfile(i,n);if(e.json){console.log(JSON.stringify({renamed:i,name:n,currentProfile:r.currentProfile}));return}console.log(`Profile renamed: ${i} -> ${n}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="clone"||t==="copy"){let i=Vt(s,!0);if(!n)throw new Dt("Target profile name is required.");let r=ne.getAll(i);if(H.createProfile(n),ne.setAll(r,n),await $e.clear(n),e.json){console.log(JSON.stringify({source:i,name:n,cloned:!0}));return}console.log(`Profile cloned: ${i} -> ${n}`);return}throw new Dt(`Unknown profile command: ${t}`)}catch(t){xe(t)}}function Kt(){console.log(`
422
+ `)}function Vt(e,t){if(e)return e;if(t&&G.getProfileCount()===1)return G.getProfileNames()[0];throw new Dt("Profile name is required when multiple profiles exist.")}function Si(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function As(e){try{let t=e.action||"list",o=G.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){Ci();return}if(t==="list"){let i=G.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:i.map(r=>({name:r,isCurrent:r===o}))}));return}console.log(`Profiles (${i.length}):`);for(let r of i)console.log(` ${r}${r===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let i=Vt(s,!0),r=oe.getAll(i),a=await Ce.getAll(i),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:i,isCurrent:i===o,config:r,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${i}${i===o?" (current)":""}`),console.log(` API URL: ${r.apiUrl??"default"}`),console.log(` Hub URL: ${r.hubUrl??"default"}`),console.log(` Model: ${r.model?.default??"unset"}`);let d=r.connectors?.defaults&&r.connectors.defaults.length>0?r.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${Si(r.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let i=s||G.DEFAULT_PROFILE;if(G.createProfile(i),e.json){console.log(JSON.stringify({name:i,created:!0}));return}console.log(`Profile created: ${i}`);return}if(t==="use"||t==="switch"){let i=Vt(s,!0);if(G.setCurrentProfile(i),e.json){console.log(JSON.stringify({name:i,current:!0}));return}console.log(`Switched to profile: ${i}`);return}if(t==="delete"||t==="remove"||t==="rm"){let i=Vt(s,!0),r=G.deleteProfile(i);if(e.json){console.log(JSON.stringify({deleted:i,currentProfile:r.currentProfile}));return}console.log(`Profile deleted: ${i}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let i=Vt(s,!0);if(!n)throw new Dt("New profile name is required.");let r=G.renameProfile(i,n);if(e.json){console.log(JSON.stringify({renamed:i,name:n,currentProfile:r.currentProfile}));return}console.log(`Profile renamed: ${i} -> ${n}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="clone"||t==="copy"){let i=Vt(s,!0);if(!n)throw new Dt("Target profile name is required.");let r=oe.getAll(i);if(G.createProfile(n),oe.setAll(r,n),await Ce.clear(n),e.json){console.log(JSON.stringify({source:i,name:n,cloned:!0}));return}console.log(`Profile cloned: ${i} -> ${n}`);return}throw new Dt(`Unknown profile command: ${t}`)}catch(t){xe(t)}}function Kt(){console.log(`
423
423
  Usage: entrydesk schedules [list|get|create|delete] [options]
424
424
 
425
425
  Commands:
@@ -445,7 +445,7 @@ Create Options:
445
445
 
446
446
  Flags:
447
447
  --json Output JSON
448
- `)}function 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 qt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,i=parseInt(s[2],10),r=parseInt(s[3],10),a=n*(i*60+r)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function $i(e){console.log(`
448
+ `)}function Ns(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function qt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,i=parseInt(s[2],10),r=parseInt(s[3],10),a=n*(i*60+r)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function $i(e){console.log(`
449
449
  Schedule: ${e.name}
450
450
  ${"\u2501".repeat(50)}
451
451
  ID: ${e.id}
@@ -457,13 +457,13 @@ Prompt:
457
457
  ${e.prompt.slice(0,200)}${e.prompt.length>200?"...":""}
458
458
 
459
459
  Schedule:
460
- ${As(e.config)}
460
+ ${Ns(e.config)}
461
461
 
462
462
  Next Run: ${e.nextRunAt?qt(e.nextRunAt,e.utcOffset):"-"}
463
463
  Created: ${qt(e.createdAt,e.utcOffset)}
464
464
  Updated: ${qt(e.updatedAt,e.utcOffset)}
465
- `)}function Si(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function Ns(e){try{if(e.help){Kt();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1));let d=await i.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}$i(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Kt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:Si(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?qt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1)),await i.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Kt(),process.exit(1));let r=[],a;do{let l=await i.getSchedules(o,s,{nextKey:a,limit:100});r.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
466
- `);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${As(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?qt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){xe(t)}}import Ti from"fs";import Nt from"fs/promises";import Es from"os";import st from"path";import vi from"archiver";function $o(){console.log(`
465
+ `)}function Ti(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function Es(e){try{if(e.help){Kt();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1));let d=await i.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}$i(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Kt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:Ti(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?qt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1)),await i.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Kt(),process.exit(1));let r=[],a;do{let l=await i.getSchedules(o,s,{nextKey:a,limit:100});r.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
466
+ `);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${Ns(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?qt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){xe(t)}}import Ii from"fs";import Nt from"fs/promises";import _s from"os";import st from"path";import vi from"archiver";function So(){console.log(`
467
467
  Usage: entrydesk skills [list|upload|delete|versions] [options]
468
468
 
469
469
  Commands:
@@ -477,17 +477,17 @@ Options:
477
477
  --me Only list skills created by me
478
478
  --force Overwrite an existing skill with the same name
479
479
  --json Output JSON (for list/upload/versions)
480
- `)}function Ii(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Pi(e){let t=await Nt.realpath(e),o=[process.cwd(),Es.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await Nt.realpath(i)}catch{return st.resolve(i)}}))).some(i=>Ii(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ai(e){let t=await Nt.mkdtemp(st.join(Es.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ti.createWriteStream(o),r=vi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function _s(e){let t,o;try{let a=await pe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new B;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),$o(),process.exit(1));let l=st.resolve(a),d;try{d=await Nt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let C=l,x=null;try{try{await Pi(l)}catch(h){let T=h instanceof Error?h.message:"Invalid upload path.";console.error(T),process.exit(1)}if(d.isDirectory()){let h=await Ai(l);C=h.zipPath,x=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));st.extname(C).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await Nt.readFile(C),$=new FormData;$.append("file",new Blob([b],{type:"application/zip"}),st.basename(C)),e.force&&$.append("force","true");let m;try{m=await n.uploadSkill(t,o,$)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let T=h;if(T.response&&T.response.status===409){try{(await T.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw h}if(e.json){console.log(JSON.stringify(m));return}console.log(`Uploaded skill: ${m.name}`),console.log(` ID: ${m.id}`),console.log(` Version ID: ${m.versionId}`),console.log(` Description: ${m.description}`);return}finally{x&&await Nt.rm(x,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),$o(),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."),$o(),process.exit(1));let l=[],d;do{let b=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});l.push(...b.skills),d=b.nextKey}while(d);let C=l.find(b=>b.name===a);C||(console.error(`Skill not found: ${a}`),process.exit(1));let x=await n.listSkillVersions(t,o,C.id);if(e.json){console.log(JSON.stringify(x));return}if(console.log(`Versions for skill "${x.skillName}":
481
- `),x.versions.length===0){console.log(" No versions found.");return}for(let b of x.versions){let $=new Date(b.createdAt);console.log(` ${$.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}`),$o(),process.exit(1));let i=[],r;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:r,limit:100});i.push(...a.skills),r=a.nextKey}while(r);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${i.length}):
482
- `);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Ls(e){try{let t=H.getEffectiveProfileName(),o=await $e.getAll(),s={model:ne.getDefaultModel(),connectors:ne.getDefaultConnectorIds(),capabilities:ne.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let i=new B,r=await dt(),{workspaces:a}=await i.getWorkspaces(r);n=a.find(d=>d.id===o.workspaceId)?.name}catch(i){if(i instanceof Qe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){xe(t)}}import Wi from"fs";import{Client as Ni}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ei}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function _i(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await pe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Me().apiUrl);let n=new Ni({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new Ei(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function So(){return _i()}import tn from"fs/promises";import Li from"os";import zt from"path";var en=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,Et={green:en?"\x1B[32m":"",yellow:en?"\x1B[33m":"",reset:en?"\x1B[0m":""},Di=10*1024,Ds=8*1024,Os=2*1024,Oi=100,Ri=100;function Ui(){return zt.join(Li.homedir(),".entrydesk","tool-results")}function ji(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Oi);return!t||t==="."||t===".."?"unnamed_tool":t}function Bi(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 Fi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=ji(e);return`${o}_${s}.json`}async function Rs(e,t){try{return await tn.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function Us(e,t){try{let o=Ui();await tn.mkdir(o,{recursive:!0});let s=Fi(e),n=zt.extname(s),i=s.slice(0,-n.length),r=Bi(t),a=zt.join(o,s);if(await Rs(a,r))return a;for(let C=1;C<=Ri;C++){let x=zt.join(o,`${i}-${C}${n}`);if(await Rs(x,r))return x}let l=Math.random().toString(36).slice(2,10),d=zt.join(o,`${i}-${l}${n}`);return await tn.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Et.yellow}Warning: Could not save result to file: ${s}${Et.reset}`),null}}function js(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Di)return e;let s=e.slice(0,Ds),n=e.slice(-Os),r=((o-Ds-Os)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(l+=`
480
+ `)}function Pi(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Ai(e){let t=await Nt.realpath(e),o=[process.cwd(),_s.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await Nt.realpath(i)}catch{return st.resolve(i)}}))).some(i=>Pi(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ni(e){let t=await Nt.mkdtemp(st.join(_s.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ii.createWriteStream(o),r=vi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function Ls(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new B;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),So(),process.exit(1));let l=st.resolve(a),d;try{d=await Nt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let C=l,k=null;try{try{await Ai(l)}catch(h){let $=h instanceof Error?h.message:"Invalid upload path.";console.error($),process.exit(1)}if(d.isDirectory()){let h=await Ni(l);C=h.zipPath,k=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));st.extname(C).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await Nt.readFile(C),S=new FormData;S.append("file",new Blob([b],{type:"application/zip"}),st.basename(C)),e.force&&S.append("force","true");let g;try{g=await n.uploadSkill(t,o,S)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let $=h;if($.response&&$.response.status===409){try{(await $.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw h}if(e.json){console.log(JSON.stringify(g));return}console.log(`Uploaded skill: ${g.name}`),console.log(` ID: ${g.id}`),console.log(` Version ID: ${g.versionId}`),console.log(` Description: ${g.description}`);return}finally{k&&await Nt.rm(k,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),So(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(s==="versions"){let a=e.configKey;a||(console.error("Missing skill name."),So(),process.exit(1));let l=[],d;do{let b=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});l.push(...b.skills),d=b.nextKey}while(d);let C=l.find(b=>b.name===a);C||(console.error(`Skill not found: ${a}`),process.exit(1));let k=await n.listSkillVersions(t,o,C.id);if(e.json){console.log(JSON.stringify(k));return}if(console.log(`Versions for skill "${k.skillName}":
481
+ `),k.versions.length===0){console.log(" No versions found.");return}for(let b of k.versions){let S=new Date(b.createdAt);console.log(` ${S.toLocaleString()}`),console.log(` ID: ${b.id}`),console.log(` Description: ${b.description.slice(0,80)}`),console.log(` Created by: ${b.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),So(),process.exit(1));let i=[],r;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:r,limit:100});i.push(...a.skills),r=a.nextKey}while(r);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${i.length}):
482
+ `);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Ds(e){try{let t=G.getEffectiveProfileName(),o=await Ce.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let i=new B,r=await dt(),{workspaces:a}=await i.getWorkspaces(r);n=a.find(d=>d.id===o.workspaceId)?.name}catch(i){if(i instanceof Qe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){xe(t)}}import Mi from"fs";import{Client as Ei}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as _i}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Li(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Me().apiUrl);let n=new Ei({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new _i(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function $o(){return Li()}import on from"fs/promises";import Di from"os";import zt from"path";var tn=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,Et={green:tn?"\x1B[32m":"",yellow:tn?"\x1B[33m":"",reset:tn?"\x1B[0m":""},Oi=10*1024,Os=8*1024,Rs=2*1024,Ri=100,Ui=100;function ji(){return zt.join(Di.homedir(),".entrydesk","tool-results")}function Bi(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Ri);return!t||t==="."||t===".."?"unnamed_tool":t}function Fi(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Wi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=Bi(e);return`${o}_${s}.json`}async function Us(e,t){try{return await on.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function js(e,t){try{let o=ji();await on.mkdir(o,{recursive:!0});let s=Wi(e),n=zt.extname(s),i=s.slice(0,-n.length),r=Fi(t),a=zt.join(o,s);if(await Us(a,r))return a;for(let C=1;C<=Ui;C++){let k=zt.join(o,`${i}-${C}${n}`);if(await Us(k,r))return k}let l=Math.random().toString(36).slice(2,10),d=zt.join(o,`${i}-${l}${n}`);return await on.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Et.yellow}Warning: Could not save result to file: ${s}${Et.reset}`),null}}function Bs(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Oi)return e;let s=e.slice(0,Os),n=e.slice(-Rs),r=((o-Os-Rs)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(l+=`
483
483
  Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
484
484
 
485
485
  ${l}
486
486
 
487
- ${n}`}function Bs(e){console.log(`${Et.green}Tool execution result saved to: ${e}${Et.reset}`),console.log()}function Fs(){console.log(`${Et.green}Tool execution result:${Et.reset}`)}function Mi(e){return e.split("__")[0]??e}function yt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function _t(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?yt("AUTH_MISSING",s,t):yt(o,s,t)}async function Ji(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},i=C=>{s||(s=!0,n(),e(C))},r=setTimeout(()=>{o||i(null)},100),a=C=>{o=!0,clearTimeout(r),t.push(C)},l=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Yt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Gi(e,t){if(e)return e;if(t)try{return Wi.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Yt(`Failed to read input file: ${n}`)}let o=await Ji();if(o)return o;throw new Yt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Hi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
488
- `)}function Vi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
489
- `)}async function Ki(e,t){let o=await So().catch(s=>{_t(s,e)});try{let n=(await o.listTools()).tools;if(t){let i=t.toLowerCase();n=n.filter(r=>Mi(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(n,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${i}:
490
- `);for(let r of n)console.log(Hi(r)),console.log()}}catch(s){_t(s,e)}finally{await o.close().catch(()=>{})}}async function qi(e,t){let o=await So().catch(s=>{_t(s,t)});try{let n=(await o.listTools()).tools.find(i=>i.name===e);n||yt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Vi(n))}catch(s){_t(s,t)}finally{await o.close().catch(()=>{})}}async function zi(e,t,o){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";yt("INVALID_INPUT",a,o)}let n=await So().catch(r=>{_t(r,o,"TOOL_CALL_FAILED")}),i=!1;try{let r=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(r,null,2));else{let a=await Us(e,r);a&&Bs(a),Fs();let l=r.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),C=js(d,a);console.log(C)}}r.isError&&(i=!0)}catch(r){_t(r,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}i&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ki(t,e.prefix);break;case"get":e.name||yt("INVALID_INPUT","Tool name is required",t),await qi(e.name,t);break;case"call":{e.name||yt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Gi(e.input,e.inputFile)}catch(s){throw s instanceof Yt&&yt("INVALID_INPUT",s.message,t),s}await zi(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
487
+ ${n}`}function Fs(e){console.log(`${Et.green}Tool execution result saved to: ${e}${Et.reset}`),console.log()}function Ws(){console.log(`${Et.green}Tool execution result:${Et.reset}`)}function Ji(e){return e.split("__")[0]??e}function yt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function _t(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?yt("AUTH_MISSING",s,t):yt(o,s,t)}async function Gi(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},i=C=>{s||(s=!0,n(),e(C))},r=setTimeout(()=>{o||i(null)},100),a=C=>{o=!0,clearTimeout(r),t.push(C)},l=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Yt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Hi(e,t){if(e)return e;if(t)try{return Mi.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Yt(`Failed to read input file: ${n}`)}let o=await Gi();if(o)return o;throw new Yt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Vi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
488
+ `)}function Ki(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
489
+ `)}async function qi(e,t){let o=await $o().catch(s=>{_t(s,e)});try{let n=(await o.listTools()).tools;if(t){let i=t.toLowerCase();n=n.filter(r=>Ji(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(n,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${i}:
490
+ `);for(let r of n)console.log(Vi(r)),console.log()}}catch(s){_t(s,e)}finally{await o.close().catch(()=>{})}}async function zi(e,t){let o=await $o().catch(s=>{_t(s,t)});try{let n=(await o.listTools()).tools.find(i=>i.name===e);n||yt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Ki(n))}catch(s){_t(s,t)}finally{await o.close().catch(()=>{})}}async function Yi(e,t,o){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";yt("INVALID_INPUT",a,o)}let n=await $o().catch(r=>{_t(r,o,"TOOL_CALL_FAILED")}),i=!1;try{let r=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(r,null,2));else{let a=await js(e,r);a&&Fs(a),Ws();let l=r.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),C=Bs(d,a);console.log(C)}}r.isError&&(i=!0)}catch(r){_t(r,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}i&&process.exit(1)}async function Ms(e){let t=e.json??!1;switch(e.action){case"list":await qi(t,e.prefix);break;case"get":e.name||yt("INVALID_INPUT","Tool name is required",t),await zi(e.name,t);break;case"call":{e.name||yt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Hi(e.input,e.inputFile)}catch(s){throw s instanceof Yt&&yt("INVALID_INPUT",s.message,t),s}await Yi(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
491
491
 
492
492
  Actions:
493
493
  list List all available tools
@@ -512,7 +512,7 @@ Examples:
512
512
  entrydesk tool call agent__search_agents --input '{"limit": 5}'
513
513
  entrydesk tool call agent__search_agents --input-file input.json
514
514
  echo '{"limit": 5}' | entrydesk tool call agent__search_agents
515
- `);break}}function Yi(){console.log(`
515
+ `);break}}function Xi(){console.log(`
516
516
  Usage: entrydesk usage [options]
517
517
 
518
518
  Options:
@@ -525,10 +525,10 @@ Examples:
525
525
  entrydesk usage --limit 10 # Show top 10 users
526
526
  entrydesk usage --sort-by operations # Sort by operation count
527
527
  entrydesk usage --json # JSON output
528
- `)}async function Ms(e){if(e.help){Yi();return}let t,o;try{let m=await pe();t=m.accessToken,o=m.workspaceId}catch(m){let h=m instanceof Error?m.message:"Authentication failed";console.error(h),process.exit(1)}let s=new B,n=[],i,r=0,a=100;do{let m=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...m.monthlyUsages),i=m.nextKey,r++,r>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
529
- `);let l=0,d=0;for(let m of n)l+=parseFloat(m.totalCost),d+=m.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
530
- `);let C=e.sortBy||"cost",x=[...n].toSorted((m,h)=>C==="cost"?parseFloat(h.totalCost)-parseFloat(m.totalCost):h.operationCount-m.operationCount),b=e.limit&&e.limit>0?e.limit:x.length,$=x.slice(0,b);console.log(`Usage by User (sorted by ${C}, showing ${$.length} of ${n.length}):
531
- `);for(let m of $){let h=parseFloat(m.totalCost);console.log(` ${m.user.name} (${m.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${m.operationCount.toLocaleString()}`),console.log("")}$.length<n.length&&console.log(`... and ${n.length-$.length} more users`)}function on(){console.log("entrydesk 1.7.10")}function nn(){console.log(`
528
+ `)}async function Js(e){if(e.help){Xi();return}let t,o;try{let g=await fe();t=g.accessToken,o=g.workspaceId}catch(g){let h=g instanceof Error?g.message:"Authentication failed";console.error(h),process.exit(1)}let s=new B,n=[],i,r=0,a=100;do{let g=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...g.monthlyUsages),i=g.nextKey,r++,r>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
529
+ `);let l=0,d=0;for(let g of n)l+=parseFloat(g.totalCost),d+=g.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
530
+ `);let C=e.sortBy||"cost",k=[...n].toSorted((g,h)=>C==="cost"?parseFloat(h.totalCost)-parseFloat(g.totalCost):h.operationCount-g.operationCount),b=e.limit&&e.limit>0?e.limit:k.length,S=k.slice(0,b);console.log(`Usage by User (sorted by ${C}, showing ${S.length} of ${n.length}):
531
+ `);for(let g of S){let h=parseFloat(g.totalCost);console.log(` ${g.user.name} (${g.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${g.operationCount.toLocaleString()}`),console.log("")}S.length<n.length&&console.log(`... and ${n.length-S.length} more users`)}function nn(){console.log("entrydesk 1.7.11")}function sn(){console.log(`
532
532
  Usage: entrydesk workspaces [list|switch|use] [options]
533
533
 
534
534
  Commands:
@@ -538,6 +538,6 @@ Commands:
538
538
 
539
539
  Flags:
540
540
  --json Output JSON
541
- `)}async function Js(e){if(e.help){nn();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await dt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",i=new B;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),nn(),process.exit(1));let{workspaces:l}=await i.getWorkspaces(t),d=l.find(C=>C.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
542
- Available workspaces:`);for(let C of l)console.error(` ${C.name}: ${C.id}`);process.exit(1)}if(await $e.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),nn(),process.exit(1));let{workspaces:r}=await i.getWorkspaces(t);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${r.length}):
543
- `);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Gs(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":r==="--google"||r==="-g"?n.google=!0:r==="-i"||r==="--interactive"?n.interactive=!0:r==="--email"?n.email=e[++i]:r==="--password"&&(n.password=e[++i]);break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(l=>l.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as ea}from"react/jsx-runtime";var He=process.argv.slice(2);(He[0]==="--help"||He[0]==="-h")&&(Co(),process.exit(0));(He[0]==="--version"||He[0]==="-v")&&(on(),process.exit(0));var sn=!He[0]||He[0].startsWith("-"),Zi=sn?"chat":He[0],be=Gs(He,Zi,sn);sn&&be.command==="chat"&&(be.interactive=!0);async function Qi(){try{if(be.command!=="profile"){let e=be.profile||H.getCurrentProfileName();H.ensureProfileExists(e),H.setOverrideProfile(e)}switch(be.command){case"login":await $s(be);break;case"logout":await Ss(be);break;case"status":await Ls(be);break;case"workspaces":await Js(be);break;case"agents":await an(be);break;case"models":await Is(be);break;case"connectors":await xs(be);break;case"skills":await _s(be);break;case"schedules":await Ns(be);break;case"chats":await ys(be);break;case"budget":await ln(be);break;case"usage":await Ms(be);break;case"config":be.action==="help"||He[1]==="--help"?Xi(ea(ks,{})):await ws(be);break;case"profile":await Ps(be);break;case"chat":He[1]==="--help"||He[1]==="-h"?Co():await ds(be);break;case"mcp-server":await vs({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ws(be);break;case"version":on();break;default:Co();break}}catch(e){xe(e)}}Qi();
541
+ `)}async function Gs(e){if(e.help){sn();return}let t,s=(await Ce.getAll())?.workspaceId;try{t=await dt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",i=new B;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),sn(),process.exit(1));let{workspaces:l}=await i.getWorkspaces(t),d=l.find(C=>C.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
542
+ Available workspaces:`);for(let C of l)console.error(` ${C.name}: ${C.id}`);process.exit(1)}if(await Ce.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),sn(),process.exit(1));let{workspaces:r}=await i.getWorkspaces(t);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${r.length}):
543
+ `);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Hs(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":r==="--google"||r==="-g"?n.google=!0:r==="-i"||r==="--interactive"?n.interactive=!0:r==="--email"?n.email=e[++i]:r==="--password"&&(n.password=e[++i]);break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(l=>l.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as ta}from"react/jsx-runtime";var He=process.argv.slice(2);(He[0]==="--help"||He[0]==="-h")&&(Co(),process.exit(0));(He[0]==="--version"||He[0]==="-v")&&(nn(),process.exit(0));var rn=!He[0]||He[0].startsWith("-"),Qi=rn?"chat":He[0],be=Hs(He,Qi,rn);rn&&be.command==="chat"&&(be.interactive=!0);async function ea(){try{if(be.command!=="profile"){let e=be.profile||G.getCurrentProfileName();G.ensureProfileExists(e),G.setOverrideProfile(e)}switch(be.command){case"login":await $s(be);break;case"logout":await Ts(be);break;case"status":await Ds(be);break;case"workspaces":await Gs(be);break;case"agents":await ln(be);break;case"models":await Ps(be);break;case"connectors":await bs(be);break;case"skills":await Ls(be);break;case"schedules":await Es(be);break;case"chats":await ws(be);break;case"budget":await cn(be);break;case"usage":await Js(be);break;case"config":be.action==="help"||He[1]==="--help"?Zi(ta(xs,{})):await ks(be);break;case"profile":await As(be);break;case"chat":He[1]==="--help"||He[1]==="-h"?Co():await fs(be);break;case"mcp-server":await vs({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ms(be);break;case"version":nn();break;default:Co();break}}catch(e){xe(e)}}ea();