@entrydesk/cli 1.8.2 → 1.8.4

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 Te,b as ze,c as at,d as fe,e as Nt,f as ke,g as G,h as oe,i as qe,j as en,k as tn,m as on,n as H}from"./chunk-ZXRAVISY.js";import{render as Vi}from"ink";function $o(){console.log(`
2
+ import{a as tn,b as on,c as $e,d as qe,e as nn,f as sn,g as lt,h as fe,i as Et,j as ke,k as J,l as oe,m as Ye,r as G}from"./chunk-5JR5ME2B.js";import{render as Wi}from"ink";function So(){console.log(`
3
3
  Usage: entrydesk agents [list|create|update|delete] [options]
4
4
 
5
5
  Commands:
@@ -21,8 +21,8 @@ Create/Update Options:
21
21
 
22
22
  Flags:
23
23
  --json Output JSON
24
- `)}function Hs(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(n=>t.get(n)??n)}function nn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),$o(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:Hs(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function sn(e){try{if(e.help){$o();return}let t=await fe(),{accessToken:n,workspaceId:s}=t,o=e.action||"list",i=new H;if(o==="create"){let a=nn(e),c=await i.createAgent(n,s,a);if(e.json){console.log(JSON.stringify(c));return}console.log(`Created agent: ${c.name}`),console.log(` ID: ${c.id}`);return}if(o==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let c=nn(e);await i.updateAgent(n,s,a,c),console.log(`Updated agent: ${a}`);return}if(o==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(n,s,a),console.log(`Deleted agent: ${a}`);return}o!=="list"&&(console.error(`Unknown agents command: ${o}`),$o(),process.exit(1));let{agents:r}=await i.getAgents(n,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
25
- `);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){ke(t)}}function Vs(){console.log(`
24
+ `)}function Hs(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function rn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),So(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:Hs(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function an(e){try{if(e.help){So();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new G;if(n==="create"){let a=rn(e),c=await i.createAgent(o,s,a);if(e.json){console.log(JSON.stringify(c));return}console.log(`Created agent: ${c.name}`),console.log(` ID: ${c.id}`);return}if(n==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let c=rn(e);await i.updateAgent(o,s,a,c),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),So(),process.exit(1));let{agents:r}=await i.getAgents(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
25
+ `);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){ke(t)}}function Ks(){console.log(`
26
26
  Usage: entrydesk budget [get|set|clear] [options]
27
27
 
28
28
  Commands:
@@ -32,7 +32,7 @@ Commands:
32
32
 
33
33
  Flags:
34
34
  --json Output JSON
35
- `)}async function rn(e){try{if(e.help){Vs();return}let t=await fe(),{accessToken:n,workspaceId:s}=t,o=e.action||"get",i=new H;if(o==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let c=parseFloat(a);if(isNaN(c)||c<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(n,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(o==="clear"){let a=await i.updateBudget(n,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(o!=="get")throw new Error(`Unknown budget command: ${o}`);let r=await i.getBudget(n,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){ke(t)}}import{render as Hr}from"ink";import{v4 as fo}from"uuid";import{exec as Ks}from"child_process";import zs from"fs";import Ye from"fs/promises";import an from"os";import So from"path";import{promisify as qs}from"util";import{glob as Ys}from"glob";var Xs=qs(Ks),Zs=`## Filesystem Tool Instructions
35
+ `)}async function ln(e){try{if(e.help){Ks();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new G;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let c=parseFloat(a);if(isNaN(c)||c<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){ke(t)}}import{render as Hr}from"ink";import{v4 as po}from"uuid";import{exec as zs}from"child_process";import qs from"fs";import Xe from"fs/promises";import cn from"os";import To from"path";import{promisify as Ys}from"util";import{glob as Xs}from"glob";var Zs=Ys(zs),Qs=`## Filesystem Tool Instructions
36
36
 
37
37
  You have access to filesystem tools that allow you to interact with the user's local filesystem.
38
38
 
@@ -56,24 +56,24 @@ You have access to filesystem tools that allow you to interact with the user's l
56
56
  - Search results are limited to prevent overwhelming responses
57
57
  - Execute Command has a default timeout of 30 seconds (max 5 minutes)
58
58
  - The current working directory is: ${process.cwd()}
59
- - The user's home directory is: ${an.homedir()}
60
- `,Qs=[{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 ln(){return{name:"filesystem",systemPrompt:Zs,tools:Qs}}function Me(e){return e.startsWith("~/")?So.join(an.homedir(),e.slice(2)):e}function Xt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
59
+ - The user's home directory is: ${cn.homedir()}
60
+ `,er=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function un(){return{name:"filesystem",systemPrompt:Qs,tools:er}}function Je(e){return e.startsWith("~/")?To.join(cn.homedir(),e.slice(2)):e}function Zt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
61
61
 
62
- ... (truncated, ${e.length-t} more characters)`}async function cn(e,t){try{switch(e){case"filesystem__read_file":{let n=Me(t.path),s=await Ye.readFile(n,"utf-8");return{success:!0,result:Xt(s)}}case"filesystem__read_multiple_files":{let n=t.paths.slice(0,10),s={};for(let o of n){let i=Me(o);try{let r=await Ye.readFile(i,"utf-8");s[o]=Xt(r,5e4)}catch(r){s[o]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let n=Me(t.path),s=t.content;return await Ye.mkdir(So.dirname(n),{recursive:!0}),await Ye.writeFile(n,s,"utf-8"),{success:!0,result:{written:n}}}case"filesystem__create_directory":{let n=Me(t.path);return await Ye.mkdir(n,{recursive:!0}),{success:!0,result:{created:n}}}case"filesystem__list_directory":{let n=Me(t.path);return{success:!0,result:(await Ye.readdir(n,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let n=t.pattern,s=t.cwd?Me(t.cwd):process.cwd(),o=await Ys(n,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:o.slice(0,100),total:o.length,truncated:o.length>100}}}case"filesystem__get_file_info":{let n=Me(t.path),s=await Ye.stat(n);return{success:!0,result:{path:n,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 n=Me(t.source),s=Me(t.destination);return await Ye.mkdir(So.dirname(s),{recursive:!0}),await Ye.rename(n,s),{success:!0,result:{moved:{from:n,to:s}}}}case"filesystem__execute_command":{let n=t.command,s=t.cwd?Me(t.cwd):process.cwd(),o=Math.min(t.timeout||3e4,3e5);if(!zs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await Xs(n,{cwd:s,timeout:o,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Xt(i,5e4),stderr:Xt(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}function To(e){return e.startsWith("filesystem__")}function un(){return[ln()]}function Zt(){return un().flatMap(e=>e.tools)}function Qt(){return un().map(e=>e.systemPrompt).filter(Boolean).join(`
62
+ ... (truncated, ${e.length-t} more characters)`}async function dn(e,t){try{switch(e){case"filesystem__read_file":{let o=Je(t.path),s=await Xe.readFile(o,"utf-8");return{success:!0,result:Zt(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Je(n);try{let r=await Xe.readFile(i,"utf-8");s[n]=Zt(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Je(t.path),s=t.content;return await Xe.mkdir(To.dirname(o),{recursive:!0}),await Xe.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Je(t.path);return await Xe.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Je(t.path);return{success:!0,result:(await Xe.readdir(o,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Je(t.cwd):process.cwd(),n=await Xs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Je(t.path),s=await Xe.stat(o);return{success:!0,result:{path:o,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let o=Je(t.source),s=Je(t.destination);return await Xe.mkdir(To.dirname(s),{recursive:!0}),await Xe.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Je(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!qs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await Zs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Zt(i,5e4),stderr:Zt(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function Io(e){return e.startsWith("filesystem__")}function fn(){return[un()]}function Qt(){return fn().flatMap(e=>e.tools)}function eo(){return fn().map(e=>e.systemPrompt).filter(Boolean).join(`
63
63
 
64
- `)}function Xe(e){return To(e)}async function eo(e,t){return To(e)?cn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Ie,Text as V,useInput as Wo}from"ink";import Mo from"ink-spinner";import{useCallback as Jo,useEffect as uo,useRef as os,useState as Ur}from"react";import{Box as to,Text as Et}from"ink";import{jsx as oo,jsxs as _t}from"react/jsx-runtime";function dn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function fn({items:e,activeIndex:t,selectedIds:n,multiSelect:s=!1,visible:o,title:i,pageSize:r=10}){if(!o||e.length===0)return null;let a=process.stdout.columns??80,c=s?4:0,d=Math.max(20,a-2-2-c),$=Math.max(1,r),C=Math.floor(t/$)*$,x=Math.min(e.length,C+$),v=e.slice(C,x);return _t(to,{flexDirection:"column",marginBottom:1,children:[oo(Et,{bold:!0,color:"cyan",children:i}),oo(to,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:v.map((h,y)=>{let _=C+y===t,F=n?.has(h.id),K=dn(h.name,d),ie=h.description?dn(h.description,Math.max(0,d-c)):"",Y=s?" ".repeat(c):"";return _t(to,{paddingX:1,flexDirection:"column",children:[_t(to,{children:[s&&oo(Et,{color:F?"green":"gray",children:F?"[\u2713] ":"[ ] "}),oo(Et,{backgroundColor:_?"cyan":void 0,color:_?"black":F?"green":"white",bold:!0,children:K})]}),ie&&_t(Et,{dimColor:!0,children:[Y,"\xB7 ",ie]})]},h.id)})}),_t(Et,{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>$?` \xB7 Showing ${C+1}-${x} of ${e.length}`:""]})]})}import{Box as vo,Text as Dt}from"ink";import{jsx as Ot,jsxs as Io}from"react/jsx-runtime";function pn({suggestions:e,activeIndex:t,visible:n}){return!n||e.length===0?null:Io(vo,{flexDirection:"column",marginBottom:1,children:[Ot(vo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,o)=>{let i=o===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Io(vo,{paddingX:1,children:[Io(Dt,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),Ot(Dt,{dimColor:!0,children:r}),Ot(Dt,{children:" - "}),Ot(Dt,{color:i?"white":"gray",children:s.description})]},s.name)})}),Ot(Dt,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as er,Text as gn,useInput as tr,useStdout as or}from"ink";import{useCallback as mn,useEffect as hn,useMemo as Ao,useRef as yn,useState as wn}from"react";import{jsx as Eo}from"react/jsx-runtime";function no(e,t){return e<0?0:e>t?t:e}function Po(e){return Array.from(e)}function so(e){return/\s/.test(e)}function No(e,t){let n=t;for(;n>0&&so(e[n-1]??"");)n-=1;for(;n>0&&!so(e[n-1]??"");)n-=1;return n}function kn(e,t){let n=t;for(;n<e.length&&so(e[n]??"");)n+=1;for(;n<e.length&&!so(e[n]??"");)n+=1;return n}function nr(e){let t=[],n=[],s=[],o=0;n.push(0),e.forEach((r,a)=>{if(r===`
65
- `){t.push(s),s=[],o=a+1,n.push(o);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:n,lineLengths:i}}function bn(e,t,n){for(let o=0;o<t.length;o+=1){let i=t[o]??0,r=n[o]??0,a=i+r;if(e<=a)return{row:o,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:n[s]??0}}var sr=2;function xn({value:e,onChange:t,onSubmit:n,onPaste:s,focus:o=!0,leadingOffset:i=0,multiline:r=!1}){let[a,c]=wn(()=>Po(e).length),d=yn(null),[$,C]=wn(0),x=yn(null),{stdout:v}=or(),h=Ao(()=>Po(e),[e]),{lines:y,lineStarts:k,lineLengths:_}=Ao(()=>nr(h),[h]),{row:F,col:K}=Ao(()=>bn(a,k,_),[a,k,_]),ie=Math.max(1,(v?.columns??80)-i);hn(()=>{d.current!==e?(c(h.length),x.current=null):c(j=>no(j,h.length)),d.current=e},[e,h.length]),hn(()=>{C(j=>{let A=j;K<A?A=K:K>=A+ie&&(A=K-ie+1);let N=_[F]??0,R=K===N?N+1:N,W=Math.max(0,R-ie);return A>W&&(A=W),A<0&&(A=0),A})},[ie,K,F,_]);let Y=mn((j,A)=>{d.current=j,t(j),c(A),x.current=null},[t]),Ce=mn(async(j,A)=>{if(!o)return;let{row:N,col:R}=bn(a,k,_),W=y[N]??[],E=_[N]??0,me=y.length>1;if(r&&(A.meta&&A.return||A.ctrl&&j==="j"||A.shift&&A.return)){let D=[...h.slice(0,a),`
66
- `,...h.slice(a)].join("");Y(D,a+1);return}if(A.return){n(e);return}if(A.leftArrow){A.ctrl||A.meta?(R===0&&N>0?c(k[N]-1):c(k[N]+No(W,R)),x.current=null):(R===0&&N>0?c(k[N]-1):c(D=>no(D-1,h.length)),x.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(R>=E&&N<y.length-1?c(k[N+1]):c(k[N]+kn(W,R)),x.current=null):(R>=E&&N<y.length-1?c(k[N+1]):c(D=>no(D+1,h.length)),x.current=null);return}if(r&&me&&A.upArrow){let D=x.current??R,p=Math.max(0,N-1),re=Math.min(D,_[p]??0);c((k[p]??0)+re),x.current=D;return}if(r&&me&&A.downArrow){let D=x.current??R,p=Math.min(y.length-1,N+1),re=Math.min(D,_[p]??0);c((k[p]??0)+re),x.current=D;return}if(A.ctrl){if(j==="a"){c(k[N]??0),x.current=null;return}if(j==="e"){c((k[N]??0)+E),x.current=null;return}if(j==="u"){if(R>0){let D=k[N]??0,p=[...h.slice(0,D),...h.slice(a)].join("");Y(p,D)}return}if(j==="k"){if(R<E){let D=(k[N]??0)+E,p=[...h.slice(0,a),...h.slice(D)].join("");Y(p,a)}return}if(j==="w"){if(R===0&&N>0){let p=[...h.slice(0,a-1),...h.slice(a)].join("");Y(p,a-1);return}let D=No(W,R);if(D!==R){let p=(k[N]??0)+D,re=[...h.slice(0,p),...h.slice(a)].join("");Y(re,p)}return}if(j==="d"){if(a<h.length){let D=[...h.slice(0,a),...h.slice(a+1)].join("");Y(D,a)}return}return}if(A.meta){j==="b"?(R===0&&N>0?c(k[N]-1):c(k[N]+No(W,R)),x.current=null):j==="f"&&(R>=E&&N<y.length-1?c(k[N+1]):c(k[N]+kn(W,R)),x.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let D=[...h.slice(0,a-1),...h.slice(a)].join("");Y(D,a-1);return}if(!(A.tab||A.escape)&&j.length>0){let D=r?j.replace(/\r\n/g,`
64
+ `)}function Ze(e){return Io(e)}async function to(e,t){return Io(e)?dn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as ve,Text as V,useInput as Bo}from"ink";import Jo from"ink-spinner";import{useCallback as Go,useEffect as fo,useRef as ss,useState as jr}from"react";import{Box as oo,Text as _t}from"ink";import{jsx as no,jsxs as Dt}from"react/jsx-runtime";function pn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function gn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,c=s?4:0,d=Math.max(20,a-2-2-c),x=Math.max(1,r),C=Math.floor(t/x)*x,b=Math.min(e.length,C+x),T=e.slice(C,b);return Dt(oo,{flexDirection:"column",marginBottom:1,children:[no(_t,{bold:!0,color:"cyan",children:i}),no(oo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:T.map((h,y)=>{let j=C+y===t,z=o?.has(h.id),X=pn(h.name,d),ie=h.description?pn(h.description,Math.max(0,d-c)):"",q=s?" ".repeat(c):"";return Dt(oo,{paddingX:1,flexDirection:"column",children:[Dt(oo,{children:[s&&no(_t,{color:z?"green":"gray",children:z?"[\u2713] ":"[ ] "}),no(_t,{backgroundColor:j?"cyan":void 0,color:j?"black":z?"green":"white",bold:!0,children:X})]}),ie&&Dt(_t,{dimColor:!0,children:[q,"\xB7 ",ie]})]},h.id)})}),Dt(_t,{dimColor:!0,children:[s?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>x?` \xB7 Showing ${C+1}-${b} of ${e.length}`:""]})]})}import{Box as vo,Text as Ot}from"ink";import{jsx as Lt,jsxs as Ao}from"react/jsx-runtime";function mn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:Ao(vo,{flexDirection:"column",marginBottom:1,children:[Lt(vo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Ao(vo,{paddingX:1,children:[Ao(Ot,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),Lt(Ot,{dimColor:!0,children:r}),Lt(Ot,{children:" - "}),Lt(Ot,{color:i?"white":"gray",children:s.description})]},s.name)})}),Lt(Ot,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as tr,Text as hn,useInput as or,useStdout as nr}from"ink";import{useCallback as yn,useEffect as wn,useMemo as Po,useRef as kn,useState as bn}from"react";import{jsx as _o}from"react/jsx-runtime";function so(e,t){return e<0?0:e>t?t:e}function No(e){return Array.from(e)}function ro(e){return/\s/.test(e)}function Eo(e,t){let o=t;for(;o>0&&ro(e[o-1]??"");)o-=1;for(;o>0&&!ro(e[o-1]??"");)o-=1;return o}function xn(e,t){let o=t;for(;o<e.length&&ro(e[o]??"");)o+=1;for(;o<e.length&&!ro(e[o]??"");)o+=1;return o}function sr(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((r,a)=>{if(r===`
65
+ `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Cn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var rr=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,c]=bn(()=>No(e).length),d=kn(null),[x,C]=bn(0),b=kn(null),{stdout:T}=nr(),h=Po(()=>No(e),[e]),{lines:y,lineStarts:v,lineLengths:j}=Po(()=>sr(h),[h]),{row:z,col:X}=Po(()=>Cn(a,v,j),[a,v,j]),ie=Math.max(1,(T?.columns??80)-i);wn(()=>{d.current!==e?(c(h.length),b.current=null):c(U=>so(U,h.length)),d.current=e},[e,h.length]),wn(()=>{C(U=>{let A=U;X<A?A=X:X>=A+ie&&(A=X-ie+1);let N=j[z]??0,L=X===N?N+1:N,W=Math.max(0,L-ie);return A>W&&(A=W),A<0&&(A=0),A})},[ie,X,z,j]);let q=yn((U,A)=>{d.current=U,t(U),c(A),b.current=null},[t]),Ce=yn(async(U,A)=>{if(!n)return;let{row:N,col:L}=Cn(a,v,j),W=y[N]??[],E=j[N]??0,me=y.length>1;if(r&&(A.meta&&A.return||A.ctrl&&U==="j"||A.shift&&A.return)){let _=[...h.slice(0,a),`
66
+ `,...h.slice(a)].join("");q(_,a+1);return}if(A.return){o(e);return}if(A.leftArrow){A.ctrl||A.meta?(L===0&&N>0?c(v[N]-1):c(v[N]+Eo(W,L)),b.current=null):(L===0&&N>0?c(v[N]-1):c(_=>so(_-1,h.length)),b.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(L>=E&&N<y.length-1?c(v[N+1]):c(v[N]+xn(W,L)),b.current=null):(L>=E&&N<y.length-1?c(v[N+1]):c(_=>so(_+1,h.length)),b.current=null);return}if(r&&me&&A.upArrow){let _=b.current??L,p=Math.max(0,N-1),re=Math.min(_,j[p]??0);c((v[p]??0)+re),b.current=_;return}if(r&&me&&A.downArrow){let _=b.current??L,p=Math.min(y.length-1,N+1),re=Math.min(_,j[p]??0);c((v[p]??0)+re),b.current=_;return}if(A.ctrl){if(U==="a"){c(v[N]??0),b.current=null;return}if(U==="e"){c((v[N]??0)+E),b.current=null;return}if(U==="u"){if(L>0){let _=v[N]??0,p=[...h.slice(0,_),...h.slice(a)].join("");q(p,_)}return}if(U==="k"){if(L<E){let _=(v[N]??0)+E,p=[...h.slice(0,a),...h.slice(_)].join("");q(p,a)}return}if(U==="w"){if(L===0&&N>0){let p=[...h.slice(0,a-1),...h.slice(a)].join("");q(p,a-1);return}let _=Eo(W,L);if(_!==L){let p=(v[N]??0)+_,re=[...h.slice(0,p),...h.slice(a)].join("");q(re,p)}return}if(U==="d"){if(a<h.length){let _=[...h.slice(0,a),...h.slice(a+1)].join("");q(_,a)}return}return}if(A.meta){U==="b"?(L===0&&N>0?c(v[N]-1):c(v[N]+Eo(W,L)),b.current=null):U==="f"&&(L>=E&&N<y.length-1?c(v[N+1]):c(v[N]+xn(W,L)),b.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let _=[...h.slice(0,a-1),...h.slice(a)].join("");q(_,a-1);return}if(!(A.tab||A.escape)&&U.length>0){let _=r?U.replace(/\r\n/g,`
67
67
  `).replace(/\r/g,`
68
- `):j.replace(/\r?\n/g,"");if(!D||(D=D.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!D))return;if((D.length>=sr||D.includes(`
69
- `))&&s){let z=!1,P={text:D,preventDefault:()=>{z=!0}};if(await Promise.resolve(s(P)),z)return}let re=Po(D),we=[...h.slice(0,a),...re,...h.slice(a)].join("");Y(we,a+re.length)}},[h,a,o,_,k,y,r,s,n,Y,e]);return tr(Ce,{isActive:o}),Eo(er,{flexDirection:"column",children:y.map((j,A)=>{let N=A===F,W=(N&&K===j.length?[...j," "]:j).slice($,$+ie),E=W.join("");if(!N)return Eo(gn,{children:E||" "},A);let me=no(K-$,Math.max(0,W.length-1)),D=W.slice(0,me).join(""),p=W[me]??" ",re=W.slice(me+1).join(""),P=`${D}\x1B[7m${p}\x1B[27m${re}`;return Eo(gn,{children:P},A)})})}import{Box as Je,Text as lt}from"ink";import Lo from"react";import{Text as Re}from"ink";import rr from"react";import{Fragment as lr,jsx as Fe,jsxs as Sn}from"react/jsx-runtime";var _o=2,Do=1,Oo=2,ir=1,Cn=3,$n=4,ar=({text:e,defaultColor:t,linkColor:n,codeColor:s})=>{let o=t;if(!/[*_~`<[https?:]/.test(e))return Fe(Re,{color:o,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,c;for(;(c=a.exec(e))!==null;){c.index>r&&i.push(Fe(Re,{color:o,children:e.slice(r,c.index)},`t-${r}`));let d=c[0],$=null,C=`m-${c.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>_o*2)$=Fe(Re,{bold:!0,color:o,children:d.slice(_o,-_o)},C);else if(d.length>Do*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(c.index-1,c.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(c.index-2,c.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))$=Fe(Re,{italic:!0,color:o,children:d.slice(Do,-Do)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Oo*2)$=Fe(Re,{strikethrough:!0,color:o,children:d.slice(Oo,-Oo)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>ir){let x=d.match(/^(`+)(.+?)\1$/s);x&&x[2]&&($=Fe(Re,{color:s,children:x[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let x=d.match(/\[(.*?)\]\((.*?)\)/);if(x){let v=x[1],h=x[2];$=Sn(Re,{color:o,children:[v,Sn(Re,{color:n,children:[" (",h,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Cn+$n-1?$=Fe(Re,{underline:!0,color:o,children:d.slice(Cn,-$n)},C):d.match(/^https?:\/\//)&&($=Fe(Re,{color:n,children:d},C))}catch{$=null}i.push($??Fe(Re,{color:o,children:d},C)),r=a.lastIndex}return r<e.length&&i.push(Fe(Re,{color:o,children:e.slice(r)},`t-${r}`)),Fe(lr,{children:i.filter(d=>d!==null)})},Lt=rr.memo(ar);import{Fragment as mr,jsx as ye,jsxs as An}from"react/jsx-runtime";var cr=1,In=1,ur=1,dr=1,fr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(Je,{paddingLeft:In,flexDirection:"column",children:ye(lt,{wrap:"wrap",children:e})});let n=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,o=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,c=/^ *> ?(.*)/,d=[],$=!1,C=!0,x=[],v="";function h(y){y&&(d.push(y),C=!1)}return n.forEach((y,k)=>{let _=`line-${k}`;if($){let A=y.match(o);A&&A[1].startsWith(v[0])&&A[1].length>=v.length?(h(ye(Tn,{content:x},_)),$=!1,x=[],v=""):x.push(y);return}let F=y.match(o),K=y.match(s),ie=y.match(i),Y=y.match(r),Ce=y.match(a),j=y.match(c);if(F)$=!0,v=F[1];else if(Ce)h(ye(Je,{children:ye(lt,{dimColor:!0,children:"---"})},_));else if(K){let A=K[1].length,N=K[2],R=A<=2?"cyan":"blue";h(ye(Je,{children:ye(lt,{color:R,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Lt,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},_))}else if(j){let A=j[1];h(ye(Je,{paddingLeft:1,children:An(lt,{dimColor:!0,children:["> ",ye(Lt,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},_))}else if(ie){let A=ie[1],N=ie[2],R=ie[3];h(ye(vn,{itemText:R,type:"ul",marker:N,leadingWhitespace:A},_))}else if(Y){let A=Y[1],N=Y[2],R=Y[3];h(ye(vn,{itemText:R,type:"ol",marker:N,leadingWhitespace:A},_))}else y.trim().length===0?C||(d.push(ye(Je,{height:cr},`spacer-${k}`)),C=!0):h(ye(Je,{children:ye(lt,{wrap:"wrap",children:ye(Lt,{text:y,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},_))}),$&&h(ye(Tn,{content:x},"line-eof")),ye(mr,{children:d})},pr=({content:e})=>{let t=e.join(`
70
- `);return ye(Je,{paddingLeft:In,flexDirection:"column",children:ye(lt,{color:"yellow",children:t})})},Tn=Lo.memo(pr),gr=({itemText:e,type:t,marker:n,leadingWhitespace:s=""})=>{let o=t==="ol"?`${n}. `:`${n} `,i=o.length,r=s.length;return An(Je,{paddingLeft:r+ur,flexDirection:"row",children:[ye(Je,{width:i,children:ye(lt,{children:o})}),ye(Je,{flexGrow:dr,children:ye(lt,{wrap:"wrap",children:ye(Lt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},vn=Lo.memo(gr),Ro=Lo.memo(fr);import{execFile as hr}from"child_process";import yr from"fs";import bt from"fs/promises";import Pn from"os";import io from"path";import{promisify as wr}from"util";var ro=wr(hr);async function kr(){let e=io.join(Pn.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
68
+ `):U.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=rr||_.includes(`
69
+ `))&&s){let H=!1,P={text:_,preventDefault:()=>{H=!0}};if(await Promise.resolve(s(P)),H)return}let re=No(_),we=[...h.slice(0,a),...re,...h.slice(a)].join("");q(we,a+re.length)}},[h,a,n,j,v,y,r,s,o,q,e]);return or(Ce,{isActive:n}),_o(tr,{flexDirection:"column",children:y.map((U,A)=>{let N=A===z,W=(N&&X===U.length?[...U," "]:U).slice(x,x+ie),E=W.join("");if(!N)return _o(hn,{children:E||" "},A);let me=so(X-x,Math.max(0,W.length-1)),_=W.slice(0,me).join(""),p=W[me]??" ",re=W.slice(me+1).join(""),P=`${_}\x1B[7m${p}\x1B[27m${re}`;return _o(hn,{children:P},A)})})}import{Box as Ge,Text as ct}from"ink";import Ro from"react";import{Text as Re}from"ink";import ir from"react";import{Fragment as cr,jsx as Fe,jsxs as In}from"react/jsx-runtime";var Do=2,Oo=1,Lo=2,ar=1,Sn=3,Tn=4,lr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Fe(Re,{color:n,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,c;for(;(c=a.exec(e))!==null;){c.index>r&&i.push(Fe(Re,{color:n,children:e.slice(r,c.index)},`t-${r}`));let d=c[0],x=null,C=`m-${c.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Do*2)x=Fe(Re,{bold:!0,color:n,children:d.slice(Do,-Do)},C);else if(d.length>Oo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(c.index-1,c.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(c.index-2,c.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))x=Fe(Re,{italic:!0,color:n,children:d.slice(Oo,-Oo)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Lo*2)x=Fe(Re,{strikethrough:!0,color:n,children:d.slice(Lo,-Lo)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>ar){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(x=Fe(Re,{color:s,children:b[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let T=b[1],h=b[2];x=In(Re,{color:n,children:[T,In(Re,{color:o,children:[" (",h,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Sn+Tn-1?x=Fe(Re,{underline:!0,color:n,children:d.slice(Sn,-Tn)},C):d.match(/^https?:\/\//)&&(x=Fe(Re,{color:o,children:d},C))}catch{x=null}i.push(x??Fe(Re,{color:n,children:d},C)),r=a.lastIndex}return r<e.length&&i.push(Fe(Re,{color:n,children:e.slice(r)},`t-${r}`)),Fe(cr,{children:i.filter(d=>d!==null)})},Rt=ir.memo(lr);import{Fragment as hr,jsx as ye,jsxs as Nn}from"react/jsx-runtime";var ur=1,Pn=1,dr=1,fr=1,pr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(Ge,{paddingLeft:Pn,flexDirection:"column",children:ye(ct,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,c=/^ *> ?(.*)/,d=[],x=!1,C=!0,b=[],T="";function h(y){y&&(d.push(y),C=!1)}return o.forEach((y,v)=>{let j=`line-${v}`;if(x){let A=y.match(n);A&&A[1].startsWith(T[0])&&A[1].length>=T.length?(h(ye(vn,{content:b},j)),x=!1,b=[],T=""):b.push(y);return}let z=y.match(n),X=y.match(s),ie=y.match(i),q=y.match(r),Ce=y.match(a),U=y.match(c);if(z)x=!0,T=z[1];else if(Ce)h(ye(Ge,{children:ye(ct,{dimColor:!0,children:"---"})},j));else if(X){let A=X[1].length,N=X[2],L=A<=2?"cyan":"blue";h(ye(Ge,{children:ye(ct,{color:L,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Rt,{text:N,defaultColor:L,linkColor:"cyan",codeColor:"yellow"})})},j))}else if(U){let A=U[1];h(ye(Ge,{paddingLeft:1,children:Nn(ct,{dimColor:!0,children:["> ",ye(Rt,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},j))}else if(ie){let A=ie[1],N=ie[2],L=ie[3];h(ye(An,{itemText:L,type:"ul",marker:N,leadingWhitespace:A},j))}else if(q){let A=q[1],N=q[2],L=q[3];h(ye(An,{itemText:L,type:"ol",marker:N,leadingWhitespace:A},j))}else y.trim().length===0?C||(d.push(ye(Ge,{height:ur},`spacer-${v}`)),C=!0):h(ye(Ge,{children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:y,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},j))}),x&&h(ye(vn,{content:b},"line-eof")),ye(hr,{children:d})},gr=({content:e})=>{let t=e.join(`
70
+ `);return ye(Ge,{paddingLeft:Pn,flexDirection:"column",children:ye(ct,{color:"yellow",children:t})})},vn=Ro.memo(gr),mr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return Nn(Ge,{paddingLeft:r+dr,flexDirection:"row",children:[ye(Ge,{width:i,children:ye(ct,{children:n})}),ye(Ge,{flexGrow:fr,children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},An=Ro.memo(mr),Uo=Ro.memo(pr);import{execFile as yr}from"child_process";import wr from"fs";import xt from"fs/promises";import En from"os";import ao from"path";import{promisify as kr}from"util";var io=kr(yr);async function br(){let e=ao.join(En.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
71
71
  set imageData to the clipboard as "PNGf"
72
72
  set fileRef to open for access POSIX file "${e}" with write permission
73
73
  set eof fileRef to 0
74
74
  write imageData to fileRef
75
75
  close access fileRef
76
- `;return await ro("osascript",["-e",t]),(await bt.stat(e)).size===0?void 0:{buffer:await bt.readFile(e),mime:"image/png"}}catch{return}finally{try{yr.existsSync(e)&&await bt.unlink(e)}catch{}}}async function br(){try{let e=`
76
+ `;return await io("osascript",["-e",t]),(await xt.stat(e)).size===0?void 0:{buffer:await xt.readFile(e),mime:"image/png"}}catch{return}finally{try{wr.existsSync(e)&&await xt.unlink(e)}catch{}}}async function xr(){try{let e=`
77
77
  Add-Type -AssemblyName System.Windows.Forms
78
78
  $img = [System.Windows.Forms.Clipboard]::GetImage()
79
79
  if ($img) {
@@ -81,44 +81,44 @@ You have access to filesystem tools that allow you to interact with the user's l
81
81
  $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
82
82
  [System.Convert]::ToBase64String($ms.ToArray())
83
83
  }
84
- `,{stdout:t}=await ro("powershell.exe",["-command",e]),n=t.trim();if(!n)return;let s=Buffer.from(n,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function xr(){try{let{stdout:e}=await ro("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 ro("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 Nn(){let e=Pn.platform();if(e==="darwin")return kr();if(e==="win32")return br();if(e==="linux")return xr()}var Cr=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 En(e){let t=io.extname(e).toLowerCase();return Cr.has(t)}function $r(e){let t=io.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 ao(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 _n(e){let t=ao(e);if(/^https?:\/\//.test(t))return!1;try{return await bt.access(t),!0}catch{return!1}}async function Dn(e){let t=ao(e);try{if(!(await bt.stat(t)).isFile())return;let s=await bt.readFile(t),o=$r(t),i=io.basename(t);return{buffer:s,mimeType:o,filename:i}}catch{return}}var Ue="\x1B[2m",se="\x1B[0m",ve="\x1B[36m",xt="\x1B[32m",On="\x1B[31m",dt="\x1B[38;2;59;91;204m",Uo="\x1B[38;2;126;200;248m",jo="\x1B[38;2;244;196;78m";import{useState as Ze}from"react";import{v4 as Ln}from"uuid";function Rn(e,t){let[n,s]=Ze({status:"loading"}),[o,i]=Ze([]),[r,a]=Ze(""),[c,d]=Ze(()=>e||Ln()),[$,C]=Ze(t),[x,v]=Ze(!!e),[h,y]=Ze(null),[k,_]=Ze(""),[F,K]=Ze(!1),ie=Ce=>{i(j=>[...j,{role:"system",content:Ce}])};return{state:n,setState:s,messages:o,setMessages:i,input:r,setInput:a,chatId:c,setChatId:d,currentChatTitle:$,setCurrentChatTitle:C,hasPersistedChat:x,setHasPersistedChat:v,credentials:h,setCredentials:y,currentResponse:k,setCurrentResponse:_,fullOutput:F,setFullOutput:K,addSystemMessage:ie,startNewChat:Ce=>{let j=Ln();d(j),C(void 0),v(!1),i([]),Ce&&ie(Ce)}}}import{useEffect as Sr,useState as Un}from"react";function jn(e){let[t,n]=Un(null),[s,o]=Un(!0);return Sr(()=>{let i=!1;async function r(){try{let a=await fe();if(i)return;n({accessToken:a.accessToken,workspaceId:a.workspaceId}),o(!1)}catch(a){if(i)return;if(a instanceof ze){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),o(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),o(!1);return}}let c=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:c}),o(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Tr,useState as Rt}from"react";function Fn(e){let[t,n]=Rt([]),[s,o]=Rt([]),[i,r]=Rt([]),[a,c]=Rt([]),[d,$]=Rt(!1);return Tr(()=>{if(!e)return;let C=!1;$(!0);async function x(){if(e)try{let v=new H,[h,y,k,_]=await Promise.all([v.getConnectors(e.accessToken,e.workspaceId),v.getModels(e.accessToken,e.workspaceId),v.getAgents(e.accessToken,e.workspaceId),v.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;n(h.connectors),o(y.models),r(k.agents),c(_.providers??[])}catch{}finally{C||$(!1)}}return x(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import Ct from"fs";import Wn from"path";import{useCallback as vr}from"react";import{v4 as Ir}from"uuid";function Bn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let o=String(e);return t||o.length<=200?o:o.slice(0,200)+"..."}let n=e;if("structuredContent"in n&&n.structuredContent){let o=n.structuredContent;if(o.stdout&&typeof o.stdout=="string"){let i=o.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in n&&Array.isArray(n.content)){let o=n.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
85
- `);return o?t||o.length<=200?o:o.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 ft(e,t=!1){let n=[];for(let s of e)if(s.type==="text"&&s.text)n.push(s.text);else if(s.type==="reasoning"&&s.text)t?n.push(`${Ue}[Thinking]
86
- ${s.text}${se}`):n.push(`${Ue}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let o=[];if(o.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)+"...";o.push(`${Ue}\u2502 Args: ${r}${se}`)}s.result!==void 0?(o.push(`${xt}\u2502 Result: ${Bn(s.result,t)}${se}`),o.push(`${ve}\u2514\u2500 completed${se}`)):o.push(`${ve}\u2514\u2500${se}`),n.push(o.join(`
87
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let o=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${ve}\u250C\u2500 Tool: ${o}${se}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Ue}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${xt}\u2502 Output: ${Bn(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}`),n.push(i.join(`
88
- `))}return n.join(`
84
+ `,{stdout:t}=await io("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function Cr(){try{let{stdout:e}=await io("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await io("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function _n(){let e=En.platform();if(e==="darwin")return br();if(e==="win32")return xr();if(e==="linux")return Cr()}var $r=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Dn(e){let t=ao.extname(e).toLowerCase();return $r.has(t)}function Sr(e){let t=ao.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function lo(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function On(e){let t=lo(e);if(/^https?:\/\//.test(t))return!1;try{return await xt.access(t),!0}catch{return!1}}async function Ln(e){let t=lo(e);try{if(!(await xt.stat(t)).isFile())return;let s=await xt.readFile(t),n=Sr(t),i=ao.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Ue="\x1B[2m",se="\x1B[0m",Ie="\x1B[36m",Ct="\x1B[32m",Rn="\x1B[31m",ft="\x1B[38;2;59;91;204m",jo="\x1B[38;2;126;200;248m",Fo="\x1B[38;2;244;196;78m";import{useState as Qe}from"react";import{v4 as Un}from"uuid";function jn(e,t){let[o,s]=Qe({status:"loading"}),[n,i]=Qe([]),[r,a]=Qe(""),[c,d]=Qe(()=>e||Un()),[x,C]=Qe(t),[b,T]=Qe(!!e),[h,y]=Qe(null),[v,j]=Qe(""),[z,X]=Qe(!1),ie=Ce=>{i(U=>[...U,{role:"system",content:Ce}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:c,setChatId:d,currentChatTitle:x,setCurrentChatTitle:C,hasPersistedChat:b,setHasPersistedChat:T,credentials:h,setCredentials:y,currentResponse:v,setCurrentResponse:j,fullOutput:z,setFullOutput:X,addSystemMessage:ie,startNewChat:Ce=>{let U=Un();d(U),C(void 0),T(!1),i([]),Ce&&ie(Ce)}}}import{useEffect as Tr,useState as Fn}from"react";function Wn(e){let[t,o]=Fn(null),[s,n]=Fn(!0);return Tr(()=>{let i=!1;async function r(){try{let a=await fe();if(i)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof qe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let c=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:c}),n(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Ir,useState as Ut}from"react";function Mn(e){let[t,o]=Ut([]),[s,n]=Ut([]),[i,r]=Ut([]),[a,c]=Ut([]),[d,x]=Ut(!1);return Ir(()=>{if(!e)return;let C=!1;x(!0);async function b(){if(e)try{let T=new G,[h,y,v,j]=await Promise.all([T.getConnectors(e.accessToken,e.workspaceId),T.getModels(e.accessToken,e.workspaceId),T.getAgents(e.accessToken,e.workspaceId),T.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;o(h.connectors),n(y.models),r(v.agents),c(j.providers??[])}catch{}finally{C||x(!1)}}return b(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import $t from"fs";import Jn from"path";import{useCallback as vr}from"react";import{v4 as Ar}from"uuid";function Bn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
85
+ `);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function pt(e,t=!1){let o=[];for(let s of e)if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="reasoning"&&s.text)t?o.push(`${Ue}[Thinking]
86
+ ${s.text}${se}`):o.push(`${Ue}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${Ie}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let i=JSON.stringify(s.args,null,t?2:void 0),r=t||i.length<=100?i:i.slice(0,100)+"...";n.push(`${Ue}\u2502 Args: ${r}${se}`)}s.result!==void 0?(n.push(`${Ct}\u2502 Result: ${Bn(s.result,t)}${se}`),n.push(`${Ie}\u2514\u2500 completed${se}`)):n.push(`${Ie}\u2514\u2500${se}`),o.push(n.join(`
87
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${Ie}\u250C\u2500 Tool: ${n}${se}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Ue}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Ct}\u2502 Output: ${Bn(s.output,t)}${se}`),i.push(`${Ie}\u2514\u2500 completed${se}`)):s.state==="error"?i.push(`${Ie}\u2514\u2500 failed${se}`):i.push(`${Ie}\u2514\u2500${se}`),o.push(i.join(`
88
+ `))}return o.join(`
89
89
 
90
- `).trim()}var lo=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[,n]of this.pendingToolCalls){let s=n.toolName.replace(/__/g," "),o=`
90
+ `).trim()}var co=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let s=o.toolName.replace(/__/g," "),n=`
91
91
 
92
- ${ve}\u250C\u2500 Tool: ${s}${se}`;if(n.args){let i=n.args.length>100?n.args.slice(0,100)+"...":n.args;o+=`
93
- ${Ue}\u2502 Input: ${i}${se}`}if(n.output){let i=n.output.length>150?n.output.slice(0,150)+"...":n.output;o+=`
94
- ${xt}\u2502 Output: ${i}${se}`}else if(n.status==="executing"){let i=n.startedAt??Date.now(),r=Math.floor((Date.now()-i)/1e3);o+=`
95
- ${ve}\u2502${se} (executing... ${r}s)`}else n.status==="preparing"&&(o+=`
96
- ${ve}\u2502${se} (preparing...)`);t.push(o)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[n,s]of this.pendingToolCalls){let o=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
92
+ ${Ie}\u250C\u2500 Tool: ${s}${se}`;if(o.args){let i=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
93
+ ${Ue}\u2502 Input: ${i}${se}`}if(o.output){let i=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
94
+ ${Ct}\u2502 Output: ${i}${se}`}else if(o.status==="executing"){let i=o.startedAt??Date.now(),r=Math.floor((Date.now()-i)/1e3);n+=`
95
+ ${Ie}\u2502${se} (executing... ${r}s)`}else o.status==="preparing"&&(n+=`
96
+ ${Ie}\u2502${se} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,s]of this.pendingToolCalls){let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
97
97
 
98
- ${ve}\u250C\u2500 Tool: ${o}${se}`,i&&(t+=`
98
+ ${Ie}\u250C\u2500 Tool: ${n}${se}`,i&&(t+=`
99
99
  ${Ue}\u2502 Input: ${i}${se}`),t+=`
100
- ${ve}\u2514\u2500 completed${se}
101
- `,this.pendingToolCalls.delete(n)}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 n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.args=(n.args||"")+t.inputTextDelta,n.status="executing",n.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.output="",n.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let n=this.pendingToolCalls.get(t.toolCallId);if(n)return n.output=(n.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,n){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let o=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 n+=`
102
-
103
- ${ve}\u250C\u2500 Tool: ${o}${se}`,i&&(n+=`
104
- ${Ue}\u2502 Input: ${i}${se}`),n+=`
105
- ${xt}\u2502 Output: ${r}${se}`,n+=`
106
- ${ve}\u2514\u2500 completed${se}
107
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:n,toolDisplay:this.buildToolDisplay()}}handleToolError(t,n){if(!t.toolCallId)return null;let o=(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 n+=`
108
-
109
- ${ve}\u250C\u2500 Tool: ${o}${se}`,n+=`
110
- ${On}\u2502 Error: ${r}${se}`,n+=`
111
- ${ve}\u2514\u2500 failed${se}
112
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:n,toolDisplay:this.buildToolDisplay()}}};var Ut=Wn.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+=`
100
+ ${Ie}\u2514\u2500 completed${se}
101
+ `,this.pendingToolCalls.delete(o)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.args=(o.args||"")+t.inputTextDelta,o.status="executing",o.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output="",o.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output=(o.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,o){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let n=s.toolName.replace(/__/g," "),i=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"",r=(s.output||"").length>200?(s.output||"").slice(0,200)+"...":s.output||"";return o+=`
102
+
103
+ ${Ie}\u250C\u2500 Tool: ${n}${se}`,i&&(o+=`
104
+ ${Ue}\u2502 Input: ${i}${se}`),o+=`
105
+ ${Ct}\u2502 Output: ${r}${se}`,o+=`
106
+ ${Ie}\u2514\u2500 completed${se}
107
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),i=t.errorText||"Unknown error",r=i.length>200?i.slice(0,200)+"...":i;return o+=`
108
+
109
+ ${Ie}\u250C\u2500 Tool: ${n}${se}`,o+=`
110
+ ${Rn}\u2502 Error: ${r}${se}`,o+=`
111
+ ${Ie}\u2514\u2500 failed${se}
112
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var jt=Jn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
113
113
  DATA: ${JSON.stringify(t,null,2)}`),s+=`
114
- `;try{Ct.appendFileSync(Ut,s)}catch{}}function Ar(){try{if(Ct.existsSync(Ut)&&Ct.unlinkSync(Ut),process.env.DEBUG){let e=Wn.dirname(Ut);Ct.existsSync(e)||Ct.mkdirSync(e,{recursive:!0}),Ct.writeFileSync(Ut,`=== Debug session started at ${new Date().toISOString()} ===
115
- `)}}catch{}}function co(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Mn({chatId:e,credentials:t,currentAgentId:n,currentModel:s,activeConnectorIds:o,sandbox:i,webSearch:r,imageGeneration:a,chart:c,localTools:d,fullOutput:$,setMessages:C,setState:x,setCurrentResponse:v,setCredentials:h,setHasPersistedChat:y,getFileIds:k,clearFiles:_}){let F=d?Zt():void 0,K=d?Qt():void 0;return{sendMessage:vr(async(Y,Ce,j)=>{Ar(),ae("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:F?.length});let A=Ce||t?.accessToken,N=j||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,h(E)}catch(E){if(E instanceof ze){if(E.code==="not-logged-in"){x({status:"not-logged-in"});return}if(E.code==="no-workspace"){x({status:"no-workspace"});return}}let me=E instanceof Error?E.message:"Authentication failed";x({status:"error",message:me});return}else try{let E=await at();E!==A&&(A=E,h({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof ze&&E.code==="not-logged-in"){x({status:"not-logged-in"});return}let me=E instanceof Error?E.message:"Authentication failed";x({status:"error",message:me});return}C(E=>[...E,{role:"user",content:Y}]),x({status:"sending"}),v("");let R=null,W=null;try{let E=new H,me=k?.()??[],D={id:e,message:{id:Ir(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};me.length>0&&(D.fileIds=me),n?D.agentId=n:(s&&(D.model=s),D.connectorIds=o??[],D.enableSandbox=i,D.enableWebSearch=r,D.enableImageGeneration=a,D.enableChart=c),F&&(D.clientTools=F),K&&(D.clientToolSystemPrompt=K);let p=await E.chat(A,N,D);if(!p.ok){let B=await p.text();throw new Error(`API error ${p.status}: ${B}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let re=new TextDecoder,we="",z="",P="",ee="",Q="",pe="",le="",M=new lo,Z=[],q=[],de=[],$e=()=>{let B=M.hasExecuting();B&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}v(z+M.buildToolDisplay())},1e3):!B&&W&&(clearInterval(W),W=null)};for(;;){let{done:B,value:ne}=await R.read();if(B)break;we+=re.decode(ne,{stream:!0});let L=we.split(`
116
- `);we=L.pop()||"";for(let f of L)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",P="";break;case"reasoning-delta":w.delta&&(P+=w.delta,v(`${Ue}[Thinking...]${se}
117
- ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let S={type:"reasoning",id:ee,text:P,state:"done"};Q&&(S.providerMetadata={anthropic:{signature:Q}}),q.push(S),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",v("");break;case"text-delta":w.delta&&(M.hasPending()&&(z=M.flushPending(z)),z+=w.delta,pe+=w.delta,v(z));break;case"tool-input-start":{let S=M.handleToolInputStart(w);S&&v(z+S),$e();break}case"tool-input-delta":{let S=M.handleToolInputDelta(w);S&&v(z+S),$e();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?Xe(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let S=co(w.args??w.input);q.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:S}),ae("Added tool to messageParts",{messagePartsCount:q.length})}if(d&&w.toolCallId&&w.toolName&&Xe(w.toolName)){let S=co(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:S}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),v(z+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?Xe(w.toolName):!1});break}case"tool-output-start":{let S=M.handleToolOutputStart(w);S&&v(z+S),$e();break}case"tool-output-delta":{let S=M.handleToolOutputDelta(w);S&&v(z+S),$e();break}case"tool-output-end":{let S=M.handleToolOutputEnd(w,z);S&&(z=S.fullResponse,v(z+S.toolDisplay)),$e();break}case"tool-input-error":case"tool-output-error":{let S=M.handleToolError(w,z);S&&(z=S.fullResponse,v(z+S.toolDisplay)),$e();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 B=q.findIndex(L=>L.type!=="reasoning"),ne=B===-1?q.length:B;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(B=>({type:B.type,toolCallId:B.toolCallId,toolName:B.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let B=[];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)}),v(z+M.buildToolDisplay()),$e();let w=await eo(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 S=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(B.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:S}],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},z);te&&(z=te.fullResponse)}else{let te=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},z);te&&(z=te.fullResponse)}v(z+M.buildToolDisplay()),$e()}Z.length=0;for(let f of B){let w=q.find(S=>(S.type==="tool-input-available"||S.type==="tool-call")&&S.toolCallId===f.toolCallId);if(w){let S=[];for(let U of f.content)U.type==="text"?S.push(U.text):U.type==="image"?S.push("[Image]"):U.type==="audio"?S.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&S.push("[Resource]");let te=S.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:B.length,toolResults:B.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let ne={id:e,clientToolResults:B};n?ne.agentId=n:(s&&(ne.model=s),ne.connectorIds=o??[],ne.enableSandbox=i,ne.enableWebSearch=r,ne.enableImageGeneration=a,ne.enableChart=c),F&&(ne.clientTools=F),K&&(ne.clientToolSystemPrompt=K),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:B.length});let L=await E.chat(A,N,ne);if(ae("=== Continuation response received ===",{ok:L.ok,status:L.status}),!L.ok){let f=await L.text();throw new Error(`Continuation failed: ${L.status}: ${f}`)}if(!L.body)break;for(ae("=== Processing continuation stream ==="),R=L.body.getReader(),q.length=0,pe="",P="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}we+=re.decode(w,{stream:!0});let S=we.split(`
120
- `);we=S.pop()||"";for(let te of S)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let U=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":ee=U.id||"0",P="";break;case"reasoning-delta":U.delta&&(P+=U.delta,v(`${Ue}[Thinking...]${se}
121
- ${P}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let xe={type:"reasoning",id:ee,text:P,state:"done"};Q&&(xe.providerMetadata={anthropic:{signature:Q}}),q.push(xe),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",v(z);break;case"text-delta":U.delta&&(z+=U.delta,pe+=U.delta,v(z));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let xe=co(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:xe})}if(d&&U.toolCallId&&U.toolName&&Xe(U.toolName)){let xe=co(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:xe}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(S=>S.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:z.length})}if(d&&F&&F.length>0){let B=[];for(let L of de)B.push({type:String(L.type),title:String(L.toolName).replace(/__/g," "),input:L.input,output:L.output,state:L.isError?"error":"output-available"});for(let L of q)L.type==="text"&&L.text&&B.push({type:"text",text:L.text});let ne=ft(B,$);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(L=>L.type==="text").length,contentLength:ne.length}),C(L=>[...L,{role:"assistant",content:ne,parts:B}])}else{ae("=== Fetching message from API ===",{fullResponseLength:z.length,fullResponsePreview:z.slice(0,200)});try{let{messages:B}=await E.getMessages(A,N,e,10);ae("=== API messages received ===",{count:B.length,roles:B.map(L=>L.role)});let ne=B.find(L=>L.role==="assistant");if(ne){let L=ne.parts,f=ft(L,$);ae("=== Setting message from API ===",{partsCount:L.length,partTypes:L.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:L}])}else ae("=== No assistant message found, using fallback ==="),C(L=>[...L,{role:"assistant",content:z}])}catch(B){ae("=== API fetch failed, using fallback ===",{error:B instanceof Error?B.message:String(B)}),C(ne=>[...ne,{role:"assistant",content:z}])}}ae("=== Message handling complete ==="),v(""),x({status:"ready"}),y(!0),me.length>0&&_?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let me=E instanceof Error?E.message:"Failed to send message";x({status:"error",message:me})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,n,s,o,i,r,a,c,d,F,K,$,C,x,v,h,y,k,_])}}import{useState as jt}from"react";var Jn={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"}},Gn=new Map(Object.values(Jn).map(e=>[e.apiKey,e.name]));function Hn(){return Object.values(Jn)}function Vn(e,t,n,s,o){let[i,r]=jt(e),[a,c]=jt(t),[d,$]=jt(n),[C,x]=jt(s),[v,h]=jt(o);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:c,imageGeneration:d,setImageGeneration:$,chart:C,setChart:x,fileSystem:v,setFileSystem:h,capabilityLabelMap:Gn}}import{useEffect as Pr,useState as Nr}from"react";function Kn(e,t){let[n,s]=Nr(null);return Pr(()=>{let o=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new H().getAgent(t.accessToken,t.workspaceId,e);o||s(a)}catch{o||s(null)}}return i(),()=>{o=!0}},[e,t]),{currentAgentDetails:n}}import{useState as Fo}from"react";function zn(e,t,n){let[s,o]=Fo(e),[i,r]=Fo(t),[a,c]=Fo(n);return{currentModel:s,setCurrentModel:o,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:c}}import{useApp as _r,useInput as Dr}from"ink";import{useCallback as Qe,useRef as Or,useState as Ee}from"react";import{spawn as Er}from"child_process";function qn(e){return new Promise((t,n)=>{let s,o;process.platform==="darwin"?(s="open",o=[e]):process.platform==="win32"?(s="cmd",o=["/c","start","",e]):(s="xdg-open",o=[e]);let i=Er(s,o,{stdio:"ignore",detached:!0});i.once("error",r=>{n(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Yn=[{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 Xn(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Yn.filter(n=>n.name.startsWith(t)||n.aliases.some(s=>s.startsWith(t))):Yn}function Zn(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),s=n[0]?.toLowerCase(),o=n.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:o||void 0};case"agent":case"a":return{type:"agent",value:o||void 0};case"skills":case"sk":return{type:"skills",value:o||void 0};case"schedules":case"sch":return{type:"schedules",value:o||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:o||void 0};case"budget":case"bg":return{type:"budget",value:o||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:o||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 Qn=`Available commands:
114
+ `;try{$t.appendFileSync(jt,s)}catch{}}function Pr(){try{if($t.existsSync(jt)&&$t.unlinkSync(jt),process.env.DEBUG){let e=Jn.dirname(jt);$t.existsSync(e)||$t.mkdirSync(e,{recursive:!0}),$t.writeFileSync(jt,`=== Debug session started at ${new Date().toISOString()} ===
115
+ `)}}catch{}}function uo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Gn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:c,localTools:d,fullOutput:x,setMessages:C,setState:b,setCurrentResponse:T,setCredentials:h,setHasPersistedChat:y,getFileIds:v,clearFiles:j}){let z=d?Qt():void 0,X=d?eo():void 0;return{sendMessage:vr(async(q,Ce,U)=>{Pr(),ae("=== sendMessage called ===",{text:q,localTools:d,clientToolsCount:z?.length});let A=Ce||t?.accessToken,N=U||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,h(E)}catch(E){if(E instanceof qe){if(E.code==="not-logged-in"){b({status:"not-logged-in"});return}if(E.code==="no-workspace"){b({status:"no-workspace"});return}}let me=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:me});return}else try{let E=await lt();E!==A&&(A=E,h({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof qe&&E.code==="not-logged-in"){b({status:"not-logged-in"});return}let me=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:me});return}C(E=>[...E,{role:"user",content:q}]),b({status:"sending"}),T("");let L=null,W=null;try{let E=new G,me=v?.()??[],_={id:e,message:{id:Ar(),createdAt:new Date,role:"user",parts:[{type:"text",text:q}]}};me.length>0&&(_.fileIds=me),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=i,_.enableWebSearch=r,_.enableImageGeneration=a,_.enableChart=c),z&&(_.clientTools=z),X&&(_.clientToolSystemPrompt=X);let p=await E.chat(A,N,_);if(!p.ok){let F=await p.text();throw new Error(`API error ${p.status}: ${F}`)}if(!p.body)throw new Error("No response body from server");L=p.body.getReader();let re=new TextDecoder,we="",H="",P="",ee="",Q="",pe="",le="",M=new co,Z=[],K=[],de=[],Se=()=>{let F=M.hasExecuting();F&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}T(H+M.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:ne}=await L.read();if(F)break;we+=re.decode(ne,{stream:!0});let O=we.split(`
116
+ `);we=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",P="";break;case"reasoning-delta":w.delta&&(P+=w.delta,T(`${Ue}[Thinking...]${se}
117
+ ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let $={type:"reasoning",id:ee,text:P,state:"done"};Q&&($.providerMetadata={anthropic:{signature:Q}}),K.push($),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T("");break;case"text-delta":w.delta&&(M.hasPending()&&(H=M.flushPending(H)),H+=w.delta,pe+=w.delta,T(H));break;case"tool-input-start":{let $=M.handleToolInputStart(w);$&&T(H+$),Se();break}case"tool-input-delta":{let $=M.handleToolInputDelta(w);$&&T(H+$),Se();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?Ze(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let $=uo(w.args??w.input);K.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added tool to messageParts",{messagePartsCount:K.length})}if(d&&w.toolCallId&&w.toolName&&Ze(w.toolName)){let $=uo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),T(H+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?Ze(w.toolName):!1});break}case"tool-output-start":{let $=M.handleToolOutputStart(w);$&&T(H+$),Se();break}case"tool-output-delta":{let $=M.handleToolOutputDelta(w);$&&T(H+$),Se();break}case"tool-output-end":{let $=M.handleToolOutputEnd(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"tool-input-error":case"tool-output-error":{let $=M.handleToolError(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let F=K.findIndex(O=>O.type!=="reasoning"),ne=F===-1?K.length:F;K.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:K.length,messageParts:K.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let F=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),M.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),M.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),T(H+M.buildToolDisplay()),Se();let w=await to(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let $=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:$}],isError:!w.success}),w.success){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},H);te&&(H=te.fullResponse)}else{let te=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},H);te&&(H=te.fullResponse)}T(H+M.buildToolDisplay()),Se()}Z.length=0;for(let f of F){let w=K.find($=>($.type==="tool-input-available"||$.type==="tool-call")&&$.toolCallId===f.toolCallId);if(w){let $=[];for(let R of f.content)R.type==="text"?$.push(R.text):R.type==="image"?$.push("[Image]"):R.type==="audio"?$.push("[Audio]"):(R.type==="resource"||R.type==="resource_link")&&$.push("[Resource]");let te=$.join(`
119
+ `);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),L)try{L.releaseLock()}catch{}let ne={id:e,clientToolResults:F};o?ne.agentId=o:(s&&(ne.model=s),ne.connectorIds=n??[],ne.enableSandbox=i,ne.enableWebSearch=r,ne.enableImageGeneration=a,ne.enableChart=c),z&&(ne.clientTools=z),X&&(ne.clientToolSystemPrompt=X),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:F.length});let O=await E.chat(A,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),L=O.body.getReader(),K.length=0,pe="",P="",ee="",Q="";;){let{done:f,value:w}=await L.read();if(f){ae("=== Continuation stream done ===");break}we+=re.decode(w,{stream:!0});let $=we.split(`
120
+ `);we=$.pop()||"";for(let te of $)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let R=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${R.type}`,R),R.type){case"reasoning-start":ee=R.id||"0",P="";break;case"reasoning-delta":R.delta&&(P+=R.delta,T(`${Ue}[Thinking...]${se}
121
+ ${P}`)),R.providerMetadata?.anthropic?.signature&&(Q=R.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let xe={type:"reasoning",id:ee,text:P,state:"done"};Q&&(xe.providerMetadata={anthropic:{signature:Q}}),K.push(xe),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T(H);break;case"text-delta":R.delta&&(H+=R.delta,pe+=R.delta,T(H));break;case"tool-call":case"tool-input-available":if(R.toolCallId&&R.toolName){let xe=uo(R.args??R.input);K.push({type:R.type,toolCallId:R.toolCallId,toolName:R.toolName,args:xe})}if(d&&R.toolCallId&&R.toolName&&Ze(R.toolName)){let xe=uo(R.args??R.input);Z.push({toolCallId:R.toolCallId,toolName:R.toolName,args:xe}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",R);break}}catch{}}if(pe){let f=K.findIndex($=>$.type!=="reasoning"),w=f===-1?K.length:f;K.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:K.length,fullResponseLength:H.length})}if(d&&z&&z.length>0){let F=[];for(let O of de)F.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of K)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=pt(F,x);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:K.filter(O=>O.type==="text").length,contentLength:ne.length}),C(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:H.length,fullResponsePreview:H.slice(0,200)});try{let{messages:F}=await E.getMessages(A,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=pt(O,x);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),C(O=>[...O,{role:"assistant",content:H}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),C(ne=>[...ne,{role:"assistant",content:H}])}}ae("=== Message handling complete ==="),T(""),b({status:"ready"}),y(!0),me.length>0&&j?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let me=E instanceof Error?E.message:"Failed to send message";b({status:"error",message:me})}finally{if(W&&(clearInterval(W),W=null),L)try{L.releaseLock()}catch{}}},[t,e,o,s,n,i,r,a,c,d,z,X,x,C,b,T,h,y,v,j])}}import{useState as Ft}from"react";var Vn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},Hn=new Map(Object.values(Vn).map(e=>[e.apiKey,e.name]));function Kn(){return Object.values(Vn)}function zn(e,t,o,s,n){let[i,r]=Ft(e),[a,c]=Ft(t),[d,x]=Ft(o),[C,b]=Ft(s),[T,h]=Ft(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:c,imageGeneration:d,setImageGeneration:x,chart:C,setChart:b,fileSystem:T,setFileSystem:h,capabilityLabelMap:Hn}}import{useEffect as Nr,useState as Er}from"react";function qn(e,t){let[o,s]=Er(null);return Nr(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new G().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Wo}from"react";function Yn(e,t,o){let[s,n]=Wo(e),[i,r]=Wo(t),[a,c]=Wo(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:c}}import{useApp as Dr,useInput as Or}from"ink";import{useCallback as et,useRef as Lr,useState as Ee}from"react";import{spawn as _r}from"child_process";function Xn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let i=_r(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Zn=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function Qn(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Zn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Zn}function es(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(s){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"chats":case"c":return{type:"chats"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:t}}}var ts=`Available commands:
122
122
  /help, /h, /? Show this help message
123
123
  /clear, /cls, /new Start a new chat
124
124
  /model [name], /m Show current model or switch to [name]
@@ -142,97 +142,97 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
142
142
 
143
143
  Keyboard shortcuts:
144
144
  Ctrl+O Toggle full output mode
145
- Ctrl+C Exit`;function Bo(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function es({input:e,setInput:t,chatId:n,setChatId:s,currentChatTitle:o,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:c,setCurrentAgentId:d,currentAgentDetails:$,setCurrentAgentDetails:C,activeConnectorIds:x,setActiveConnectorIds:v,sandbox:h,setSandbox:y,webSearch:k,setWebSearch:_,imageGeneration:F,setImageGeneration:K,chart:ie,setChart:Y,fileSystem:Ce,setFileSystem:j,availableModels:A,availableAgents:N,availableConnectors:R,messages:W,hasPersistedChat:E,setHasPersistedChat:me,setMessages:D,addSystemMessage:p,startNewChat:re,sendMessage:we,setFullOutput:z,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:M=!1}){let{exit:Z}=_r(),[q,de]=Ee([]),[$e,B]=Ee(0),[ne,L]=Ee(!1),[f,w]=Ee(null),[S,te]=Ee([]),[U,xe]=Ee(0),[tt,ot]=Ee(new Set),[De,nt]=Ee(new Set),[bo,Vt]=Ee([]),[je,gt]=Ee([]),[He,Kt]=Ee([]),[st,xo]=Ee([]),[We,Ve]=Ee(null),[zt,mt]=Ee(""),ut=Or(!1),[rt,ht]=Ee(!1),yt=Qe(async()=>{if(!P)return[];let I=new H,m=[],l;do{let u=await I.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:l});m.push(...u.skills),l=u.nextKey}while(l);return gt(m),m},[P]),wt=Qe(async()=>{if(!P)return[];let I=new H,m=[],l;do{let u=await I.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:l});m.push(...u.schedules),l=u.nextKey}while(l);return Kt(m),m},[P]),Ne=Qe(async I=>{if(I==="model"){if(A.length===0){p("No models available.");return}let m=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(m);let l=r?m.findIndex(u=>u.id===r):-1;xe(Math.max(l,0)),w("model")}else if(I==="agent"){if(N.length===0){p("No agents available.");return}let m=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(m);let l=c?m.findIndex(u=>u.id===c):-1;xe(Math.max(l,0)),w("agent")}else if(I==="skills"){let m=je;if(m.length===0)try{m=await yt()}catch{p("Failed to load skills.");return}if(m.length===0){p("No skills available.");return}let l=m.map(u=>({id:u.id,name:u.name,description:u.description}));te(l),xe(0),w("skills")}else if(I==="schedules"){let m=He;if(m.length===0)try{m=await wt()}catch{p("Failed to load schedules.");return}if(m.length===0){p("No schedules found.");return}let l=m.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(l),xe(0),w("schedules")}else if(I==="connectors"){if(R.length===0){p("No connectors available.");return}let m=R.map(l=>({id:l.id,name:l.name}));te(m),xe(0),ot(new Set(x||[])),w("connectors")}else if(I==="capabilities"){let m=Hn().map(u=>({id:u.id,name:u.name,description:u.description}));te(m),xe(0);let l=new Set;h&&l.add("sandbox"),k&&l.add("webSearch"),F&&l.add("imageGeneration"),ie&&l.add("chart"),Ce&&l.add("fileSystem"),nt(l),w("capabilities")}else if(I==="chats"){if(!P){p("Not authenticated.");return}try{let m=new H,{chats:l}=await m.getChats(P.accessToken,P.workspaceId,20);if(l.length===0){p("No chats available.");return}Vt(l);let u=l.map(T=>({id:T.id,name:T.title||"Untitled",description:new Date(T.createdAt).toLocaleDateString()}));te(u);let g=u.findIndex(T=>T.id===n);xe(Math.max(g,0)),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let m=G.getProfileNames(),l=G.getCurrentProfileName(),u=m.map(T=>({id:T,name:T,description:T===l?"(current)":void 0}));te(u);let g=u.findIndex(T=>T.id===l);xe(Math.max(g,0)),w("profile")}L(!1),de([])},[A,N,je,He,R,x,r,c,yt,wt,h,k,F,ie,Ce,P,n,p]),he=Qe(I=>{let m=oe.getAll(I);a(m.model?.default),d(void 0),C(null);let l=m.connectors?.defaults;v(l&&l.length>0?l:void 0);let u=m.capabilities;y(u?.sandbox??pe.sandbox),_(u?.webSearch??pe.webSearch),K(u?.imageGeneration??pe.imageGeneration),Y(u?.chart??pe.chart);let g=m.localTools;j(g?.fileSystem??pe.fileSystem)},[a,d,C,v,y,_,K,Y,j,pe]),Ke=Qe(async()=>{try{let I=await fe();ee({accessToken:I.accessToken,workspaceId:I.workspaceId}),Q({status:"ready"})}catch(I){if(ee(null),I instanceof ze){if(I.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(I.code==="no-workspace"){Q({status:"no-workspace"});return}}let m=I instanceof Error?I.message:"Failed to authenticate";Q({status:"error",message:m})}},[ee,Q]),kt=Qe(async I=>{switch(I.type){case"help":return p(Qn),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(I.value){let m=I.value.toLowerCase(),l=A.find(u=>u.id.toLowerCase()===m||u.name.toLowerCase().includes(m));if(l)c?re(`Switched to model: ${l.name} (new chat)`):p(`Switched to model: ${l.name}`),a(l.id),d(void 0),C(null),oe.setDefaultModel(l.id);else{let u=A.map(g=>g.name).join(", ");p(`Model "${I.value}" not found.
145
+ Ctrl+C Exit`;function Mo(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:c,setCurrentAgentId:d,currentAgentDetails:x,setCurrentAgentDetails:C,activeConnectorIds:b,setActiveConnectorIds:T,sandbox:h,setSandbox:y,webSearch:v,setWebSearch:j,imageGeneration:z,setImageGeneration:X,chart:ie,setChart:q,fileSystem:Ce,setFileSystem:U,availableModels:A,availableAgents:N,availableConnectors:L,messages:W,hasPersistedChat:E,setHasPersistedChat:me,setMessages:_,addSystemMessage:p,startNewChat:re,sendMessage:we,setFullOutput:H,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:M=!1}){let{exit:Z}=Dr(),[K,de]=Ee([]),[Se,F]=Ee(0),[ne,O]=Ee(!1),[f,w]=Ee(null),[$,te]=Ee([]),[R,xe]=Ee(0),[ot,nt]=Ee(new Set),[De,st]=Ee(new Set),[xo,Kt]=Ee([]),[je,mt]=Ee([]),[He,zt]=Ee([]),[rt,Co]=Ee([]),[Be,Ke]=Ee(null),[qt,ht]=Ee(""),dt=Lr(!1),[it,yt]=Ee(!1),wt=et(async()=>{if(!P)return[];let I=new G,m=[],l;do{let u=await I.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:l});m.push(...u.skills),l=u.nextKey}while(l);return mt(m),m},[P]),kt=et(async()=>{if(!P)return[];let I=new G,m=[],l;do{let u=await I.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:l});m.push(...u.schedules),l=u.nextKey}while(l);return zt(m),m},[P]),Ne=et(async I=>{if(I==="model"){if(A.length===0){p("No models available.");return}let m=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(m);let l=r?m.findIndex(u=>u.id===r):-1;xe(Math.max(l,0)),w("model")}else if(I==="agent"){if(N.length===0){p("No agents available.");return}let m=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(m);let l=c?m.findIndex(u=>u.id===c):-1;xe(Math.max(l,0)),w("agent")}else if(I==="skills"){let m=je;if(m.length===0)try{m=await wt()}catch{p("Failed to load skills.");return}if(m.length===0){p("No skills available.");return}let l=m.map(u=>({id:u.id,name:u.name,description:u.description}));te(l),xe(0),w("skills")}else if(I==="schedules"){let m=He;if(m.length===0)try{m=await kt()}catch{p("Failed to load schedules.");return}if(m.length===0){p("No schedules found.");return}let l=m.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(l),xe(0),w("schedules")}else if(I==="connectors"){if(L.length===0){p("No connectors available.");return}let m=L.map(l=>({id:l.id,name:l.name}));te(m),xe(0),nt(new Set(b||[])),w("connectors")}else if(I==="capabilities"){let m=Kn().map(u=>({id:u.id,name:u.name,description:u.description}));te(m),xe(0);let l=new Set;h&&l.add("sandbox"),v&&l.add("webSearch"),z&&l.add("imageGeneration"),ie&&l.add("chart"),Ce&&l.add("fileSystem"),st(l),w("capabilities")}else if(I==="chats"){if(!P){p("Not authenticated.");return}try{let m=new G,{chats:l}=await m.getChats(P.accessToken,P.workspaceId,20);if(l.length===0){p("No chats available.");return}Kt(l);let u=l.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));te(u);let g=u.findIndex(S=>S.id===o);xe(Math.max(g,0)),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let m=J.getProfileNames(),l=J.getCurrentProfileName(),u=m.map(S=>({id:S,name:S,description:S===l?"(current)":void 0}));te(u);let g=u.findIndex(S=>S.id===l);xe(Math.max(g,0)),w("profile")}O(!1),de([])},[A,N,je,He,L,b,r,c,wt,kt,h,v,z,ie,Ce,P,o,p]),he=et(I=>{let m=oe.getAll(I);a(m.model?.default),d(void 0),C(null);let l=m.connectors?.defaults;T(l&&l.length>0?l:void 0);let u=m.capabilities;y(u?.sandbox??pe.sandbox),j(u?.webSearch??pe.webSearch),X(u?.imageGeneration??pe.imageGeneration),q(u?.chart??pe.chart);let g=m.localTools;U(g?.fileSystem??pe.fileSystem)},[a,d,C,T,y,j,X,q,U,pe]),ze=et(async()=>{try{let I=await fe();ee({accessToken:I.accessToken,workspaceId:I.workspaceId}),Q({status:"ready"})}catch(I){if(ee(null),I instanceof qe){if(I.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(I.code==="no-workspace"){Q({status:"no-workspace"});return}}let m=I instanceof Error?I.message:"Failed to authenticate";Q({status:"error",message:m})}},[ee,Q]),bt=et(async I=>{switch(I.type){case"help":return p(ts),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(I.value){let m=I.value.toLowerCase(),l=A.find(u=>u.id.toLowerCase()===m||u.name.toLowerCase().includes(m));if(l)c?re(`Switched to model: ${l.name} (new chat)`):p(`Switched to model: ${l.name}`),a(l.id),d(void 0),C(null),oe.setDefaultModel(l.id);else{let u=A.map(g=>g.name).join(", ");p(`Model "${I.value}" not found.
146
146
  Available: ${u||"none"}`)}}else{let m=A.find(l=>l.id===r)?.name||r;p(r?`Current model: ${m}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return N.length===0?(p("No agents available."),!0):(Ne("agent"),!0);let m=I.value.toLowerCase(),l=N.find(u=>u.id.toLowerCase()===m||u.name.toLowerCase().includes(m));if(l)l.id!==c?re(`Switched to agent: ${l.name} (new chat)`):p(`Switched to agent: ${l.name}`),d(l.id),a(void 0);else{let u=N.map(g=>g.name).join(", ");p(`Agent "${I.value}" not found.
147
- Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return Ne("skills"),!0;let m=I.value.toLowerCase();return(je.length>0?Promise.resolve(je):yt().catch(()=>[])).then(u=>{let g=u.find(T=>T.id.toLowerCase()===m||T.name.toLowerCase().includes(m));p(g?`Skill: ${g.name}
147
+ Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return Ne("skills"),!0;let m=I.value.toLowerCase();return(je.length>0?Promise.resolve(je):wt().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===m||S.name.toLowerCase().includes(m));p(g?`Skill: ${g.name}
148
148
  ${g.description}
149
149
  Provider: ${g.provider}
150
150
  Author: ${g.author.name}
151
- ID: ${g.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return Ne("schedules"),!0;let m=I.value.toLowerCase();return(He.length>0?Promise.resolve(He):wt().catch(()=>[])).then(u=>{let g=u.find(T=>T.id.toLowerCase()===m||T.name.toLowerCase().includes(m));if(g){let T=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
151
+ ID: ${g.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return Ne("schedules"),!0;let m=I.value.toLowerCase();return(He.length>0?Promise.resolve(He):kt().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===m||S.name.toLowerCase().includes(m));if(g){let S=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
152
152
  Agent: ${g.agent.name}
153
153
  Status: ${g.isActive?"Active":"Paused"}
154
- Repeat: ${Bo(g.config)}
155
- Next Run: ${T}
156
- ID: ${g.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(c){let l=$?.connectors||[];if(l.length===0)p("No agent connectors.");else{let u=l.map(g=>` - ${g.name}`).join(`
154
+ Repeat: ${Mo(g.config)}
155
+ Next Run: ${S}
156
+ ID: ${g.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(c){let l=x?.connectors||[];if(l.length===0)p("No agent connectors.");else{let u=l.map(g=>` - ${g.name}`).join(`
157
157
  `);p(`Agent connectors:
158
- ${u}`)}return!0}let m=R.filter(l=>x?.includes(l.id));if(m.length===0)p("No active connectors.");else{let l=m.map(u=>` - ${u.name}`).join(`
158
+ ${u}`)}return!0}let m=L.filter(l=>b?.includes(l.id));if(m.length===0)p("No active connectors.");else{let l=m.map(u=>` - ${u.name}`).join(`
159
159
  `);p(`Active connectors:
160
- ${l}`)}return!0}case"capabilities":{if(c){let u=($?.capabilities||[]).map(g=>le.get(g)??g);return p(u.length>0?`Agent capabilities:
160
+ ${l}`)}return!0}case"capabilities":{if(c){let u=(x?.capabilities||[]).map(g=>le.get(g)??g);return p(u.length>0?`Agent capabilities:
161
161
  ${u.map(g=>` - ${g}`).join(`
162
- `)}`:"No agent capabilities."),!0}let m=[];return h&&m.push("Sandbox"),k&&m.push("Web Search"),F&&m.push("Image Generation"),ie&&m.push("Chart"),Ce&&m.push("FileSystem"),p(m.length>0?`Active capabilities:
162
+ `)}`:"No agent capabilities."),!0}let m=[];return h&&m.push("Sandbox"),v&&m.push("Web Search"),z&&m.push("Image Generation"),ie&&m.push("Chart"),Ce&&m.push("FileSystem"),p(m.length>0?`Active capabilities:
163
163
  ${m.map(l=>` - ${l}`).join(`
164
- `)}`:"No capabilities enabled."),!0}case"chats":return p(o?`Current chat: ${o}`:`Current chat: ${n.slice(0,8)}...`),!0;case"workspace":{if(!P)return p("Not authenticated."),!0;let m=new H;if(!I.value){try{let{workspaces:u}=await m.getWorkspaces(P.accessToken);if(u.length===0)p("No workspaces found.");else{let g=u.map(T=>` ${T.id===P.workspaceId?"* ":" "}${T.name}
165
- ID: ${T.id}`);p(`Workspaces:
164
+ `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!P)return p("Not authenticated."),!0;let m=new G;if(!I.value){try{let{workspaces:u}=await m.getWorkspaces(P.accessToken);if(u.length===0)p("No workspaces found.");else{let g=u.map(S=>` ${S.id===P.workspaceId?"* ":" "}${S.name}
165
+ ID: ${S.id}`);p(`Workspaces:
166
166
  ${g.join(`
167
- `)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let l=I.value;try{let{workspaces:u}=await m.getWorkspaces(P.accessToken),g=u.find(T=>T.id===l);if(!g)return p(`Workspace not found: ${l}`),!0;await Te.saveWorkspaceId(l),p(`Switched to workspace: ${g.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let m=new H;if(!I.value){try{let g=await m.getBudget(P.accessToken,P.workspaceId);g.budget===null?p("No budget set for this workspace."):p(`Current budget: $${g.budget}`)}catch(g){p(`Failed to get budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let l=I.value.toLowerCase();if(l==="clear"||l==="null"){try{await m.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(g){p(`Failed to clear budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let u=parseFloat(l);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await m.updateBudget(P.accessToken,P.workspaceId,l),p(`Budget set to: $${l}`)}catch(g){p(`Failed to set budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let m=new H;try{let l=[],u,g=0,T=10;do{let Se=await m.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(l.push(...Se.monthlyUsages),u=Se.nextKey,g++,g>=T){p(`Warning: Showing first ${l.length} entries (pagination limit reached)`);break}}while(u);if(l.length===0)return p("No usage data found for this workspace."),!0;let b=0,O=0;for(let Se of l)b+=parseFloat(Se.totalCost),O+=Se.operationCount;let ge=[...l].toSorted((Se,it)=>parseFloat(it.totalCost)-parseFloat(Se.totalCost)),J=10,ce=ge.slice(0,J),Oe=[`Total Cost: $${b.toFixed(2)}`,`Total Operations: ${O.toLocaleString()}`,`Users: ${l.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Se=>` ${Se.user.name}: $${parseFloat(Se.totalCost).toFixed(2)} (${Se.operationCount.toLocaleString()} ops)`)];l.length>J&&(Oe.push("",`... and ${l.length-J} more users`),Oe.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Oe.join(`
168
- `))}catch(l){p(`Failed to get usage: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"status":{let m=G.getCurrentProfileName(),l=r?A.find(b=>b.id===r)?.name||r:null,u=c?N.find(b=>b.id===c)?.name||c:null,g=x?R.filter(b=>x.includes(b.id)).map(b=>b.name):[],T=[];return h&&T.push("Sandbox"),k&&T.push("Web Search"),F&&T.push("Image Gen"),ie&&T.push("Chart"),Ce&&T.push("FileSystem"),Te.getEmail().then(b=>{let O=[`Profile: ${m}${m!=="default"?" (non-default)":""}`,b?`Logged in as: ${b}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${n}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${T.length>0?T.join(", "):"none"}`].filter(Boolean);p(O.join(`
169
- `))}).catch(()=>{let b=[`Profile: ${m}`,"Not logged in",E?`Chat ID: ${n}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${T.length>0?T.join(", "):"none"}`].filter(Boolean);p(b.join(`
170
- `))}),!0}case"profile":{let m=I.value?I.value.split(/\s+/).filter(Boolean):[];if(m.length===0)return Ne("profile"),!0;let l=m[0]?.toLowerCase()||"list",u=m[1],g=m[2],T=G.getProfileNames(),b=G.getCurrentProfileName(),O=G.getOverrideProfile(),ge=(J,ce=!1)=>{if(J)return J;if(ce&&T.length===1)return T[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(l==="list"){let J=[`Profiles (${T.length}):`];for(let ce of T){let Oe=ce===b?" (current)":"";J.push(` ${ce}${Oe}`)}return p(J.join(`
171
- `)),!0}if(l==="current")return p(`Current profile: ${b}`),!0;if(l==="show"){let J=ge(u,!0),ce=oe.getAll(J),Oe=await Te.getAll(J),Se=!!Oe?.accessToken,it=ce.capabilities?Object.entries(ce.capabilities).filter(([,Co])=>Co).map(([Co])=>Co):[],Js=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Gs=[`Profile: ${J}${J===b?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Js}`,`Capabilities: ${it.length>0?it.join(", "):"none"}`,Se?`Logged in as: ${Oe?.email??"unknown"}`:"Not logged in",Se&&Oe?.workspaceId?`Workspace ID: ${Oe.workspaceId}`:null].filter(Boolean);return p(Gs.join(`
172
- `)),!0}if(l==="create"){let J=u||G.DEFAULT_PROFILE;return G.createProfile(J),p(`Profile created: ${J}`),!0}if(l==="use"||l==="switch"){let J=ge(u,!0);return G.setOverrideProfile(J),G.setCurrentProfile(J),he(J),await Ke(),re(`Switched to profile: ${J} (new chat)`),!0}if(l==="delete"||l==="remove"||l==="rm"){let J=ge(u,!0),ce=J===b,Oe=G.deleteProfile(J),Se=`Profile deleted: ${J}`;if(ce)G.setOverrideProfile(Oe.currentProfile),he(Oe.currentProfile),await Ke(),re(`${Se}
173
- Switched to profile: ${Oe.currentProfile} (new chat)`);else if(O===J){let it=G.getCurrentProfileName();G.setOverrideProfile(it),he(it),await Ke(),re(`${Se}
174
- Switched to profile: ${it} (new chat)`)}else p(Se);return!0}if(l==="rename"||l==="move"||l==="mv"){let J=ge(u,!0);if(!g)throw new Error("New profile name is required.");let ce=G.renameProfile(J,g);return p(`Profile renamed: ${J} -> ${g}`),O===J?(G.setOverrideProfile(g),he(g)):ce.currentProfile===g&&he(g),!0}if(l==="clone"||l==="copy"){let J=ge(u,!0);if(!g)throw new Error("Target profile name is required.");let ce=oe.getAll(J);return G.createProfile(g),oe.setAll(ce,g),await Te.clear(g),p(`Profile cloned: ${J} -> ${g}`),!0}p(`Unknown profile command: ${l}`)}catch(J){let ce=J instanceof Error?J.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let m=qe().hubUrl.replace(/\/$/,""),u=E||W.some(b=>b.role!=="system")?`/chat/${n}`:"/chat/new",g=c?`?agentId=${encodeURIComponent(c)}`:"",T=`${m}${u}${g}`;try{await qn(T),p(`Opened in browser: ${T}`)}catch(b){p(`Failed to open browser: ${b instanceof Error?b.message:"Unknown error"}
175
- URL: ${T}`)}return!0}case"share":{if(!P)return p("Not authenticated."),!0;if(!(E||W.some(l=>l.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new H().createChatShare(P.accessToken,P.workspaceId,n,"public"),T=`${qe().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${T}`)}catch(l){p(`Failed to create share link: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"delete":return P?E?(ht(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${I.input}
176
- Type /help for available commands.`),!0;default:return!1}},[p,A,N,R,je,He,r,c,x,h,k,F,ie,Ce,n,o,Z,Ne,re,le,$,E,W,yt,wt,D,a,d,C,a,he,Ke]),qt=Qe(I=>{if(ut.current=!1,rt){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&ht(!1));return}if(t(I),mt(I),We!==null&&Ve(null),f&&(w(null),te([])),I.startsWith("/")&&!I.includes(" ")){let m=Xn(I);de(m),B(0),L(m.length>0)}else L(!1),de([])},[f,We,rt,t]),Pt=Qe((I,m=!1)=>{if(I>=0&&I<q.length){let l=q[I];L(!1),de([]),l.name==="model"?(t("/model "),Ne("model")):l.name==="agent"?(t("/agent "),Ne("agent")):l.name==="skills"?(t("/skills "),Ne("skills")):l.name==="schedules"?(t("/schedules "),Ne("schedules")):l.name==="connectors"?(t("/connectors "),Ne("connectors")):l.name==="capabilities"?(t("/capabilities "),Ne("capabilities")):l.name==="chats"?(t("/chats "),Ne("chats")):l.name==="profile"?(t("/profile "),Ne("profile")):m?(t(""),kt({type:l.name})):t(`/${l.name}`)}},[q,Ne,t,kt]),Yt=Qe(async I=>{ut.current=!1;let m=I.trim();if(!m||rt)return;if(f==="model"&&S.length>0){let u=S[U];u&&(c?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&S.length>0){let u=S[U];u&&(u.id!==c?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&S.length>0){let u=S[U];if(u){let g=je.find(T=>T.id===u.id);g&&p(`Skill: ${g.name}
167
+ `)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let l=I.value;try{let{workspaces:u}=await m.getWorkspaces(P.accessToken),g=u.find(S=>S.id===l);if(!g)return p(`Workspace not found: ${l}`),!0;await $e.saveWorkspaceId(l),p(`Switched to workspace: ${g.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let m=new G;if(!I.value){try{let g=await m.getBudget(P.accessToken,P.workspaceId);g.budget===null?p("No budget set for this workspace."):p(`Current budget: $${g.budget}`)}catch(g){p(`Failed to get budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let l=I.value.toLowerCase();if(l==="clear"||l==="null"){try{await m.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(g){p(`Failed to clear budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let u=parseFloat(l);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await m.updateBudget(P.accessToken,P.workspaceId,l),p(`Budget set to: $${l}`)}catch(g){p(`Failed to set budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let m=new G;try{let l=[],u,g=0,S=10;do{let Te=await m.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(l.push(...Te.monthlyUsages),u=Te.nextKey,g++,g>=S){p(`Warning: Showing first ${l.length} entries (pagination limit reached)`);break}}while(u);if(l.length===0)return p("No usage data found for this workspace."),!0;let k=0,D=0;for(let Te of l)k+=parseFloat(Te.totalCost),D+=Te.operationCount;let ge=[...l].toSorted((Te,at)=>parseFloat(at.totalCost)-parseFloat(Te.totalCost)),B=10,ce=ge.slice(0,B),Oe=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${D.toLocaleString()}`,`Users: ${l.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Te=>` ${Te.user.name}: $${parseFloat(Te.totalCost).toFixed(2)} (${Te.operationCount.toLocaleString()} ops)`)];l.length>B&&(Oe.push("",`... and ${l.length-B} more users`),Oe.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Oe.join(`
168
+ `))}catch(l){p(`Failed to get usage: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"status":{let m=J.getCurrentProfileName(),l=r?A.find(k=>k.id===r)?.name||r:null,u=c?N.find(k=>k.id===c)?.name||c:null,g=b?L.filter(k=>b.includes(k.id)).map(k=>k.name):[],S=[];return h&&S.push("Sandbox"),v&&S.push("Web Search"),z&&S.push("Image Gen"),ie&&S.push("Chart"),Ce&&S.push("FileSystem"),$e.getEmail().then(k=>{let D=[`Profile: ${m}${m!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${o}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(D.join(`
169
+ `))}).catch(()=>{let k=[`Profile: ${m}`,"Not logged in",E?`Chat ID: ${o}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(k.join(`
170
+ `))}),!0}case"profile":{let m=I.value?I.value.split(/\s+/).filter(Boolean):[];if(m.length===0)return Ne("profile"),!0;let l=m[0]?.toLowerCase()||"list",u=m[1],g=m[2],S=J.getProfileNames(),k=J.getCurrentProfileName(),D=J.getOverrideProfile(),ge=(B,ce=!1)=>{if(B)return B;if(ce&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(l==="list"){let B=[`Profiles (${S.length}):`];for(let ce of S){let Oe=ce===k?" (current)":"";B.push(` ${ce}${Oe}`)}return p(B.join(`
171
+ `)),!0}if(l==="current")return p(`Current profile: ${k}`),!0;if(l==="show"){let B=ge(u,!0),ce=oe.getAll(B),Oe=await $e.getAll(B),Te=!!Oe?.accessToken,at=ce.capabilities?Object.entries(ce.capabilities).filter(([,$o])=>$o).map(([$o])=>$o):[],Gs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Vs=[`Profile: ${B}${B===k?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Gs}`,`Capabilities: ${at.length>0?at.join(", "):"none"}`,Te?`Logged in as: ${Oe?.email??"unknown"}`:"Not logged in",Te&&Oe?.workspaceId?`Workspace ID: ${Oe.workspaceId}`:null].filter(Boolean);return p(Vs.join(`
172
+ `)),!0}if(l==="create"){let B=u||J.DEFAULT_PROFILE;return J.createProfile(B),p(`Profile created: ${B}`),!0}if(l==="use"||l==="switch"){let B=ge(u,!0);return J.setOverrideProfile(B),J.setCurrentProfile(B),he(B),await ze(),re(`Switched to profile: ${B} (new chat)`),!0}if(l==="delete"||l==="remove"||l==="rm"){let B=ge(u,!0),ce=B===k,Oe=J.deleteProfile(B),Te=`Profile deleted: ${B}`;if(ce)J.setOverrideProfile(Oe.currentProfile),he(Oe.currentProfile),await ze(),re(`${Te}
173
+ Switched to profile: ${Oe.currentProfile} (new chat)`);else if(D===B){let at=J.getCurrentProfileName();J.setOverrideProfile(at),he(at),await ze(),re(`${Te}
174
+ Switched to profile: ${at} (new chat)`)}else p(Te);return!0}if(l==="rename"||l==="move"||l==="mv"){let B=ge(u,!0);if(!g)throw new Error("New profile name is required.");let ce=J.renameProfile(B,g);return p(`Profile renamed: ${B} -> ${g}`),D===B?(J.setOverrideProfile(g),he(g)):ce.currentProfile===g&&he(g),!0}if(l==="clone"||l==="copy"){let B=ge(u,!0);if(!g)throw new Error("Target profile name is required.");let ce=oe.getAll(B);return J.createProfile(g),oe.setAll(ce,g),await $e.clear(g),p(`Profile cloned: ${B} -> ${g}`),!0}p(`Unknown profile command: ${l}`)}catch(B){let ce=B instanceof Error?B.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let m=Ye().hubUrl.replace(/\/$/,""),u=E||W.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",g=c?`?agentId=${encodeURIComponent(c)}`:"",S=`${m}${u}${g}`;try{await Xn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
175
+ URL: ${S}`)}return!0}case"share":{if(!P)return p("Not authenticated."),!0;if(!(E||W.some(l=>l.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new G().createChatShare(P.accessToken,P.workspaceId,o,"public"),S=`${Ye().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${S}`)}catch(l){p(`Failed to create share link: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"delete":return P?E?(yt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${I.input}
176
+ Type /help for available commands.`),!0;default:return!1}},[p,A,N,L,je,He,r,c,b,h,v,z,ie,Ce,o,n,Z,Ne,re,le,x,E,W,wt,kt,_,a,d,C,a,he,ze]),Yt=et(I=>{if(dt.current=!1,it){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&yt(!1));return}if(t(I),ht(I),Be!==null&&Ke(null),f&&(w(null),te([])),I.startsWith("/")&&!I.includes(" ")){let m=Qn(I);de(m),F(0),O(m.length>0)}else O(!1),de([])},[f,Be,it,t]),Nt=et((I,m=!1)=>{if(I>=0&&I<K.length){let l=K[I];O(!1),de([]),l.name==="model"?(t("/model "),Ne("model")):l.name==="agent"?(t("/agent "),Ne("agent")):l.name==="skills"?(t("/skills "),Ne("skills")):l.name==="schedules"?(t("/schedules "),Ne("schedules")):l.name==="connectors"?(t("/connectors "),Ne("connectors")):l.name==="capabilities"?(t("/capabilities "),Ne("capabilities")):l.name==="chats"?(t("/chats "),Ne("chats")):l.name==="profile"?(t("/profile "),Ne("profile")):m?(t(""),bt({type:l.name})):t(`/${l.name}`)}},[K,Ne,t,bt]),Xt=et(async I=>{dt.current=!1;let m=I.trim();if(!m||it)return;if(f==="model"&&$.length>0){let u=$[R];u&&(c?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&$.length>0){let u=$[R];u&&(u.id!==c?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&$.length>0){let u=$[R];if(u){let g=je.find(S=>S.id===u.id);g&&p(`Skill: ${g.name}
177
177
  ${g.description}
178
178
  Provider: ${g.provider}
179
179
  Author: ${g.author.name}
180
- ID: ${g.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&S.length>0){let u=S[U];if(u){let g=He.find(T=>T.id===u.id);if(g){let T=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
180
+ ID: ${g.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&$.length>0){let u=$[R];if(u){let g=He.find(S=>S.id===u.id);if(g){let S=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
181
181
  Agent: ${g.agent.name}
182
182
  Status: ${g.isActive?"Active":"Paused"}
183
- Repeat: ${Bo(g.config)}
184
- Next Run: ${T}
185
- ID: ${g.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(tt);v(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let g=R.filter(T=>tt.has(T.id)).map(T=>T.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=De.has("sandbox"),g=De.has("webSearch"),T=De.has("imageGeneration"),b=De.has("chart"),O=De.has("fileSystem");y(u),_(g),K(T),Y(b),j(O),oe.setCapabilities({sandbox:u,webSearch:g,imageGeneration:T,chart:b}),oe.setLocalTools({fileSystem:O});let ge=[];u&&ge.push("Sandbox"),g&&ge.push("Web Search"),T&&ge.push("Image Generation"),b&&ge.push("Chart"),O&&ge.push("FileSystem"),p(ge.length>0?`Active capabilities: ${ge.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&S.length>0){let u=S[U];if(u){let g=G.getCurrentProfileName();u.id!==g?(G.setOverrideProfile(u.id),G.setCurrentProfile(u.id),he(u.id),Ke(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&q.length>0){Pt($e,!0);return}Ve(null),mt(""),xo(u=>u.length>0&&u.at(-1)===m?u:[...u,m]);let l=Zn(m);if(l){await kt(l),t(""),L(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),L(!1),we(m)},[we,kt,ne,q,$e,Pt,f,S,U,tt,De,R,je,He,p,t,c,re,a,d,C,v,y,_,K,Y,j,M,he,Ke,rt,P,E,n]);return Dr((I,m)=>{if(m.ctrl&&I==="c"){if(e.length>0){qt(""),ut.current=!0,p("Press Ctrl+C again to exit.");return}if(ut.current){Z();return}Z();return}if(m.ctrl&&I==="o"){z(l=>!l);return}if(rt){if(m.escape||m.return||I==="n"||I==="N"){ht(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){ht(!1),t(""),P&&E&&new H().deleteChat(P.accessToken,P.workspaceId,n).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&S.length>0){if(m.upArrow){xe(l=>l<=0?S.length-1:l-1);return}if(m.downArrow){xe(l=>l>=S.length-1?0:l+1);return}if(m.escape){w(null),te([]),t("");return}if(m.return){if(f==="model"){let l=S[U];l&&(c?re(`Switched to model: ${l.name} (new chat)`):p(`Switched to model: ${l.name}`),a(l.id),d(void 0),C(null),oe.setDefaultModel(l.id))}else if(f==="agent"){let l=S[U];l&&(l.id!==c?re(`Switched to agent: ${l.name} (new chat)`):p(`Switched to agent: ${l.name}`),d(l.id),a(void 0))}else if(f==="skills"){let l=S[U];if(l){let u=je.find(g=>g.id===l.id);u&&p(`Skill: ${u.name}
183
+ Repeat: ${Mo(g.config)}
184
+ Next Run: ${S}
185
+ ID: ${g.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(ot);T(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let g=L.filter(S=>ot.has(S.id)).map(S=>S.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=De.has("sandbox"),g=De.has("webSearch"),S=De.has("imageGeneration"),k=De.has("chart"),D=De.has("fileSystem");y(u),j(g),X(S),q(k),U(D),oe.setCapabilities({sandbox:u,webSearch:g,imageGeneration:S,chart:k}),oe.setLocalTools({fileSystem:D});let ge=[];u&&ge.push("Sandbox"),g&&ge.push("Web Search"),S&&ge.push("Image Generation"),k&&ge.push("Chart"),D&&ge.push("FileSystem"),p(ge.length>0?`Active capabilities: ${ge.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&$.length>0){let u=$[R];if(u){let g=J.getCurrentProfileName();u.id!==g?(J.setOverrideProfile(u.id),J.setCurrentProfile(u.id),he(u.id),ze(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&K.length>0){Nt(Se,!0);return}Ke(null),ht(""),Co(u=>u.length>0&&u.at(-1)===m?u:[...u,m]);let l=es(m);if(l){await bt(l),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),we(m)},[we,bt,ne,K,Se,Nt,f,$,R,ot,De,L,je,He,p,t,c,re,a,d,C,T,y,j,X,q,U,M,he,ze,it,P,E,o]);return Or((I,m)=>{if(m.ctrl&&I==="c"){if(e.length>0){Yt(""),dt.current=!0,p("Press Ctrl+C again to exit.");return}if(dt.current){Z();return}Z();return}if(m.ctrl&&I==="o"){H(l=>!l);return}if(it){if(m.escape||m.return||I==="n"||I==="N"){yt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){yt(!1),t(""),P&&E&&new G().deleteChat(P.accessToken,P.workspaceId,o).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&$.length>0){if(m.upArrow){xe(l=>l<=0?$.length-1:l-1);return}if(m.downArrow){xe(l=>l>=$.length-1?0:l+1);return}if(m.escape){w(null),te([]),t("");return}if(m.return){if(f==="model"){let l=$[R];l&&(c?re(`Switched to model: ${l.name} (new chat)`):p(`Switched to model: ${l.name}`),a(l.id),d(void 0),C(null),oe.setDefaultModel(l.id))}else if(f==="agent"){let l=$[R];l&&(l.id!==c?re(`Switched to agent: ${l.name} (new chat)`):p(`Switched to agent: ${l.name}`),d(l.id),a(void 0))}else if(f==="skills"){let l=$[R];if(l){let u=je.find(g=>g.id===l.id);u&&p(`Skill: ${u.name}
186
186
  ${u.description}
187
187
  Provider: ${u.provider}
188
188
  Author: ${u.author.name}
189
- ID: ${u.id}`)}}else if(f==="schedules"){let l=S[U];if(l){let u=He.find(g=>g.id===l.id);if(u){let g=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
189
+ ID: ${u.id}`)}}else if(f==="schedules"){let l=$[R];if(l){let u=He.find(g=>g.id===l.id);if(u){let g=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
190
190
  Agent: ${u.agent.name}
191
191
  Status: ${u.isActive?"Active":"Paused"}
192
- Repeat: ${Bo(u.config)}
192
+ Repeat: ${Mo(u.config)}
193
193
  Next Run: ${g}
194
- ID: ${u.id}`)}}}else if(f==="connectors"){let l=Array.from(tt);v(l.length>0?l:void 0),oe.setDefaultConnectorIds(l);let u=R.filter(g=>tt.has(g.id)).map(g=>g.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let l=De.has("sandbox"),u=De.has("webSearch"),g=De.has("imageGeneration"),T=De.has("chart"),b=De.has("fileSystem");y(l),_(u),K(g),Y(T),j(b),oe.setCapabilities({sandbox:l,webSearch:u,imageGeneration:g,chart:T}),oe.setLocalTools({fileSystem:b});let O=[];l&&O.push("Sandbox"),u&&O.push("Web Search"),g&&O.push("Image Generation"),T&&O.push("Chart"),b&&O.push("FileSystem"),p(O.length>0?`Active capabilities: ${O.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let l=S[U];if(l){let u=bo.find(g=>g.id===l.id);u&&P&&(s(u.id),i(u.title||void 0),me(!0),new H().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:T})=>{let b=T.filter(O=>O.role==="user"||O.role==="assistant").map(O=>({role:O.role,content:ft(O.parts,!1),parts:O.parts})).filter(O=>O.content).toReversed();D(b),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let l=S[U];if(l){let u=G.getCurrentProfileName();l.id!==u?(G.setOverrideProfile(l.id),G.setCurrentProfile(l.id),he(l.id),Ke(),re(`Switched to profile: ${l.name}`)):p(`Already using profile: ${l.name}`)}}w(null),te([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let l=S[U];l&&(f==="connectors"?ot:nt)(g=>{let T=new Set(g);return T.has(l.id)?T.delete(l.id):T.add(l.id),T});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?ot:nt)(new Set(S.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?ot:nt)(new Set);return}return}if(ne&&q.length>0){if(m.upArrow){B(l=>l<=0?q.length-1:l-1);return}if(m.downArrow){B(l=>l>=q.length-1?0:l+1);return}if(m.escape){L(!1),de([]);return}if(m.tab){Pt($e);return}}if(m.upArrow){if(e.includes(`
195
- `)||st.length===0)return;if(We===null){mt(e);let u=st.length-1;Ve(u),t(st[u]);return}let l=Math.max(0,We-1);Ve(l),t(st[l]);return}if(m.downArrow){if(e.includes(`
196
- `)||We===null)return;if(We>=st.length-1){Ve(null),t(zt);return}let l=We+1;Ve(l),t(st[l])}}),{suggestions:q,suggestionIndex:$e,showSuggestions:ne,argMode:f,argItems:S,argIndex:U,selectedConnectorIds:tt,selectedCapabilities:De,deleteConfirmMode:rt,handleInputChange:qt,handleSubmit:Yt}}import{useCallback as Ft,useRef as Lr,useState as Rr}from"react";function ts({credentials:e,currentModel:t,modelProviders:n,onUploadSuccess:s,onUploadError:o}){let[i,r]=Rr([]),a=Lr(0),c=Ft(y=>{if(!(!Array.isArray(n)||n.length===0)){for(let k of n)if(k.models.some(F=>F.id===y))return k.id;return n[0]?.id}},[n]),d=Ft(async y=>{if(!e){o?.(y.filename,"Not logged in");return}if(!Array.isArray(n)||n.length===0){o?.(y.filename,"Model providers not loaded yet. Please wait and try again.");return}let k=t?c(t):n[0]?.id;if(!k){o?.(y.filename,"No model provider available");return}let _=`file-${++a.current}`;r(F=>[...F,{id:_,filename:y.filename,mimeType:y.mimeType,status:"uploading"}]);try{let K=await new H().uploadFile(e.accessToken,e.workspaceId,y,k);r(ie=>ie.map(Y=>Y.id===_?{...Y,status:"uploaded",fileId:K.id}:Y)),s?.(y.filename)}catch(F){let K=F instanceof Error?F.message:"Upload failed";r(ie=>ie.map(Y=>Y.id===_?{...Y,status:"error",error:K}:Y)),o?.(y.filename,K)}},[e,t,c,n,s,o]),$=Ft(y=>{r(k=>k.filter(_=>_.id!==y))},[]),C=Ft(()=>{r([])},[]),x=Ft(()=>i.filter(y=>y.status==="uploaded"&&y.fileId).map(y=>y.fileId),[i]),v=i.some(y=>y.status==="uploading"),h=i.length>0;return{pendingFiles:i,addFile:d,removeFile:$,clearFiles:C,getUploadedFileIds:x,hasUploadingFiles:v,hasFiles:h}}import{jsx as X,jsxs as ue}from"react/jsx-runtime";var jr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Fr=[jo,jo,Uo,Uo,dt,dt,dt,dt],ns=jr.map((e,t)=>`${Fr[t]??dt}${e}${se}`).join(`
197
- `),Br=`${dt}EntryDesk${se}`,Wr=500;function Mr(e){let t="",n=0;for(;n<e.length;){if(e.charCodeAt(n)===27&&e[n+1]==="["){for(n+=2;n<e.length;){let s=e.charCodeAt(n);if(s>=64&&s<=126){n+=1;break}n+=1}continue}t+=e[n],n+=1}return t}function Jr(e){let t=Mr(e);return Math.max(...t.split(`
198
- `).map(n=>n.length))}function Gr(e){let t=Jr(ns);return e>=t?ns:Br}function ss({agentId:e,model:t,message:n,chatId:s,chatTitle:o,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:c=!1,enableChart:d=!1,enableFileSystem:$=!0}){let C=process.stdout.columns??80,x=Gr(C),v=os(null),h=Rn(s,o),{state:y,setState:k,messages:_,setMessages:F,input:K,setInput:ie,chatId:Y,setChatId:Ce,currentChatTitle:j,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:R,credentials:W,setCredentials:E,currentResponse:me,setCurrentResponse:D,fullOutput:p,setFullOutput:re,addSystemMessage:we,startNewChat:z}=h,{credentials:P}=jn(k);uo(()=>{P&&!W&&E(P)},[P,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:M}=Fn(W),{currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:$e,activeConnectorIds:B,setActiveConnectorIds:ne}=zn(t,e,i),L=os(!1);uo(()=>{if(!L.current){if(L.current=!0,!t&&!e){let b=oe.getDefaultModel();b&&q(b)}if(!i&&!e){let b=oe.getDefaultConnectorIds();b&&ne(b.length>0?b:void 0)}}},[t,e,i,q,ne]);let{currentAgentDetails:f}=Kn(de,W),{sandbox:w,setSandbox:S,webSearch:te,setWebSearch:U,imageGeneration:xe,setImageGeneration:tt,chart:ot,setChart:De,fileSystem:nt,setFileSystem:bo,capabilityLabelMap:Vt}=Vn(r,a,c,d,$),{pendingFiles:je,addFile:gt,removeFile:He,clearFiles:Kt,getUploadedFileIds:st,hasUploadingFiles:xo,hasFiles:We}=ts({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:b=>{we(`\u2713 Attached: ${b}`)},onUploadError:(b,O)=>{we(`\u2717 Failed to upload ${b}: ${O}`)}}),{sendMessage:Ve}=Mn({chatId:Y,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:B,sandbox:w,webSearch:te,imageGeneration:xe,chart:ot,localTools:nt,fullOutput:p,setMessages:F,setState:k,setCurrentResponse:D,setCredentials:E,setHasPersistedChat:R,getFileIds:st,clearFiles:Kt}),zt=Jo(b=>{z(b),D("")},[z]),[mt,ut]=Ur(!1),rt=Jo(async b=>{let O=b.text.trim(),ge=ao(O);if(/^https?:\/\//.test(ge))return;if(await _n(O)&&En(ge)){let ce=await Dn(O);ce&&(b.preventDefault(),await gt(ce))}},[gt]),ht=Jo(async()=>{if(!(mt||y.status!=="ready")){if(M||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),ut(!0);try{let b=await Nn();if(b){let O=`clipboard-${Date.now()}.png`;we(`Uploading: ${O} (${Math.round(b.buffer.length/1024)}KB)`),await gt({buffer:b.buffer,filename:O,mimeType:b.mime})}else we("No image found in clipboard. Copy an image first.")}catch(b){let O=b instanceof Error?b.message:"Failed to read clipboard";we(`Clipboard error: ${O}`)}finally{ut(!1)}}},[gt,we,mt,y.status,M,le.length]),{suggestions:yt,suggestionIndex:wt,showSuggestions:Ne,argMode:he,argItems:Ke,argIndex:kt,selectedConnectorIds:qt,selectedCapabilities:Pt,deleteConfirmMode:Yt,handleInputChange:I,handleSubmit:m}=es({input:K,setInput:ie,chatId:Y,setChatId:Ce,currentChatTitle:j,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:$e,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:B,setActiveConnectorIds:ne,sandbox:w,setSandbox:S,webSearch:te,setWebSearch:U,imageGeneration:xe,setImageGeneration:tt,chart:ot,setChart:De,fileSystem:nt,setFileSystem:bo,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:_,hasPersistedChat:N,setHasPersistedChat:R,setMessages:F,addSystemMessage:we,startNewChat:zt,sendMessage:Ve,setFullOutput:re,credentials:W,setCredentials:E,setState:k,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:c,chart:d,fileSystem:$},capabilityLabelMap:Vt,hasUploadingFiles:xo});if(Wo((b,O)=>{(O.ctrl||O.meta)&&b==="v"&&ht()},{isActive:y.status==="ready"&&!he}),Wo((b,O)=>{if(!O.escape)return;let ge=Date.now(),J=v.current;v.current=ge,!(!J||ge-J>Wr)&&(he||Ne||(v.current=null,We&&Kt(),K.length>0&&I("")))},{isActive:y.status==="ready"}),Wo((b,O)=>{O.return&&(zt("Started a new chat."),k({status:"ready"}))},{isActive:y.status==="error"}),uo(()=>{if(W&&!M&&y.status==="loading")if(!Z&&!de){let b=oe.getDefaultModel(),O=b&&Q.some(J=>J.id===b),ge=O?b:Q[0]?.id;ge?(O||oe.setDefaultModel(ge),q(ge),k({status:"ready"})):pe.length===0?k({status:"no-model"}):k({status:"ready"})}else k({status:"ready"})},[W,M,Z,de,Q,pe,y.status,q,k]),uo(()=>{n&&W&&y.status==="ready"&&Ve(n)},[W,n]),y.status==="loading")return ue(Ie,{flexDirection:"column",children:[X(V,{children:x}),ue(Ie,{children:[X(V,{color:"cyan",children:X(Mo,{type:"dots"})}),X(V,{children:" Initializing chat..."})]})]});if(y.status==="not-logged-in")return ue(Ie,{flexDirection:"column",children:[X(V,{children:x}),X(V,{color:"yellow",children:"Not logged in"}),X(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(y.status==="no-workspace")return ue(Ie,{flexDirection:"column",children:[X(V,{children:x}),X(V,{color:"yellow",children:"No workspace selected"}),X(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(y.status==="no-model")return ue(Ie,{flexDirection:"column",children:[X(V,{children:x}),X(V,{color:"yellow",children:"No model or agent specified"}),s&&X(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(y.status==="error")return ue(Ie,{flexDirection:"column",children:[X(V,{children:x}),ue(V,{color:"red",children:["Error: ",y.message]}),X(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let l=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(b=>b.name).join(", "):"none":"loading...":B&&B.length>0?ee.filter(b=>B.includes(b.id)).map(b=>b.name).join(", ")||`${B.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let b of f.capabilities)u.push(Vt.get(b)??b);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),xe&&u.push("Image"),ot&&u.push("Chart");nt&&u.push("FileSystem");let g=G.getCurrentProfileName(),T=g!=="default";return ue(Ie,{flexDirection:"column",children:[ue(Ie,{marginBottom:1,flexDirection:"column",children:[X(V,{children:x}),ue(Ie,{children:[X(V,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.8.2"]}),T&&ue(V,{color:"magenta",children:[" [",g,"]"]}),X(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),_.map((b,O)=>{let ge=b.parts&&p?ft(b.parts,!0):b.content,J=b.role==="user"?"green":b.role==="system"?"yellow":"blue",ce=b.role==="user"?"You":b.role==="system"?"System":"Assistant";return ue(Ie,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:J,children:[ce,":"]}),X(Ro,{text:ge})]},O)}),me&&ue(Ie,{flexDirection:"column",marginBottom:1,children:[X(V,{bold:!0,color:"blue",children:"Assistant:"}),X(Ro,{text:me})]}),y.status==="ready"&&X(pn,{suggestions:yt,activeIndex:wt,visible:Ne}),y.status==="ready"&&he&&X(fn,{items:Ke,activeIndex:kt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?qt:he==="capabilities"?Pt:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),y.status==="sending"&&!me?ue(Ie,{children:[X(V,{color:"cyan",children:X(Mo,{type:"dots"})}),X(V,{children:" Thinking..."})]}):y.status==="ready"&&!he?ue(Ie,{flexDirection:"column",children:[Yt&&X(Ie,{marginBottom:1,children:X(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),We&&!Yt&&ue(Ie,{marginBottom:1,flexDirection:"row",gap:1,children:[X(V,{dimColor:!0,children:"Attachments:"}),je.map((b,O)=>ue(V,{children:[b.status==="uploading"?ue(V,{color:"yellow",children:[X(Mo,{type:"dots"})," ",b.filename]}):b.status==="error"?ue(V,{color:"red",children:["\u2717 ",b.filename]}):ue(V,{color:"green",children:["\u2713 ",b.filename]}),O<je.length-1&&X(V,{children:", "})]},b.id))]}),ue(Ie,{children:[X(V,{color:"green",children:"> "}),X(xn,{value:K,onChange:I,onSubmit:m,onPaste:rt,leadingOffset:2,multiline:!0})]})]}):null,ue(Ie,{marginTop:1,flexDirection:"column",children:[ue(Ie,{gap:2,children:[ue(V,{children:[X(V,{dimColor:!0,children:"Model: "}),X(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(b=>b.id===Z)?.name||Z||"none"})]}),ue(V,{children:[X(V,{dimColor:!0,children:"Connectors: "}),X(V,{color:"cyan",children:l})]}),ue(V,{children:[X(V,{dimColor:!0,children:"Capabilities: "}),X(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 qr}from"react/jsx-runtime";async function Vr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function Kr(e,t,n,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:o}=await e.getChats(t,n,20);if(o.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>o.length)return console.error(`Chat number ${s} not found. You have ${o.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=o[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,n,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var $t="\x1B[2m",_e="\x1B[0m",Go="\x1B[36m",ls="\x1B[33m",po="\x1B[32m",rs="stream-json";function is(e,t,n,s){e&&t&&(console.error(`Error: Cannot use both ${n} and ${s}`),process.exit(1))}function go(e,t){let n=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(n)}
199
- `)}function mo(e,t){if(t)return e;let n=e.split(`
200
- `);if(n.length<=20)return e;let s=n.slice(0,5),o=n.slice(-5),i=n.length-10;return[...s,`${$t}... (${i} lines omitted, use --full-output to see all) ...${_e}`,...o].join(`
201
- `)}function zr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function as(e,t){if(!e)return"(no result)";if(typeof e!="object")return mo(String(e),t);let n=e;if("structuredContent"in n&&n.structuredContent){let s=n.structuredContent,o=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&o.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&o.push(`${ls}[stderr]${_e} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&o.push(`${r.path}: ${r.url}`)}return o.length===0&&o.push(JSON.stringify(s,null,2)),mo(o.join(`
202
- `),t)}if("content"in n&&Array.isArray(n.content)){let o=n.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
203
- `);return mo(o||JSON.stringify(e,null,2),t)}return mo(JSON.stringify(e,null,2),t)}async function cs(e){let t,n;try{let ee=await fe();t=ee.accessToken,n=ee.workspaceId}catch(ee){ke(ee)}let s=e.output===rs;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${rs}`),process.exit(1));let o=!s&&(e.plain||!process.stdout.isTTY),i=oe.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await Vr());let a=new H;async function c(){if(!i)try{let{models:ee}=await a.getModels(t,n),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),i=Q}catch{}}let d,$,C,x;if(e.continue){let ee=await Kr(a,t,n,e.continue);ee||process.exit(1),d=ee.chat.id,$=ee.chat.title??void 0,C=ee.chat.agentId??void 0,x=ee.modelId;let Q=e.agentId||e.model||C||x||i;!Q&&!e.interactive&&(await c(),Q=e.agentId||e.model||C||x||i),!Q&&!e.interactive&&(o||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)),!o&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
205
- `)}let v=e.agentId||C,h=e.model||x||i||void 0;!v&&!h&&(await c(),h=e.model||x||i||void 0),is(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),is(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let y=oe.getCapabilities(),k=e.noSandbox?!1:e.sandbox?!0:y?.sandbox??!0,_=e.webSearch??y?.webSearch??!1,F=e.imageGen??y?.imageGeneration??!1,K=e.chart??y?.chart??!1,ie=oe.getDefaultConnectorIds(),Y=e.connectors??ie??void 0,Ce=oe.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:Ce?.fileSystem??!0;if(e.interactive){Hr(qr(ss,{agentId:v,model:h,message:e.message,chatId:d,chatTitle:$??void 0,connectorIds:Y,enableSandbox:k,enableWebSearch:_,enableImageGeneration:F,enableChart:K,enableFileSystem:j}),{exitOnCtrlC:!1});return}let A=!e.continue&&!h&&!v;(!r||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||fo(),W=j?Zt():void 0,E=j?Qt():void 0,me=[],D=fo(),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}]}),v?le.agentId=v:(h&&(le.model=h),le.connectorIds=Y??[],le.enableSandbox=k,le.enableWebSearch=_,le.enableImageGeneration=F,le.enableChart=K),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:$e}=await Q.read();if(de)break;le+=pe.decode($e,{stream:!0});let B=le.split(`
206
- `);le=B.pop()||"";for(let ne of B){let L=ne.trimEnd();if(L==="data: [DONE]"){s&&go("done");continue}if(L.startsWith("data: "))try{let f=JSON.parse(L.slice(6));if(f.type&&q.push(f),s){f.type==="text-delta"&&f.delta!==void 0?go("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?go("reasoning-delta",f.delta):go(f.type||"event",f);continue}if(o){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&&Xe(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(`${$t}${f.delta}${_e}`);break;case"reasoning-end":process.stdout.write(`
207
-
208
- `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let S=j&&Xe(f.toolName)?`${po}[LOCAL]${_e} `:"";console.log(`
209
- ${Go}\u250C\u2500 ${S}Tool Call: ${f.toolName}${_e}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},S=zr(w);console.log(`${ls}\u2502 Arguments:${_e}`);for(let te of S.split(`
210
- `))console.log(`${$t}\u2502 ${te}${_e}`);j&&Xe(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),S=as(f.result,N);console.log(`${po}\u2502 Result:${_e}`);for(let te of S.split(`
211
- `))console.log(`${$t}\u2502 ${te}${_e}`);console.log(`${Go}\u2514\u2500 ${w?.toolName||"Tool"} completed${_e}
212
- `),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${$t}Error: ${f.errorText}${_e}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:q}},we=p({id:fo(),text:r}),z=await a.chat(t,n,we),P=await re(z);for(me=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let M of P.pendingClientTools){!o&&!s&&console.log(`${po}\u2502 Executing locally...${_e}`);let Z=await eo(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}),!o&&!s){let de=as(Z.success?Z.result:{error:Z.error},N);console.log(`${po}\u2502 Result:${_e}`);for(let $e of de.split(`
213
- `))console.log(`${$t}\u2502 ${$e}${_e}`);console.log(`${Go}\u2514\u2500 ${M.toolName} completed${_e}
214
- `)}}let Q=me.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:D,role:"assistant",parts:Q}];D=fo();let le=p(void 0,ee,pe);z=await a.chat(t,n,le),P=await re(z),me=P.messageParts}s||console.log("")}var Bt="\x1B[2m",Ae="\x1B[0m",ct="\x1B[36m",Vo="\x1B[33m",us="\x1B[32m",ds="stream-json";function Ge(e,t){let n=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(n)}
216
- `)}function Ho(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),o=Math.floor(s/(1e3*60*60*24));return o===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):o===1?"Yesterday":o<7?`${o} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function ho(e,t){if(t)return e;let n=e.split(`
217
- `);if(n.length<=15)return e;let s=n.slice(0,6),o=n.slice(-4),i=n.length-10;return[...s,`... (${i} lines omitted, use --full-output to see all) ...`,...o].join(`
218
- `)}function Ko(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ko);let t={};for(let[n,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[n]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[n]=Ko(s):t[n]=s;return t}function fs(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ps(e,t){if(!e)return"(no result)";if(typeof e!="object")return ho(String(e),t);let n=t?e:Ko(e);if("structuredContent"in n&&n.structuredContent){let s=n.structuredContent,o=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&o.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&o.push(`${Vo}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&o.push(`${r.path}: ${r.url}`)}return o.length===0&&o.push(JSON.stringify(s,null,2)),ho(o.join(`
219
- `),t)}if("content"in n&&Array.isArray(n.content)){let o=n.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
220
- `);return ho(o||JSON.stringify(e,null,2),t)}return ho(JSON.stringify(e,null,2),t)}function Yr(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 gs(e,t){let n=[];for(let s of e)if(s.type==="reasoning"&&s.text)n.push(`${Bt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)n.push(s.text);else if(s.type==="tool-call"&&s.toolName){let o=[];if(o.push(`${ct}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){o.push(`${Vo}\u2502 Arguments:${Ae}`);let i=fs(s.args);for(let r of i.split(`
221
- `))o.push(`${Bt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){o.push(`${us}\u2502 Result:${Ae}`);let i=ps(s.result,t);for(let r of i.split(`
222
- `))o.push(`${Bt}\u2502 ${r}${Ae}`);o.push(`${ct}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?o.push(`${ct}\u2514\u2500 (awaiting result)${Ae}`):o.push(`${ct}\u2514\u2500${Ae}`);n.push(o.join(`
223
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let o=Yr(s),i=[];if(i.push(`${ct}\u250C\u2500 Tool: ${o}${Ae}`),s.input){i.push(`${Vo}\u2502 Input:${Ae}`);let r=fs(s.input);for(let a of r.split(`
224
- `))i.push(`${Bt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${us}\u2502 Output:${Ae}`);let r=ps(s.output,t);for(let a of r.split(`
225
- `))i.push(`${Bt}\u2502 ${a}${Ae}`);i.push(`${ct}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?i.push(`${ct}\u2514\u2500 (in progress)${Ae}`):i.push(`${ct}\u2514\u2500${Ae}`);n.push(i.join(`
226
- `))}return n.join(`
227
-
228
- `).trim()}async function ms(e){let t=e.output===ds;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ds}`),process.exit(1));let n=new H;if(e.shareId){let r;try{r=await at()}catch{}try{let a=await n.getSharedChat(e.shareId,r),{messages:c}=await n.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:c}));return}if(t){if(Ge("chat",a),c.length===0)Ge("info","No messages in this shared chat.");else for(let C of c.toReversed())Ge("message",C);Ge("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${c.length} messages
229
- `),c.length===0){console.log("No messages in this shared chat.");return}let d=c.toReversed(),$=e.fullOutput??!1;for(let C of d){let x=gs(C.parts,$);if(!x)continue;let v=C.role==="user"?"You":"Assistant";console.log(`[${v}] ${Ho(C.createdAt)}`),console.log(x),console.log("")}return}catch(a){if(a instanceof Error){let c=a.message.toLowerCase();c.includes("401")||c.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):c.includes("404")||c.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,o;try{let r=await fe();s=r.accessToken,o=r.workspaceId}catch(r){ke(r)}if(e.chatId){let r=e.chatId,a=!1,c=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let h=d===0?1:d,{chats:y}=await n.getChats(s,o,20);h>y.length&&(console.error(`Chat number ${h} not found. You have ${y.length} recent chats.`),process.exit(1));let k=y[h-1];r=k.id,a=!0,c=k,t||console.log(`Chat: ${k.title||"Untitled"}
230
- `)}let{messages:C}=await n.getMessages(s,o,r,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(c&&Ge("chat",c),C.length===0)Ge("info","No messages in this chat.");else for(let h of C.toReversed())Ge("message",h);Ge("done");return}if(C.length===0){console.log("No messages in this chat.");return}let x=C.toReversed(),v=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
231
- `);for(let h of x){let y=gs(h.parts,v);if(!y)continue;let k=h.role==="user"?"You":"Assistant";console.log(`[${k}] ${Ho(h.createdAt)}`),console.log(y),console.log("")}return}let{chats:i}=await n.getChats(s,o,20);if(t){for(let r of i)Ge("chat",r);Ge("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
232
- `),i.forEach((r,a)=>{let c=(a+1).toString().padStart(2," ");console.log(` ${c}. ${Ho(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Xr,Text as Pe}from"ink";import{jsx as Le,jsxs as St}from"react/jsx-runtime";var Tt=["apiUrl","hubUrl"];function zo(e){return Tt.includes(e)}async function hs(e){let t=e.action||"list",n=e.configKey,s=e.value,o=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: ${o}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${Tt.join(", ")}`);return}console.log(`Configuration:
194
+ ID: ${u.id}`)}}}else if(f==="connectors"){let l=Array.from(ot);T(l.length>0?l:void 0),oe.setDefaultConnectorIds(l);let u=L.filter(g=>ot.has(g.id)).map(g=>g.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let l=De.has("sandbox"),u=De.has("webSearch"),g=De.has("imageGeneration"),S=De.has("chart"),k=De.has("fileSystem");y(l),j(u),X(g),q(S),U(k),oe.setCapabilities({sandbox:l,webSearch:u,imageGeneration:g,chart:S}),oe.setLocalTools({fileSystem:k});let D=[];l&&D.push("Sandbox"),u&&D.push("Web Search"),g&&D.push("Image Generation"),S&&D.push("Chart"),k&&D.push("FileSystem"),p(D.length>0?`Active capabilities: ${D.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let l=$[R];if(l){let u=xo.find(g=>g.id===l.id);u&&P&&(s(u.id),i(u.title||void 0),me(!0),new G().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(D=>D.role==="user"||D.role==="assistant").map(D=>({role:D.role,content:pt(D.parts,!1),parts:D.parts})).filter(D=>D.content).toReversed();_(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let l=$[R];if(l){let u=J.getCurrentProfileName();l.id!==u?(J.setOverrideProfile(l.id),J.setCurrentProfile(l.id),he(l.id),ze(),re(`Switched to profile: ${l.name}`)):p(`Already using profile: ${l.name}`)}}w(null),te([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let l=$[R];l&&(f==="connectors"?nt:st)(g=>{let S=new Set(g);return S.has(l.id)?S.delete(l.id):S.add(l.id),S});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set($.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set);return}return}if(ne&&K.length>0){if(m.upArrow){F(l=>l<=0?K.length-1:l-1);return}if(m.downArrow){F(l=>l>=K.length-1?0:l+1);return}if(m.escape){O(!1),de([]);return}if(m.tab){Nt(Se);return}}if(m.upArrow){if(e.includes(`
195
+ `)||rt.length===0)return;if(Be===null){ht(e);let u=rt.length-1;Ke(u),t(rt[u]);return}let l=Math.max(0,Be-1);Ke(l),t(rt[l]);return}if(m.downArrow){if(e.includes(`
196
+ `)||Be===null)return;if(Be>=rt.length-1){Ke(null),t(qt);return}let l=Be+1;Ke(l),t(rt[l])}}),{suggestions:K,suggestionIndex:Se,showSuggestions:ne,argMode:f,argItems:$,argIndex:R,selectedConnectorIds:ot,selectedCapabilities:De,deleteConfirmMode:it,handleInputChange:Yt,handleSubmit:Xt}}import{useCallback as Wt,useRef as Rr,useState as Ur}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=Ur([]),a=Rr(0),c=Wt(y=>{if(!(!Array.isArray(o)||o.length===0)){for(let v of o)if(v.models.some(z=>z.id===y))return v.id;return o[0]?.id}},[o]),d=Wt(async y=>{if(!e){n?.(y.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(y.filename,"Model providers not loaded yet. Please wait and try again.");return}let v=t?c(t):o[0]?.id;if(!v){n?.(y.filename,"No model provider available");return}let j=`file-${++a.current}`;r(z=>[...z,{id:j,filename:y.filename,mimeType:y.mimeType,status:"uploading"}]);try{let X=await new G().uploadFile(e.accessToken,e.workspaceId,y,v);r(ie=>ie.map(q=>q.id===j?{...q,status:"uploaded",fileId:X.id}:q)),s?.(y.filename)}catch(z){let X=z instanceof Error?z.message:"Upload failed";r(ie=>ie.map(q=>q.id===j?{...q,status:"error",error:X}:q)),n?.(y.filename,X)}},[e,t,c,o,s,n]),x=Wt(y=>{r(v=>v.filter(j=>j.id!==y))},[]),C=Wt(()=>{r([])},[]),b=Wt(()=>i.filter(y=>y.status==="uploaded"&&y.fileId).map(y=>y.fileId),[i]),T=i.some(y=>y.status==="uploading"),h=i.length>0;return{pendingFiles:i,addFile:d,removeFile:x,clearFiles:C,getUploadedFileIds:b,hasUploadingFiles:T,hasFiles:h}}import{jsx as Y,jsxs as ue}from"react/jsx-runtime";var Fr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Fo,Fo,jo,jo,ft,ft,ft,ft],rs=Fr.map((e,t)=>`${Wr[t]??ft}${e}${se}`).join(`
197
+ `),Mr=`${ft}EntryDesk${se}`,Br=500;function Jr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Gr(e){let t=Jr(e);return Math.max(...t.split(`
198
+ `).map(o=>o.length))}function Vr(e){let t=Gr(rs);return e>=t?rs:Mr}function is({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:c=!1,enableChart:d=!1,enableFileSystem:x=!0}){let C=process.stdout.columns??80,b=Vr(C),T=ss(null),h=jn(s,n),{state:y,setState:v,messages:j,setMessages:z,input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:L,credentials:W,setCredentials:E,currentResponse:me,setCurrentResponse:_,fullOutput:p,setFullOutput:re,addSystemMessage:we,startNewChat:H}=h,{credentials:P}=Wn(v);fo(()=>{P&&!W&&E(P)},[P,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:M}=Mn(W),{currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,activeConnectorIds:F,setActiveConnectorIds:ne}=Yn(t,e,i),O=ss(!1);fo(()=>{if(!O.current){if(O.current=!0,!t&&!e){let k=oe.getDefaultModel();k&&K(k)}if(!i&&!e){let k=oe.getDefaultConnectorIds();k&&ne(k.length>0?k:void 0)}}},[t,e,i,K,ne]);let{currentAgentDetails:f}=qn(de,W),{sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:xe,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:xo,capabilityLabelMap:Kt}=zn(r,a,c,d,x),{pendingFiles:je,addFile:mt,removeFile:He,clearFiles:zt,getUploadedFileIds:rt,hasUploadingFiles:Co,hasFiles:Be}=ns({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:k=>{we(`\u2713 Attached: ${k}`)},onUploadError:(k,D)=>{we(`\u2717 Failed to upload ${k}: ${D}`)}}),{sendMessage:Ke}=Gn({chatId:q,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:F,sandbox:w,webSearch:te,imageGeneration:xe,chart:nt,localTools:st,fullOutput:p,setMessages:z,setState:v,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:L,getFileIds:rt,clearFiles:zt}),qt=Go(k=>{H(k),_("")},[H]),[ht,dt]=jr(!1),it=Go(async k=>{let D=k.text.trim(),ge=lo(D);if(/^https?:\/\//.test(ge))return;if(await On(D)&&Dn(ge)){let ce=await Ln(D);ce&&(k.preventDefault(),await mt(ce))}},[mt]),yt=Go(async()=>{if(!(ht||y.status!=="ready")){if(M||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),dt(!0);try{let k=await _n();if(k){let D=`clipboard-${Date.now()}.png`;we(`Uploading: ${D} (${Math.round(k.buffer.length/1024)}KB)`),await mt({buffer:k.buffer,filename:D,mimeType:k.mime})}else we("No image found in clipboard. Copy an image first.")}catch(k){let D=k instanceof Error?k.message:"Failed to read clipboard";we(`Clipboard error: ${D}`)}finally{dt(!1)}}},[mt,we,ht,y.status,M,le.length]),{suggestions:wt,suggestionIndex:kt,showSuggestions:Ne,argMode:he,argItems:ze,argIndex:bt,selectedConnectorIds:Yt,selectedCapabilities:Nt,deleteConfirmMode:Xt,handleInputChange:I,handleSubmit:m}=os({input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:ne,sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:xe,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:xo,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:j,hasPersistedChat:N,setHasPersistedChat:L,setMessages:z,addSystemMessage:we,startNewChat:qt,sendMessage:Ke,setFullOutput:re,credentials:W,setCredentials:E,setState:v,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:c,chart:d,fileSystem:x},capabilityLabelMap:Kt,hasUploadingFiles:Co});if(Bo((k,D)=>{(D.ctrl||D.meta)&&k==="v"&&yt()},{isActive:y.status==="ready"&&!he}),Bo((k,D)=>{if(!D.escape)return;let ge=Date.now(),B=T.current;T.current=ge,!(!B||ge-B>Br)&&(he||Ne||(T.current=null,Be&&zt(),X.length>0&&I("")))},{isActive:y.status==="ready"}),Bo((k,D)=>{D.return&&(qt("Started a new chat."),v({status:"ready"}))},{isActive:y.status==="error"}),fo(()=>{if(W&&!M&&y.status==="loading")if(!Z&&!de){let k=oe.getDefaultModel(),D=k&&Q.some(B=>B.id===k),ge=D?k:Q[0]?.id;ge?(D||oe.setDefaultModel(ge),K(ge),v({status:"ready"})):pe.length===0?v({status:"no-model"}):v({status:"ready"})}else v({status:"ready"})},[W,M,Z,de,Q,pe,y.status,K,v]),fo(()=>{o&&W&&y.status==="ready"&&Ke(o)},[W,o]),y.status==="loading")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Initializing chat..."})]})]});if(y.status==="not-logged-in")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"Not logged in"}),Y(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(y.status==="no-workspace")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No workspace selected"}),Y(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(y.status==="no-model")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No model or agent specified"}),s&&Y(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),Y(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),Y(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(y.status==="error")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),ue(V,{color:"red",children:["Error: ",y.message]}),Y(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let l=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":F&&F.length>0?ee.filter(k=>F.includes(k.id)).map(k=>k.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let k of f.capabilities)u.push(Kt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),xe&&u.push("Image"),nt&&u.push("Chart");st&&u.push("FileSystem");let g=J.getCurrentProfileName(),S=g!=="default";return ue(ve,{flexDirection:"column",children:[ue(ve,{marginBottom:1,flexDirection:"column",children:[Y(V,{children:b}),ue(ve,{children:[Y(V,{bold:!0,color:"cyan",children:U?`Continuing: ${U}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.8.4"]}),S&&ue(V,{color:"magenta",children:[" [",g,"]"]}),Y(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),j.map((k,D)=>{let ge=k.parts&&p?pt(k.parts,!0):k.content,B=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ce=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return ue(ve,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:B,children:[ce,":"]}),Y(Uo,{text:ge})]},D)}),me&&ue(ve,{flexDirection:"column",marginBottom:1,children:[Y(V,{bold:!0,color:"blue",children:"Assistant:"}),Y(Uo,{text:me})]}),y.status==="ready"&&Y(mn,{suggestions:wt,activeIndex:kt,visible:Ne}),y.status==="ready"&&he&&Y(gn,{items:ze,activeIndex:bt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?Yt:he==="capabilities"?Nt:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),y.status==="sending"&&!me?ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Thinking..."})]}):y.status==="ready"&&!he?ue(ve,{flexDirection:"column",children:[Xt&&Y(ve,{marginBottom:1,children:Y(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Be&&!Xt&&ue(ve,{marginBottom:1,flexDirection:"row",gap:1,children:[Y(V,{dimColor:!0,children:"Attachments:"}),je.map((k,D)=>ue(V,{children:[k.status==="uploading"?ue(V,{color:"yellow",children:[Y(Jo,{type:"dots"})," ",k.filename]}):k.status==="error"?ue(V,{color:"red",children:["\u2717 ",k.filename]}):ue(V,{color:"green",children:["\u2713 ",k.filename]}),D<je.length-1&&Y(V,{children:", "})]},k.id))]}),ue(ve,{children:[Y(V,{color:"green",children:"> "}),Y($n,{value:X,onChange:I,onSubmit:m,onPaste:it,leadingOffset:2,multiline:!0})]})]}):null,ue(ve,{marginTop:1,flexDirection:"column",children:[ue(ve,{gap:2,children:[ue(V,{children:[Y(V,{dimColor:!0,children:"Model: "}),Y(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(k=>k.id===Z)?.name||Z||"none"})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Connectors: "}),Y(V,{color:"cyan",children:l})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Capabilities: "}),Y(V,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(V,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Yr}from"react/jsx-runtime";async function Kr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function zr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=n[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,o,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var St="\x1B[2m",_e="\x1B[0m",Vo="\x1B[36m",us="\x1B[33m",go="\x1B[32m",as="stream-json";function ls(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function mo(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
199
+ `)}function ho(e,t){if(t)return e;let o=e.split(`
200
+ `);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${St}... (${i} lines omitted, use --full-output to see all) ...${_e}`,...n].join(`
201
+ `)}function qr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cs(e,t){if(!e)return"(no result)";if(typeof e!="object")return ho(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${us}[stderr]${_e} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),ho(n.join(`
202
+ `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
203
+ `);return ho(n||JSON.stringify(e,null,2),t)}return ho(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){ke(ee)}let s=e.output===as;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${as}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=oe.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await Kr());let a=new G;async function c(){if(!i)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),i=Q}catch{}}let d,x,C,b;if(e.continue){let ee=await zr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,x=ee.chat.title??void 0,C=ee.chat.agentId??void 0,b=ee.modelId;let Q=e.agentId||e.model||C||b||i;!Q&&!e.interactive&&(await c(),Q=e.agentId||e.model||C||b||i),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
204
+ Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
205
+ `)}let T=e.agentId||C,h=e.model||b||i||void 0;!T&&!h&&(await c(),h=e.model||b||i||void 0),ls(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),ls(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let y=oe.getCapabilities(),v=e.noSandbox?!1:e.sandbox?!0:y?.sandbox??!0,j=e.webSearch??y?.webSearch??!1,z=e.imageGen??y?.imageGeneration??!1,X=e.chart??y?.chart??!1,ie=oe.getDefaultConnectorIds(),q=e.connectors??ie??void 0,Ce=oe.getLocalTools(),U=e.noFileSystem?!1:e.fileSystem?!0:Ce?.fileSystem??!0;if(e.interactive){Hr(Yr(is,{agentId:T,model:h,message:e.message,chatId:d,chatTitle:x??void 0,connectorIds:q,enableSandbox:v,enableWebSearch:j,enableImageGeneration:z,enableChart:X,enableFileSystem:U}),{exitOnCtrlC:!1});return}let A=!e.continue&&!h&&!T;(!r||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,L=d||po(),W=U?Qt():void 0,E=U?eo():void 0,me=[],_=po(),p=(ee,Q,pe)=>{let le={id:L};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),T?le.agentId=T:(h&&(le.model=h),le.connectorIds=q??[],le.enableSandbox=v,le.enableWebSearch=j,le.enableImageGeneration=z,le.enableChart=X),W&&(le.clientTools=W),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},re=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",M=new Map,Z=[],K=[];for(;;){let{done:de,value:Se}=await Q.read();if(de)break;le+=pe.decode(Se,{stream:!0});let F=le.split(`
206
+ `);le=F.pop()||"";for(let ne of F){let O=ne.trimEnd();if(O==="data: [DONE]"){s&&mo("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&K.push(f),s){f.type==="text-delta"&&f.delta!==void 0?mo("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?mo("reasoning-delta",f.delta):mo(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),U&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&Ze(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${St}${f.delta}${_e}`);break;case"reasoning-end":process.stdout.write(`
207
+
208
+ `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let $=U&&Ze(f.toolName)?`${go}[LOCAL]${_e} `:"";console.log(`
209
+ ${Vo}\u250C\u2500 ${$}Tool Call: ${f.toolName}${_e}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},$=qr(w);console.log(`${us}\u2502 Arguments:${_e}`);for(let te of $.split(`
210
+ `))console.log(`${St}\u2502 ${te}${_e}`);U&&Ze(f.toolName)&&(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),$=cs(f.result,N);console.log(`${go}\u2502 Result:${_e}`);for(let te of $.split(`
211
+ `))console.log(`${St}\u2502 ${te}${_e}`);console.log(`${Vo}\u2514\u2500 ${w?.toolName||"Tool"} completed${_e}
212
+ `),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${St}Error: ${f.errorText}${_e}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:K}},we=p({id:po(),text:r}),H=await a.chat(t,o,we),P=await re(H);for(me=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let M of P.pendingClientTools){!n&&!s&&console.log(`${go}\u2502 Executing locally...${_e}`);let Z=await to(M.toolName,M.args),K=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:K}],isError:!Z.success}),!n&&!s){let de=cs(Z.success?Z.result:{error:Z.error},N);console.log(`${go}\u2502 Result:${_e}`);for(let Se of de.split(`
213
+ `))console.log(`${St}\u2502 ${Se}${_e}`);console.log(`${Vo}\u2514\u2500 ${M.toolName} completed${_e}
214
+ `)}}let Q=me.map(M=>{if(M.type==="tool-call"){let Z=ee.find(de=>de.toolCallId===M.toolCallId),K=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:K}}return M}),pe=[{id:_,role:"assistant",parts:Q}];_=po();let le=p(void 0,ee,pe);H=await a.chat(t,o,le),P=await re(H),me=P.messageParts}s||console.log("")}var Mt="\x1B[2m",Ae="\x1B[0m",ut="\x1B[36m",Ko="\x1B[33m",fs="\x1B[32m",ps="stream-json";function Ve(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
216
+ `)}function Ho(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function yo(e,t){if(t)return e;let o=e.split(`
217
+ `);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),i=o.length-10;return[...s,`... (${i} lines omitted, use --full-output to see all) ...`,...n].join(`
218
+ `)}function zo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(zo);let t={};for(let[o,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[o]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[o]=zo(s):t[o]=s;return t}function gs(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ms(e,t){if(!e)return"(no result)";if(typeof e!="object")return yo(String(e),t);let o=t?e:zo(e);if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${Ko}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),yo(n.join(`
219
+ `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
220
+ `);return yo(n||JSON.stringify(e,null,2),t)}return yo(JSON.stringify(e,null,2),t)}function Xr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function hs(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Mt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${ut}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Ko}\u2502 Arguments:${Ae}`);let i=gs(s.args);for(let r of i.split(`
221
+ `))n.push(`${Mt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){n.push(`${fs}\u2502 Result:${Ae}`);let i=ms(s.result,t);for(let r of i.split(`
222
+ `))n.push(`${Mt}\u2502 ${r}${Ae}`);n.push(`${ut}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${ut}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${ut}\u2514\u2500${Ae}`);o.push(n.join(`
223
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Xr(s),i=[];if(i.push(`${ut}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${Ko}\u2502 Input:${Ae}`);let r=gs(s.input);for(let a of r.split(`
224
+ `))i.push(`${Mt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${fs}\u2502 Output:${Ae}`);let r=ms(s.output,t);for(let a of r.split(`
225
+ `))i.push(`${Mt}\u2502 ${a}${Ae}`);i.push(`${ut}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?i.push(`${ut}\u2514\u2500 (in progress)${Ae}`):i.push(`${ut}\u2514\u2500${Ae}`);o.push(i.join(`
226
+ `))}return o.join(`
227
+
228
+ `).trim()}async function ys(e){let t=e.output===ps;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ps}`),process.exit(1));let o=new G;if(e.shareId){let r;try{r=await lt()}catch{}try{let a=await o.getSharedChat(e.shareId,r),{messages:c}=await o.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:c}));return}if(t){if(Ve("chat",a),c.length===0)Ve("info","No messages in this shared chat.");else for(let C of c.toReversed())Ve("message",C);Ve("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${c.length} messages
229
+ `),c.length===0){console.log("No messages in this shared chat.");return}let d=c.toReversed(),x=e.fullOutput??!1;for(let C of d){let b=hs(C.parts,x);if(!b)continue;let T=C.role==="user"?"You":"Assistant";console.log(`[${T}] ${Ho(C.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let c=a.message.toLowerCase();c.includes("401")||c.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):c.includes("404")||c.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await fe();s=r.accessToken,n=r.workspaceId}catch(r){ke(r)}if(e.chatId){let r=e.chatId,a=!1,c=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let h=d===0?1:d,{chats:y}=await o.getChats(s,n,20);h>y.length&&(console.error(`Chat number ${h} not found. You have ${y.length} recent chats.`),process.exit(1));let v=y[h-1];r=v.id,a=!0,c=v,t||console.log(`Chat: ${v.title||"Untitled"}
230
+ `)}let{messages:C}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(c&&Ve("chat",c),C.length===0)Ve("info","No messages in this chat.");else for(let h of C.toReversed())Ve("message",h);Ve("done");return}if(C.length===0){console.log("No messages in this chat.");return}let b=C.toReversed(),T=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
231
+ `);for(let h of b){let y=hs(h.parts,T);if(!y)continue;let v=h.role==="user"?"You":"Assistant";console.log(`[${v}] ${Ho(h.createdAt)}`),console.log(y),console.log("")}return}let{chats:i}=await o.getChats(s,n,20);if(t){for(let r of i)Ve("chat",r);Ve("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
232
+ `),i.forEach((r,a)=>{let c=(a+1).toString().padStart(2," ");console.log(` ${c}. ${Ho(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Zr,Text as Pe}from"ink";import{jsx as Le,jsxs as Tt}from"react/jsx-runtime";var It=["apiUrl","hubUrl"];function qo(e){return It.includes(e)}async function ws(e){let t=e.action||"list",o=e.configKey,s=e.value,n=J.getEffectiveProfileName();if(t==="list"){let i=oe.getAll(),r=Object.entries(i);if(e.json){console.log(JSON.stringify(i));return}if(console.log(`Profile: ${n}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${It.join(", ")}`);return}console.log(`Configuration:
233
233
  `);for(let[a,c]of r)console.log(` ${a}=${c}`);console.log(`
234
- Available keys: ${Tt.join(", ")}`);return}if(t==="get"){n||(console.error("Error: key is required for get action"),process.exit(1)),zo(n)||(console.error(`Error: Invalid key '${n}'. Valid keys: ${Tt.join(", ")}`),process.exit(1));let i=oe.get(n);e.json?console.log(JSON.stringify({[n]:i??null})):console.log(i||"Not set");return}if(t==="set"){n||(console.error("Error: key is required for set action"),process.exit(1)),zo(n)||(console.error(`Error: Invalid key '${n}'. Valid keys: ${Tt.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(n,s),console.log(`Set ${n}=${s}`);return}if(t==="unset"){n||(console.error("Error: key is required for unset action"),process.exit(1)),zo(n)||(console.error(`Error: Invalid key '${n}'. Valid keys: ${Tt.join(", ")}`),process.exit(1)),oe.unset(n),console.log(`Unset ${n}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ys(){let e=qe();return St(Xr,{flexDirection:"column",children:[Le(Pe,{bold:!0,children:"entrydesk config"}),Le(Pe,{children:" "}),Le(Pe,{children:"Manage CLI configuration"}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Usage:"}),Le(Pe,{children:" entrydesk config List all configuration"}),St(Pe,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),St(Pe,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),St(Pe,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Available keys:"}),St(Pe,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),St(Pe,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Examples:"}),Le(Pe,{children:" entrydesk config set apiUrl http://localhost:3200"}),Le(Pe,{children:" entrydesk config get apiUrl"}),Le(Pe,{children:" entrydesk config unset apiUrl"})]})}async function ws(e){try{let t,n;try{let i=await fe();t=i.accessToken,n=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new H,{connectors:o}=await s.getConnectors(t,n);if(e.json){console.log(JSON.stringify(o));return}if(o.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${o.length}):
235
- `);for(let i of o){let r=i.connected?"connected":"disconnected";console.log(` ${i.name} (${r})`),console.log(` Provider: ${i.provider}`),console.log(` ID: ${i.id}`),console.log("")}}catch(t){ke(t)}}function yo(){console.log(`
234
+ Available keys: ${It.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1));let i=oe.get(o);e.json?console.log(JSON.stringify({[o]:i??null})):console.log(i||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ks(){let e=Ye();return Tt(Zr,{flexDirection:"column",children:[Le(Pe,{bold:!0,children:"entrydesk config"}),Le(Pe,{children:" "}),Le(Pe,{children:"Manage CLI configuration"}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Usage:"}),Le(Pe,{children:" entrydesk config List all configuration"}),Tt(Pe,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Available keys:"}),Tt(Pe,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Tt(Pe,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Examples:"}),Le(Pe,{children:" entrydesk config set apiUrl http://localhost:3200"}),Le(Pe,{children:" entrydesk config get apiUrl"}),Le(Pe,{children:" entrydesk config unset apiUrl"})]})}async function bs(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new G,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
235
+ `);for(let i of n){let r=i.connected?"connected":"disconnected";console.log(` ${i.name} (${r})`),console.log(` Provider: ${i.provider}`),console.log(` ID: ${i.id}`),console.log("")}}catch(t){ke(t)}}function wo(){console.log(`
236
236
  EntryDesk CLI - Interact with EntryDesk from your terminal
237
237
 
238
238
  Usage: entrydesk <command> [options]
@@ -397,9 +397,10 @@ Local Development:
397
397
  $ entrydesk config set hubUrl http://localhost:3000
398
398
 
399
399
  For more information, visit https://entrydesk.com/docs/cli
400
- `)}import{execFile as Zr}from"child_process";import{setTimeout as Qr}from"timers/promises";import{decodeJwt as ei}from"jose";import ti,{HTTPError as oi}from"ky";var ks="entrydesk-cli",ni="offline_access workspaces:read chats:read chats:write chats:delete agents:read agents:write connectors:read connectors:write tools:read tools:execute skills:read skills:write meetings:read meetings:write publishes:read publishes:write calendar:read calendar:write schedules:read schedules:write user:read user:write";function si(e){return new Promise((t,n)=>{let s=process.platform,o,i;switch(s){case"darwin":o="open",i=[e];break;case"win32":o="cmd",i=["/c","start","",e];break;default:o="xdg-open",i=[e];break}Zr(o,i,r=>{r?n(new Error(`Failed to open browser. Please manually visit: ${e}`,{cause:r})):t()})})}async function bs(e){let t=en(),n=tn(),s=on(),o=process.env.NODE_TLS_REJECT_UNAUTHORIZED;s.ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",console.error("WARNING: SSL certificate validation is disabled globally for this process during the login flow. All connections in this process will skip TLS verification. Only use ENTRYDESK_IGNORE_SSL_ERRORS for local development."));try{let i=ti.create({prefixUrl:t,timeout:3e4,hooks:{beforeError:[k=>(k.request?.headers&&(k.request.headers.delete("authorization"),k.request.headers.delete("Authorization")),k)]}}),r;try{r=await i.post("v1/oauth/device/code",{json:{client_id:ks,scope:ni}}).json()}catch(k){let _=k instanceof Error?k:new Error("Failed to request device code");throw e?.onError?.(_),_}let{device_code:a,user_code:c,expires_in:d,interval:$}=r,C=new URL("/oauth/device",n);C.searchParams.set("user_code",c);let x=C.toString();e?.onDeviceCodeReceived?.(c,x),e?.onBrowserOpening?.();try{await si(x)}catch(k){process.env.DEBUG&&console.error("[DEBUG] Failed to open browser:",k)}e?.onWaitingForAuthorization?.();let h=Math.max($,5)*1e3,y=Date.now()+d*1e3;for(;Date.now()<y;){await Qr(h);try{let k=await i.post("v1/oauth/token",{json:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:a,client_id:ks}}).json();e?.onAuthorized?.();let _={};try{_=ei(k.access_token)}catch{}return{accessToken:k.access_token,refreshToken:k.refresh_token??void 0,email:_.email||"",scopes:k.scope.split(" ").filter(F=>F.length>0)}}catch(k){if(k instanceof oi){let F;try{let K=await k.response.json();F=K.code||K.error}catch{continue}switch(F){case"authorization_pending":continue;case"slow_down":h+=5e3;continue;case"access_denied":throw new Error("Authorization denied by user",{cause:k});case"expired_token":throw new Error("Device code expired. Please try again.",{cause:k});default:throw new Error(`Authorization failed: ${F||"Unknown error"}`,{cause:k})}}let _=k instanceof Error?k:new Error("Unknown error during authorization");throw e?.onError?.(_),_}}throw new Error("Device code expired. Please try again.")}finally{o===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=o}}async function xs(e){if(process.env.DEBUG){let{getApiUrl:i,getHubUrl:r}=await import("./config-NHNGDQX6.js");console.log(`[DEBUG] Hub URL: ${r()}`),console.log(`[DEBUG] API URL: ${i()}`)}let t=await bs({onDeviceCodeReceived:(i,r)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${r}`),console.log(` 2. Enter code: ${i}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),n=new H,{workspaces:s}=await n.getWorkspaces(t.accessToken),o=s[0];await Te.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:o?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:o?.id,workspaceName:o?.name})):(console.log(`Logged in as ${t.email}`),o&&console.log(`Workspace: ${o.name}`))}async function Cs(e){try{let t=await Te.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new H().revokeToken(t.refreshToken)}catch{}await Te.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import ri from"http";import{Client as ii}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ai}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as li}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ci}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ui}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as di,ListToolsRequestSchema as fi}from"@modelcontextprotocol/sdk/types.js";async function pi(e,t,n){let s=new ii({name:"entrydesk-cli-proxy",version:"1.0.0"}),o=new URL(`${e}/v1/workspaces/${n}/mcp`),i=new ai(o,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function $s(e){let t=new li({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(fi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(di,async n=>{let{name:s,arguments:o}=n.params,i=await e.callTool({name:s,arguments:o}),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 gi(e,t){let n=ri.createServer(async(s,o)=>{if(s.method==="OPTIONS"){o.setHeader("Access-Control-Allow-Origin","*"),o.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),o.writeHead(204),o.end();return}if(s.url!=="/mcp"){o.writeHead(404,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Not found"}));return}let i=$s(e),r=new ui({sessionIdGenerator:void 0});if(o.setHeader("Access-Control-Allow-Origin","*"),o.on("close",()=>{r.close(),i.close()}),await i.connect(r),s.method==="POST"){let a="";s.on("data",c=>{a+=c.toString()}),s.on("end",async()=>{try{let c=JSON.parse(a);await r.handleRequest(s,o,c)}catch{o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Invalid JSON"}))}})}else await r.handleRequest(s,o)});n.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(`
401
- Shutting down...`),n.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{n.close(),await e.close(),process.exit(0)})}async function mi(e){let t=$s(e),n=new ci;n.onclose=async()=>{await e.close()},await t.connect(n)}async function Ss(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,n;try{let r=await fe();t=r.accessToken,n=r.workspaceId}catch(r){let a=r instanceof Error?r.message:"Authentication failed";console.error(a),process.exit(1)}let{apiUrl:s,mcp:o}=qe();console.error(`[entrydesk-mcp] Connecting to ${s}...`),console.error(`[entrydesk-mcp] Workspace: ${n}`);let i=await pi(s,t,n);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||o.httpPort;await gi(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await mi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Ts(e){try{let t,n;try{let i=await fe();t=i.accessToken,n=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new H,{models:o}=await s.getModels(t,n);if(e.json){console.log(JSON.stringify(o));return}if(o.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${o.length}):
402
- `);for(let i of o)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){ke(t)}}function hi(){console.log(`
400
+ `)}async function xs(e){if(process.env.DEBUG){let{getApiUrl:i,getHubUrl:r}=await import("./config-WCQC54DU.js");console.log(`[DEBUG] Hub URL: ${r()}`),console.log(`[DEBUG] API URL: ${i()}`)}let t=await on({onDeviceCodeReceived:(i,r)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${r}`),console.log(` 2. Enter code: ${i}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),o=new G,{workspaces:s}=await o.getWorkspaces(t.accessToken),n=s[0];await $e.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:n?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:n?.id,workspaceName:n?.name})):(console.log(`Logged in as ${t.email}`),n&&console.log(`Workspace: ${n.name}`))}async function Cs(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new G().revokeOAuthToken({token:t.refreshToken,clientId:tn})}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import Qr from"http";import{stderr as ei}from"process";import{Client as ti}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as oi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as ni}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as si}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ri}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ii,ListToolsRequestSchema as ai}from"@modelcontextprotocol/sdk/types.js";function We(e){ei.write(`${e}
401
+ `)}async function $s(e,t,o){let s=new ti({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new oi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Ss(e){let t=new ni({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(ai,async()=>({tools:(await(await e()).listTools()).tools})),t.setRequestHandler(ii,async o=>{let{name:s,arguments:n}=o.params,r=await(await e()).callTool({name:s,arguments:n}),a=Array.isArray(r.content)?[...r.content]:[];return r.structuredContent&&a.push({type:"text",text:JSON.stringify(r.structuredContent,null,2)}),{content:a,structuredContent:r.structuredContent,isError:r.isError}}),t}async function li(e,t,o){let s=Qr.createServer(async(n,i)=>{if(n.method==="OPTIONS"){i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),i.writeHead(204),i.end();return}if(n.url!=="/mcp"){i.writeHead(404,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Not found"}));return}let r=Ss(e),a=new ri({sessionIdGenerator:void 0});if(i.setHeader("Access-Control-Allow-Origin","*"),i.on("close",()=>{a.close(),r.close()}),await r.connect(a),n.method==="POST"){let c="";n.on("data",d=>{c+=d.toString()}),n.on("end",async()=>{try{let d=JSON.parse(c);await a.handleRequest(n,i,d)}catch{i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Invalid JSON"}))}})}else await a.handleRequest(n,i)});s.listen(o,()=>{We(`EntryDesk MCP server running at http://localhost:${o}/mcp`),We("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{We(`
402
+ Shutting down...`),s.close(),await t(),process.exit(0)}),process.on("SIGTERM",async()=>{s.close(),await t(),process.exit(0)})}async function ci(e,t){let o=Ss(e),s=new si;s.onclose=async()=>{await t()},await o.connect(s)}async function Ts(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{We("[entrydesk-mcp] Starting MCP server...");let t,o;try{let d=await fe();t=d.accessToken,o=d.workspaceId}catch(d){let x=d instanceof Error?d.message:"Authentication failed";console.error(x),process.exit(1)}let{apiUrl:s,mcp:n}=Ye();We(`[entrydesk-mcp] Connecting to ${s}...`),We(`[entrydesk-mcp] Workspace: ${o}`);let i=await $s(s,t,o);We("[entrydesk-mcp] Connected to EntryDesk API");let r=null,a=async()=>nn(t)?r||(r=(async()=>{We("[entrydesk-mcp] Token expiring soon, refreshing...");let d=await $e.getAll();if(!d?.accessToken)throw new Error("Not logged in. Please run `entrydesk login` again.");let x=await sn(d);if(x!==t){t=x;try{await i.close()}catch{}i=await $s(s,t,o),We("[entrydesk-mcp] Token refreshed, reconnected")}return i})().finally(()=>{r=null}),r):i,c=async()=>{try{await i.close()}catch{}};if(e.mode==="http"){let d=e.port||n.httpPort;await li(a,c,d)}else We("[entrydesk-mcp] Starting stdio server..."),await ci(a,c),We("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Is(e){try{let t,o;try{let i=await fe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new G,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
403
+ `);for(let i of n)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){ke(t)}}function ui(){console.log(`
403
404
  Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
404
405
 
405
406
  Commands:
@@ -414,7 +415,7 @@ Commands:
414
415
 
415
416
  Flags:
416
417
  --json Output JSON
417
- `)}function Wt(e,t){if(e)return e;if(t&&G.getProfileCount()===1)return G.getProfileNames()[0];throw new Nt("Profile name is required when multiple profiles exist.")}function yi(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function vs(e){try{let t=e.action||"list",n=G.getCurrentProfileName(),s=e.name??e.profile,o=e.value;if(e.help||t==="help"){hi();return}if(t==="list"){let i=G.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:n,profiles:i.map(r=>({name:r,isCurrent:r===n}))}));return}console.log(`Profiles (${i.length}):`);for(let r of i)console.log(` ${r}${r===n?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:n,isCurrent:!0}));return}console.log(`Current profile: ${n}`);return}if(t==="show"){let i=Wt(s,!0),r=oe.getAll(i),a=await Te.getAll(i),c=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:i,isCurrent:i===n,config:r,auth:c?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${i}${i===n?" (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: ${yi(r.capabilities)}`),console.log(c?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),c&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let i=s||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=Wt(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=Wt(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=Wt(s,!0);if(!o)throw new Nt("New profile name is required.");let r=G.renameProfile(i,o);if(e.json){console.log(JSON.stringify({renamed:i,name:o,currentProfile:r.currentProfile}));return}console.log(`Profile renamed: ${i} -> ${o}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="clone"||t==="copy"){let i=Wt(s,!0);if(!o)throw new Nt("Target profile name is required.");let r=oe.getAll(i);if(G.createProfile(o),oe.setAll(r,o),await Te.clear(o),e.json){console.log(JSON.stringify({source:i,name:o,cloned:!0}));return}console.log(`Profile cloned: ${i} -> ${o}`);return}throw new Nt(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Mt(){console.log(`
418
+ `)}function Bt(e,t){if(e)return e;if(t&&J.getProfileCount()===1)return J.getProfileNames()[0];throw new Et("Profile name is required when multiple profiles exist.")}function di(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function vs(e){try{let t=e.action||"list",o=J.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){ui();return}if(t==="list"){let i=J.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:i.map(r=>({name:r,isCurrent:r===o}))}));return}console.log(`Profiles (${i.length}):`);for(let r of i)console.log(` ${r}${r===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let i=Bt(s,!0),r=oe.getAll(i),a=await $e.getAll(i),c=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:i,isCurrent:i===o,config:r,auth:c?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${i}${i===o?" (current)":""}`),console.log(` API URL: ${r.apiUrl??"default"}`),console.log(` Hub URL: ${r.hubUrl??"default"}`),console.log(` Model: ${r.model?.default??"unset"}`);let d=r.connectors?.defaults&&r.connectors.defaults.length>0?r.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${di(r.capabilities)}`),console.log(c?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),c&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let i=s||J.DEFAULT_PROFILE;if(J.createProfile(i),e.json){console.log(JSON.stringify({name:i,created:!0}));return}console.log(`Profile created: ${i}`);return}if(t==="use"||t==="switch"){let i=Bt(s,!0);if(J.setCurrentProfile(i),e.json){console.log(JSON.stringify({name:i,current:!0}));return}console.log(`Switched to profile: ${i}`);return}if(t==="delete"||t==="remove"||t==="rm"){let i=Bt(s,!0),r=J.deleteProfile(i);if(e.json){console.log(JSON.stringify({deleted:i,currentProfile:r.currentProfile}));return}console.log(`Profile deleted: ${i}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let i=Bt(s,!0);if(!n)throw new Et("New profile name is required.");let r=J.renameProfile(i,n);if(e.json){console.log(JSON.stringify({renamed:i,name:n,currentProfile:r.currentProfile}));return}console.log(`Profile renamed: ${i} -> ${n}`),console.log(`Current profile: ${r.currentProfile}`);return}if(t==="clone"||t==="copy"){let i=Bt(s,!0);if(!n)throw new Et("Target profile name is required.");let r=oe.getAll(i);if(J.createProfile(n),oe.setAll(r,n),await $e.clear(n),e.json){console.log(JSON.stringify({source:i,name:n,cloned:!0}));return}console.log(`Profile cloned: ${i} -> ${n}`);return}throw new Et(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Jt(){console.log(`
418
419
  Usage: entrydesk schedules [list|get|create|delete] [options]
419
420
 
420
421
  Commands:
@@ -440,7 +441,7 @@ Create Options:
440
441
 
441
442
  Flags:
442
443
  --json Output JSON
443
- `)}function Is(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 n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(o=>n[o]).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 n=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 ${n} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Jt(e,t){let n=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return n.toISOString();let o=s[1]==="+"?1:-1,i=parseInt(s[2],10),r=parseInt(s[3],10),a=o*(i*60+r)*60*1e3;return`${new Date(n.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function wi(e){console.log(`
444
+ `)}function As(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Gt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,i=parseInt(s[2],10),r=parseInt(s[3],10),a=n*(i*60+r)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function fi(e){console.log(`
444
445
  Schedule: ${e.name}
445
446
  ${"\u2501".repeat(50)}
446
447
  ID: ${e.id}
@@ -452,13 +453,13 @@ Prompt:
452
453
  ${e.prompt.slice(0,200)}${e.prompt.length>200?"...":""}
453
454
 
454
455
  Schedule:
455
- ${Is(e.config)}
456
+ ${As(e.config)}
456
457
 
457
- Next Run: ${e.nextRunAt?Jt(e.nextRunAt,e.utcOffset):"-"}
458
- Created: ${Jt(e.createdAt,e.utcOffset)}
459
- Updated: ${Jt(e.updatedAt,e.utcOffset)}
460
- `)}function ki(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let n=e.every||1,s=e.time||"09:00",[o,i]=s.split(":"),r={hour:parseInt(o,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:n}};case"hours":return{type:"repeat",interval:{unit:"hours",every:n,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:n,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:n,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:n,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function As(e){try{if(e.help){Mt();return}let t=await fe(),{accessToken:n,workspaceId:s}=t,o=e.action||"list",i=new H;if(o==="get"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Mt(),process.exit(1));let d=await i.getSchedule(n,s,c);if(e.json){console.log(JSON.stringify(d));return}wi(d);return}if(o==="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"),Mt(),process.exit(1));let c={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:ki(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(n,s,c);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Jt(d.nextRunAt,d.utcOffset):"-"}`);return}if(o==="delete"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Mt(),process.exit(1)),await i.deleteSchedule(n,s,c),console.log(`Deleted schedule: ${c}`);return}o!=="list"&&(console.error(`Unknown schedules command: ${o}`),Mt(),process.exit(1));let r=[],a;do{let c=await i.getSchedules(n,s,{nextKey:a,limit:100});r.push(...c.schedules),a=c.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
461
- `);for(let c of r){let d=c.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${c.name}`),console.log(` Agent: ${c.agent.name}`),console.log(` Repeat: ${Is(c.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${c.nextRunAt?Jt(c.nextRunAt,c.utcOffset):"-"}`),console.log(` ID: ${c.id}`),console.log("")}}catch(t){ke(t)}}import bi from"fs";import vt from"fs/promises";import Ps from"os";import et from"path";import xi from"archiver";function wo(){console.log(`
458
+ Next Run: ${e.nextRunAt?Gt(e.nextRunAt,e.utcOffset):"-"}
459
+ Created: ${Gt(e.createdAt,e.utcOffset)}
460
+ Updated: ${Gt(e.updatedAt,e.utcOffset)}
461
+ `)}function pi(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function Ps(e){try{if(e.help){Jt();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new G;if(n==="get"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Jt(),process.exit(1));let d=await i.getSchedule(o,s,c);if(e.json){console.log(JSON.stringify(d));return}fi(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Jt(),process.exit(1));let c={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:pi(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(o,s,c);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Gt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Jt(),process.exit(1)),await i.deleteSchedule(o,s,c),console.log(`Deleted schedule: ${c}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Jt(),process.exit(1));let r=[],a;do{let c=await i.getSchedules(o,s,{nextKey:a,limit:100});r.push(...c.schedules),a=c.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
462
+ `);for(let c of r){let d=c.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${c.name}`),console.log(` Agent: ${c.agent.name}`),console.log(` Repeat: ${As(c.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${c.nextRunAt?Gt(c.nextRunAt,c.utcOffset):"-"}`),console.log(` ID: ${c.id}`),console.log("")}}catch(t){ke(t)}}import gi from"fs";import vt from"fs/promises";import Ns from"os";import tt from"path";import mi from"archiver";function ko(){console.log(`
462
463
  Usage: entrydesk skills [list|upload|delete|versions] [options]
463
464
 
464
465
  Commands:
@@ -472,17 +473,17 @@ Options:
472
473
  --me Only list skills created by me
473
474
  --force Overwrite an existing skill with the same name
474
475
  --json Output JSON (for list/upload/versions)
475
- `)}function Ci(e,t){let n=et.relative(e,t);return n===""||!n.startsWith("..")&&!et.isAbsolute(n)}async function $i(e){let t=await vt.realpath(e),n=[process.cwd(),Ps.homedir()];if(!(await Promise.all(n.map(async i=>{try{return await vt.realpath(i)}catch{return et.resolve(i)}}))).some(i=>Ci(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Si(e){let t=await vt.mkdtemp(et.join(Ps.tmpdir(),"entrydesk-skill-")),n=et.join(t,`${et.basename(e)}.zip`);return await new Promise((s,o)=>{let i=bi.createWriteStream(n),r=xi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",o),r.on("error",o),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:n,cleanupDir:t}}async function Ns(e){let t,n;try{let a=await fe();t=a.accessToken,n=a.workspaceId}catch(a){ke(a)}let s=e.action||"list",o=new H;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),wo(),process.exit(1));let c=et.resolve(a),d;try{d=await vt.stat(c)}catch{console.error(`File not found: ${c}`),process.exit(1)}let $=c,C=null;try{try{await $i(c)}catch(y){let k=y instanceof Error?y.message:"Invalid upload path.";console.error(k),process.exit(1)}if(d.isDirectory()){let y=await Si(c);$=y.zipPath,C=y.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${c}`),process.exit(1));et.extname($).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let x=await vt.readFile($),v=new FormData;v.append("file",new Blob([x],{type:"application/zip"}),et.basename($)),e.force&&v.append("force","true");let h;try{h=await o.uploadSkill(t,n,v)}catch(y){if(y instanceof Error&&y.name==="HTTPError"){let k=y;if(k.response&&k.response.status===409){try{(await k.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw y}if(e.json){console.log(JSON.stringify(h));return}console.log(`Uploaded skill: ${h.name}`),console.log(` ID: ${h.id}`),console.log(` Version ID: ${h.versionId}`),console.log(` Description: ${h.description}`);return}finally{C&&await vt.rm(C,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),wo(),process.exit(1)),await o.deleteSkill(t,n,a),console.log(`Deleted skill: ${a}`);return}if(s==="versions"){let a=e.configKey;a||(console.error("Missing skill name."),wo(),process.exit(1));let c=[],d;do{let x=await o.listAvailableSkills(t,n,{nextKey:d,limit:100});c.push(...x.skills),d=x.nextKey}while(d);let $=c.find(x=>x.name===a);$||(console.error(`Skill not found: ${a}`),process.exit(1));let C=await o.listSkillVersions(t,n,$.id);if(e.json){console.log(JSON.stringify(C));return}if(console.log(`Versions for skill "${C.skillName}":
476
- `),C.versions.length===0){console.log(" No versions found.");return}for(let x of C.versions){let v=new Date(x.createdAt);console.log(` ${v.toLocaleString()}`),console.log(` ID: ${x.id}`),console.log(` Description: ${x.description.slice(0,80)}`),console.log(` Created by: ${x.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),wo(),process.exit(1));let i=[],r;do{let a=await o.listAvailableSkills(t,n,{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}):
477
- `);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Es(e){try{let t=G.getEffectiveProfileName(),n=await Te.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!n){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 o;if(n.workspaceId)try{let i=new H,r=await at(),{workspaces:a}=await i.getWorkspaces(r);o=a.find(d=>d.id===n.workspaceId)?.name}catch(i){if(i instanceof ze){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:n.email,workspaceId:n.workspaceId,workspaceName:o,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${n.email}`),o&&console.log(`Workspace: ${o}`),n.workspaceId&&console.log(`Workspace ID: ${n.workspaceId}`))}catch(t){ke(t)}}import Ri from"fs";import{Client as Ti}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as vi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Ii(e={}){let t=e.apiUrl,n=e.accessToken,s=e.workspaceId;if(!n||!s){let a=await fe();n=n||a.accessToken,s=s||a.workspaceId}t||(t=qe().apiUrl);let o=new Ti({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new vi(i,{requestInit:{headers:{Authorization:`Bearer ${n}`}}});return await o.connect(r),o}async function ko(){return Ii()}import Yo from"fs/promises";import Ai from"os";import Gt from"path";var qo=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,It={green:qo?"\x1B[32m":"",yellow:qo?"\x1B[33m":"",reset:qo?"\x1B[0m":""},Pi=10*1024,_s=8*1024,Ds=2*1024,Ni=100,Ei=100;function _i(){return Gt.join(Ai.homedir(),".entrydesk","tool-results")}function Di(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Ni);return!t||t==="."||t===".."?"unnamed_tool":t}function Oi(e){try{return JSON.stringify(e,(t,n)=>typeof n=="bigint"?`${n}n`:typeof n=="function"?"[Function]":typeof n=="symbol"?n.toString():n,2)}catch{return String(e)}}function Li(e){let t=new Date,n=[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=Di(e);return`${n}_${s}.json`}async function Os(e,t){try{return await Yo.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="EEXIST")return!1;throw n}}async function Ls(e,t){try{let n=_i();await Yo.mkdir(n,{recursive:!0});let s=Li(e),o=Gt.extname(s),i=s.slice(0,-o.length),r=Oi(t),a=Gt.join(n,s);if(await Os(a,r))return a;for(let $=1;$<=Ei;$++){let C=Gt.join(n,`${i}-${$}${o}`);if(await Os(C,r))return C}let c=Math.random().toString(36).slice(2,10),d=Gt.join(n,`${i}-${c}${o}`);return await Yo.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(n){let s=n instanceof Error?n.message:"unknown error";return console.error(`${It.yellow}Warning: Could not save result to file: ${s}${It.reset}`),null}}function Rs(e,t){let n=Buffer.byteLength(e,"utf8");if(n<=Pi)return e;let s=e.slice(0,_s),o=e.slice(-Ds),r=((n-_s-Ds)/1024).toFixed(1),a=(n/1024).toFixed(1),c=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(c+=`
476
+ `)}function hi(e,t){let o=tt.relative(e,t);return o===""||!o.startsWith("..")&&!tt.isAbsolute(o)}async function yi(e){let t=await vt.realpath(e),o=[process.cwd(),Ns.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await vt.realpath(i)}catch{return tt.resolve(i)}}))).some(i=>hi(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function wi(e){let t=await vt.mkdtemp(tt.join(Ns.tmpdir(),"entrydesk-skill-")),o=tt.join(t,`${tt.basename(e)}.zip`);return await new Promise((s,n)=>{let i=gi.createWriteStream(o),r=mi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function Es(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){ke(a)}let s=e.action||"list",n=new G;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),ko(),process.exit(1));let c=tt.resolve(a),d;try{d=await vt.stat(c)}catch{console.error(`File not found: ${c}`),process.exit(1)}let x=c,C=null;try{try{await yi(c)}catch(y){let v=y instanceof Error?y.message:"Invalid upload path.";console.error(v),process.exit(1)}if(d.isDirectory()){let y=await wi(c);x=y.zipPath,C=y.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${c}`),process.exit(1));tt.extname(x).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await vt.readFile(x),T=new FormData;T.append("file",new Blob([b],{type:"application/zip"}),tt.basename(x)),e.force&&T.append("force","true");let h;try{h=await n.uploadSkill(t,o,T)}catch(y){if(y instanceof Error&&y.name==="HTTPError"){let v=y;if(v.response&&v.response.status===409){try{(await v.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw y}if(e.json){console.log(JSON.stringify(h));return}console.log(`Uploaded skill: ${h.name}`),console.log(` ID: ${h.id}`),console.log(` Version ID: ${h.versionId}`),console.log(` Description: ${h.description}`);return}finally{C&&await vt.rm(C,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),ko(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(s==="versions"){let a=e.configKey;a||(console.error("Missing skill name."),ko(),process.exit(1));let c=[],d;do{let b=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});c.push(...b.skills),d=b.nextKey}while(d);let x=c.find(b=>b.name===a);x||(console.error(`Skill not found: ${a}`),process.exit(1));let C=await n.listSkillVersions(t,o,x.id);if(e.json){console.log(JSON.stringify(C));return}if(console.log(`Versions for skill "${C.skillName}":
477
+ `),C.versions.length===0){console.log(" No versions found.");return}for(let b of C.versions){let T=new Date(b.createdAt);console.log(` ${T.toLocaleString()}`),console.log(` ID: ${b.id}`),console.log(` Description: ${b.description.slice(0,80)}`),console.log(` Created by: ${b.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),ko(),process.exit(1));let i=[],r;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:r,limit:100});i.push(...a.skills),r=a.nextKey}while(r);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${i.length}):
478
+ `);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function _s(e){try{let t=J.getEffectiveProfileName(),o=await $e.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let i=new G,r=await lt(),{workspaces:a}=await i.getWorkspaces(r);n=a.find(d=>d.id===o.workspaceId)?.name}catch(i){if(i instanceof qe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){ke(t)}}import Ni from"fs";import{Client as ki}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as bi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function xi(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Ye().apiUrl);let n=new ki({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new bi(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function bo(){return xi()}import Xo from"fs/promises";import Ci from"os";import Vt from"path";var Yo=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,At={green:Yo?"\x1B[32m":"",yellow:Yo?"\x1B[33m":"",reset:Yo?"\x1B[0m":""},$i=10*1024,Ds=8*1024,Os=2*1024,Si=100,Ti=100;function Ii(){return Vt.join(Ci.homedir(),".entrydesk","tool-results")}function vi(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Si);return!t||t==="."||t===".."?"unnamed_tool":t}function Ai(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Pi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=vi(e);return`${o}_${s}.json`}async function Ls(e,t){try{return await Xo.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function Rs(e,t){try{let o=Ii();await Xo.mkdir(o,{recursive:!0});let s=Pi(e),n=Vt.extname(s),i=s.slice(0,-n.length),r=Ai(t),a=Vt.join(o,s);if(await Ls(a,r))return a;for(let x=1;x<=Ti;x++){let C=Vt.join(o,`${i}-${x}${n}`);if(await Ls(C,r))return C}let c=Math.random().toString(36).slice(2,10),d=Vt.join(o,`${i}-${c}${n}`);return await Xo.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${At.yellow}Warning: Could not save result to file: ${s}${At.reset}`),null}}function Us(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=$i)return e;let s=e.slice(0,Ds),n=e.slice(-Os),r=((o-Ds-Os)/1024).toFixed(1),a=(o/1024).toFixed(1),c=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(c+=`
478
479
  Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
479
480
 
480
481
  ${c}
481
482
 
482
- ${o}`}function Us(e){console.log(`${It.green}Tool execution result saved to: ${e}${It.reset}`),console.log()}function js(){console.log(`${It.green}Tool execution result:${It.reset}`)}function Ui(e){return e.split("__")[0]??e}function pt(e,t,n){console.error(n?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function At(e,t,n="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?pt("AUTH_MISSING",s,t):pt(n,s,t)}async function ji(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],n=!1,s=!1,o=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",c),process.stdin.removeListener("error",d)},i=$=>{s||(s=!0,o(),e($))},r=setTimeout(()=>{n||i(null)},100),a=$=>{n=!0,clearTimeout(r),t.push($)},c=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",c),process.stdin.on("error",d),process.stdin.resume()})}var Ht=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Fi(e,t){if(e)return e;if(t)try{return Ri.readFileSync(t,"utf-8").trim()}catch(s){let o=s instanceof Error?s.message:"Failed to read input file";throw new Ht(`Failed to read input file: ${o}`)}let n=await ji();if(n)return n;throw new Ht("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Bi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
483
- `)}function Wi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
484
- `)}async function Mi(e,t){let n=await ko().catch(s=>{At(s,e)});try{let o=(await n.listTools()).tools;if(t){let i=t.toLowerCase();o=o.filter(r=>Ui(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(o,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${o.length})${i}:
485
- `);for(let r of o)console.log(Bi(r)),console.log()}}catch(s){At(s,e)}finally{await n.close().catch(()=>{})}}async function Ji(e,t){let n=await ko().catch(s=>{At(s,t)});try{let o=(await n.listTools()).tools.find(i=>i.name===e);o||pt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(o,null,2):Wi(o))}catch(s){At(s,t)}finally{await n.close().catch(()=>{})}}async function Gi(e,t,n){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";pt("INVALID_INPUT",a,n)}let o=await ko().catch(r=>{At(r,n,"TOOL_CALL_FAILED")}),i=!1;try{let r=await o.callTool({name:e,arguments:s});if(n)console.log(JSON.stringify(r,null,2));else{let a=await Ls(e,r);a&&Us(a),js();let c=r.content;for(let d of c)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),$=Rs(d,a);console.log($)}}r.isError&&(i=!0)}catch(r){At(r,n,"TOOL_CALL_FAILED")}finally{await o.close().catch(()=>{})}i&&process.exit(1)}async function Fs(e){let t=e.json??!1;switch(e.action){case"list":await Mi(t,e.prefix);break;case"get":e.name||pt("INVALID_INPUT","Tool name is required",t),await Ji(e.name,t);break;case"call":{e.name||pt("INVALID_INPUT","Tool name is required",t);let n;try{n=await Fi(e.input,e.inputFile)}catch(s){throw s instanceof Ht&&pt("INVALID_INPUT",s.message,t),s}await Gi(e.name,n,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
483
+ ${n}`}function js(e){console.log(`${At.green}Tool execution result saved to: ${e}${At.reset}`),console.log()}function Fs(){console.log(`${At.green}Tool execution result:${At.reset}`)}function Ei(e){return e.split("__")[0]??e}function gt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Pt(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?gt("AUTH_MISSING",s,t):gt(o,s,t)}async function _i(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",c),process.stdin.removeListener("error",d)},i=x=>{s||(s=!0,n(),e(x))},r=setTimeout(()=>{o||i(null)},100),a=x=>{o=!0,clearTimeout(r),t.push(x)},c=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",c),process.stdin.on("error",d),process.stdin.resume()})}var Ht=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Di(e,t){if(e)return e;if(t)try{return Ni.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Ht(`Failed to read input file: ${n}`)}let o=await _i();if(o)return o;throw new Ht("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Oi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
484
+ `)}function Li(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
485
+ `)}async function Ri(e,t){let o=await bo().catch(s=>{Pt(s,e)});try{let n=(await o.listTools()).tools;if(t){let i=t.toLowerCase();n=n.filter(r=>Ei(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(n,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${i}:
486
+ `);for(let r of n)console.log(Oi(r)),console.log()}}catch(s){Pt(s,e)}finally{await o.close().catch(()=>{})}}async function Ui(e,t){let o=await bo().catch(s=>{Pt(s,t)});try{let n=(await o.listTools()).tools.find(i=>i.name===e);n||gt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Li(n))}catch(s){Pt(s,t)}finally{await o.close().catch(()=>{})}}async function ji(e,t,o){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";gt("INVALID_INPUT",a,o)}let n=await bo().catch(r=>{Pt(r,o,"TOOL_CALL_FAILED")}),i=!1;try{let r=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(r,null,2));else{let a=await Rs(e,r);a&&js(a),Fs();let c=r.content;for(let d of c)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),x=Us(d,a);console.log(x)}}r.isError&&(i=!0)}catch(r){Pt(r,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}i&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ri(t,e.prefix);break;case"get":e.name||gt("INVALID_INPUT","Tool name is required",t),await Ui(e.name,t);break;case"call":{e.name||gt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Di(e.input,e.inputFile)}catch(s){throw s instanceof Ht&&gt("INVALID_INPUT",s.message,t),s}await ji(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
486
487
 
487
488
  Actions:
488
489
  list List all available tools
@@ -507,7 +508,7 @@ Examples:
507
508
  entrydesk tool call agent__search_agents --input '{"limit": 5}'
508
509
  entrydesk tool call agent__search_agents --input-file input.json
509
510
  echo '{"limit": 5}' | entrydesk tool call agent__search_agents
510
- `);break}}function Hi(){console.log(`
511
+ `);break}}function Fi(){console.log(`
511
512
  Usage: entrydesk usage [options]
512
513
 
513
514
  Options:
@@ -520,10 +521,10 @@ Examples:
520
521
  entrydesk usage --limit 10 # Show top 10 users
521
522
  entrydesk usage --sort-by operations # Sort by operation count
522
523
  entrydesk usage --json # JSON output
523
- `)}async function Bs(e){if(e.help){Hi();return}let t,n;try{let h=await fe();t=h.accessToken,n=h.workspaceId}catch(h){let y=h instanceof Error?h.message:"Authentication failed";console.error(y),process.exit(1)}let s=new H,o=[],i,r=0,a=100;do{let h=await s.getMonthlyUsages(t,n,{nextKey:i,limit:100});if(o.push(...h.monthlyUsages),i=h.nextKey,r++,r>=a){console.error(`Warning: Showing first ${o.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(o));return}if(o.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
524
- `);let c=0,d=0;for(let h of o)c+=parseFloat(h.totalCost),d+=h.operationCount;console.log(`Total Cost: $${c.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${o.length}
525
- `);let $=e.sortBy||"cost",C=[...o].toSorted((h,y)=>$==="cost"?parseFloat(y.totalCost)-parseFloat(h.totalCost):y.operationCount-h.operationCount),x=e.limit&&e.limit>0?e.limit:C.length,v=C.slice(0,x);console.log(`Usage by User (sorted by ${$}, showing ${v.length} of ${o.length}):
526
- `);for(let h of v){let y=parseFloat(h.totalCost);console.log(` ${h.user.name} (${h.user.email})`),console.log(` Cost: $${y.toFixed(2)}`),console.log(` Operations: ${h.operationCount.toLocaleString()}`),console.log("")}v.length<o.length&&console.log(`... and ${o.length-v.length} more users`)}function Xo(){console.log("entrydesk 1.8.2")}function Zo(){console.log(`
524
+ `)}async function Ms(e){if(e.help){Fi();return}let t,o;try{let h=await fe();t=h.accessToken,o=h.workspaceId}catch(h){let y=h instanceof Error?h.message:"Authentication failed";console.error(y),process.exit(1)}let s=new G,n=[],i,r=0,a=100;do{let h=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...h.monthlyUsages),i=h.nextKey,r++,r>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
525
+ `);let c=0,d=0;for(let h of n)c+=parseFloat(h.totalCost),d+=h.operationCount;console.log(`Total Cost: $${c.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
526
+ `);let x=e.sortBy||"cost",C=[...n].toSorted((h,y)=>x==="cost"?parseFloat(y.totalCost)-parseFloat(h.totalCost):y.operationCount-h.operationCount),b=e.limit&&e.limit>0?e.limit:C.length,T=C.slice(0,b);console.log(`Usage by User (sorted by ${x}, showing ${T.length} of ${n.length}):
527
+ `);for(let h of T){let y=parseFloat(h.totalCost);console.log(` ${h.user.name} (${h.user.email})`),console.log(` Cost: $${y.toFixed(2)}`),console.log(` Operations: ${h.operationCount.toLocaleString()}`),console.log("")}T.length<n.length&&console.log(`... and ${n.length-T.length} more users`)}function Zo(){console.log("entrydesk 1.8.4")}function Qo(){console.log(`
527
528
  Usage: entrydesk workspaces [list|switch|use] [options]
528
529
 
529
530
  Commands:
@@ -533,6 +534,6 @@ Commands:
533
534
 
534
535
  Flags:
535
536
  --json Output JSON
536
- `)}async function Ws(e){if(e.help){Zo();return}let t,s=(await Te.getAll())?.workspaceId;try{t=await at()}catch(a){let c=a instanceof Error?a.message:"Authentication failed";console.error(c),process.exit(1)}let o=e.action||"list",i=new H;if(o==="switch"||o==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),Zo(),process.exit(1));let{workspaces:c}=await i.getWorkspaces(t),d=c.find($=>$.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
537
- Available workspaces:`);for(let $ of c)console.error(` ${$.name}: ${$.id}`);process.exit(1)}if(await Te.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}o!=="list"&&(console.error(`Unknown workspaces command: ${o}`),Zo(),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}):
538
- `);for(let a of r){let c=a.id===s?" (current)":"";console.log(` ${a.name}${c}`),console.log(` ID: ${a.id}`),console.log("")}}function Ms(e,t,n=!1){let s={},o={};for(let i=n?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":break;case"chat":if(r==="-m"||r==="--message")o.message=e[++i];else if(r==="-a"||r==="--agent")o.agentId=e[++i];else if(r==="--model")o.model=e[++i];else if(r==="--connectors"){let a=e[++i];o.connectors=a?.split(",").map(c=>c.trim())}else r==="-i"||r==="--interactive"?o.interactive=!0:r==="--full-output"?o.fullOutput=!0:r==="-c"||r==="--continue"?o.continue=parseInt(e[++i],10):r==="--plain"?o.plain=!0:r==="--output"?o.output=e[++i]:r==="--sandbox"?o.sandbox=!0:r==="--no-sandbox"?o.noSandbox=!0:r==="--web-search"?o.webSearch=!0:r==="--image-gen"?o.imageGen=!0:r==="--chart"?o.chart=!0:r==="--file-system"?o.fileSystem=!0:r==="--no-file-system"&&(o.noFileSystem=!0);break;case"agents":if(r==="--name")o.name=e[++i];else if(r==="--description")o.description=e[++i];else if(r==="--system-prompt")o.systemPrompt=e[++i];else if(r==="--model-id")o.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];o.connectorIds=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];o.capabilities=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];o.conversationStarters=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];o.tools=a?.split(",").map(c=>c.trim()).filter(Boolean)}else r==="--icon-id"?o.iconId=e[++i]:r.startsWith("-")||(o.action?o.agentId=r:o.action=r);break;case"skills":r==="--force"?o.force=!0:r==="--me"||r==="--mine"?o.createdBy="me":r.startsWith("-")||(o.action?o.configKey=r:o.action=r);break;case"schedules":if(r==="--name")o.name=e[++i];else if(r==="--prompt")o.prompt=e[++i];else if(r==="--agent-id")o.agentId=e[++i];else if(r==="--starts-at")o.startsAt=e[++i];else if(r==="--utc-offset")o.utcOffset=e[++i];else if(r==="--repeat-type")o.repeatType=e[++i];else if(r==="--every")o.every=parseInt(e[++i],10);else if(r==="--time")o.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];o.daysOfWeek=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else if(r==="--days-of-month"){let a=e[++i];o.daysOfMonth=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else r==="--last-day-of-month"?o.lastDayOfMonth=!0:r.startsWith("-")||(o.action?o.scheduleId=r:o.action=r);break;case"config":!o.action&&!r.startsWith("-")?o.action=r:!o.configKey&&!r.startsWith("-")?o.configKey=r:!o.value&&!r.startsWith("-")&&(o.value=r);break;case"profile":!o.action&&!r.startsWith("-")?o.action=r:!o.name&&!r.startsWith("-")?o.name=r:!o.value&&!r.startsWith("-")&&(o.value=r);break;case"chats":r==="--share"||r==="-s"?o.shareId=e[++i]:r==="--full-output"?o.fullOutput=!0:r==="--output"?o.output=e[++i]:!o.chatId&&!r.startsWith("-")&&(o.chatId=r);break;case"budget":!o.action&&!r.startsWith("-")?o.action=r:!o.configKey&&!r.startsWith("-")&&(o.configKey=r);break;case"usage":if(r==="--limit")o.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(o.sortBy=a)}break;case"mcp-server":r==="--http"?o.http=!0:(r==="-p"||r==="--port")&&(o.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?o.input=e[++i]:r==="-f"||r==="--input-file"?o.inputFile=e[++i]:r==="-p"||r==="--prefix"?o.prefix=e[++i]:r.startsWith("-")||(o.action?o.name||(o.name=r):o.action=r);break;case"workspaces":!o.action&&!r.startsWith("-")&&(o.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...o};case"logout":return{command:"logout",...s,...o};case"status":return{command:"status",...s,...o};case"workspaces":return{command:"workspaces",...s,...o};case"agents":return{command:"agents",...s,...o};case"models":return{command:"models",...s,...o};case"connectors":return{command:"connectors",...s,...o};case"skills":return{command:"skills",...s,...o};case"schedules":return{command:"schedules",...s,...o};case"config":return{command:"config",...s,...o};case"profile":return{command:"profile",...s,...o};case"chat":return{command:"chat",...s,...o};case"chats":return{command:"chats",...s,...o};case"budget":return{command:"budget",...s,...o};case"usage":return{command:"usage",...s,...o};case"mcp-server":return{command:"mcp-server",...s,...o};case"tool":return{command:"tool",...s,...o};case"version":return{command:"version",...s,...o};default:return{command:"help",...s,...o}}}import{jsx as qi}from"react/jsx-runtime";var Be=process.argv.slice(2);(Be[0]==="--help"||Be[0]==="-h")&&(yo(),process.exit(0));(Be[0]==="--version"||Be[0]==="-v")&&(Xo(),process.exit(0));var Qo=!Be[0]||Be[0].startsWith("-"),Ki=Qo?"chat":Be[0],be=Ms(Be,Ki,Qo);Qo&&be.command==="chat"&&(be.interactive=!0);async function zi(){try{if(be.command!=="profile"){let e=be.profile||G.getCurrentProfileName();G.ensureProfileExists(e),G.setOverrideProfile(e)}switch(be.command){case"login":await xs(be);break;case"logout":await Cs(be);break;case"status":await Es(be);break;case"workspaces":await Ws(be);break;case"agents":await sn(be);break;case"models":await Ts(be);break;case"connectors":await ws(be);break;case"skills":await Ns(be);break;case"schedules":await As(be);break;case"chats":await ms(be);break;case"budget":await rn(be);break;case"usage":await Bs(be);break;case"config":be.action==="help"||Be[1]==="--help"?Vi(qi(ys,{})):await hs(be);break;case"profile":await vs(be);break;case"chat":Be[1]==="--help"||Be[1]==="-h"?yo():await cs(be);break;case"mcp-server":await Ss({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Fs(be);break;case"version":Xo();break;default:yo();break}}catch(e){ke(e)}}zi();
537
+ `)}async function Bs(e){if(e.help){Qo();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await lt()}catch(a){let c=a instanceof Error?a.message:"Authentication failed";console.error(c),process.exit(1)}let n=e.action||"list",i=new G;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),Qo(),process.exit(1));let{workspaces:c}=await i.getWorkspaces(t),d=c.find(x=>x.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
538
+ Available workspaces:`);for(let x of c)console.error(` ${x.name}: ${x.id}`);process.exit(1)}if(await $e.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),Qo(),process.exit(1));let{workspaces:r}=await i.getWorkspaces(t);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${r.length}):
539
+ `);for(let a of r){let c=a.id===s?" (current)":"";console.log(` ${a.name}${c}`),console.log(` ID: ${a.id}`),console.log("")}}function Js(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(c=>c.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(c=>c.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as Ji}from"react/jsx-runtime";var Me=process.argv.slice(2);(Me[0]==="--help"||Me[0]==="-h")&&(wo(),process.exit(0));(Me[0]==="--version"||Me[0]==="-v")&&(Zo(),process.exit(0));var en=!Me[0]||Me[0].startsWith("-"),Mi=en?"chat":Me[0],be=Js(Me,Mi,en);en&&be.command==="chat"&&(be.interactive=!0);async function Bi(){try{if(be.command!=="profile"){let e=be.profile||J.getCurrentProfileName();J.ensureProfileExists(e),J.setOverrideProfile(e)}switch(be.command){case"login":await xs(be);break;case"logout":await Cs(be);break;case"status":await _s(be);break;case"workspaces":await Bs(be);break;case"agents":await an(be);break;case"models":await Is(be);break;case"connectors":await bs(be);break;case"skills":await Es(be);break;case"schedules":await Ps(be);break;case"chats":await ys(be);break;case"budget":await ln(be);break;case"usage":await Ms(be);break;case"config":be.action==="help"||Me[1]==="--help"?Wi(Ji(ks,{})):await ws(be);break;case"profile":await vs(be);break;case"chat":Me[1]==="--help"||Me[1]==="-h"?wo():await ds(be);break;case"mcp-server":await Ts({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ws(be);break;case"version":Zo();break;default:wo();break}}catch(e){ke(e)}}Bi();