@entrydesk/cli 1.11.1 → 1.11.3

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 nn,b as sn,c as Se,d as Xe,e as rn,f as an,g as ct,h as fe,i as _t,j as ke,k as G,l as oe,m as Ze,r as V}from"./chunk-ZGVZBGOQ.js";import{render as Vi}from"ink";function To(){console.log(`
2
+ import{a as nn,b as rn,c as Se,d as Xe,e as sn,f as an,g as ct,h as fe,i as _t,j as ke,k as G,l as oe,m as Ze,r as V}from"./chunk-Q64GXVJE.js";import{render as Vi}from"ink";function To(){console.log(`
3
3
  Usage: entrydesk agents [list|create|update|delete] [options]
4
4
 
5
5
  Commands:
@@ -27,7 +27,7 @@ List Options:
27
27
  Flags:
28
28
  --json Output JSON
29
29
  `)}function cn(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function ln(e){console.log(`Available Agents (${e.length}):
30
- `);for(let t of e){if(console.log(` ${t.name} (${t.visibility})`),t.description){let o=t.description.length>80?`${t.description.slice(0,80)}...`:t.description;console.log(` ${o}`)}console.log(` ID: ${t.id}`),console.log("")}}function zs(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),To(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:cn(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function un(e){try{if(e.help){To();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new V;if(n==="create"){let l=zs(e),d=await r.createAgent(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created agent: ${d.name}`),console.log(` ID: ${d.id}`);return}if(n==="update"){let l=e.agentId;if(!l)throw new Error("Missing agentId for update command");let d=await r.getAgent(o,s,l),k={name:e.name??d.name,description:e.description??d.description,systemPrompt:e.systemPrompt??d.systemPrompt??"",modelId:e.modelId??d.model?.id??"",connectorIds:e.connectorIds??d.connectors?.map(C=>C.id)??[],capabilities:e.capabilities?cn(e.capabilities):d.capabilities??[],conversationStarters:e.conversationStarters??d.conversationStarters??[],tools:e.tools??d.tools??[],iconId:e.iconId??d.iconId};await r.updateAgent(o,s,l,k),console.log(`Updated agent: ${l}`);return}if(n==="delete"){let l=e.agentId;if(!l)throw new Error("Missing agentId for delete command");await r.deleteAgent(o,s,l),console.log(`Deleted agent: ${l}`);return}if(n!=="list"&&(console.error(`Unknown agents command: ${n}`),To(),process.exit(1)),e.all&&e.nextKey&&(console.error("Cannot use --all and --next-key together."),process.exit(1)),e.all){let d=[],k;for(let C=0;;C++){C>=100&&(console.error("Reached maximum page limit (100). Use --limit and --next-key for manual pagination."),process.exit(1));let $=await r.getAgents(o,s,{limit:e.limit??100,nextKey:k});if(d.push(...$.agents),k=$.nextKey,!k)break}if(e.json){console.log(JSON.stringify({agents:d}));return}if(d.length===0){console.log("No agents found in this workspace.");return}ln(d);return}let{agents:i,nextKey:a}=await r.getAgents(o,s,{limit:e.limit,nextKey:e.nextKey});if(e.json){console.log(JSON.stringify({agents:i,nextKey:a}));return}if(i.length===0){console.log("No agents found in this workspace.");return}ln(i),a&&console.log(`Next page: --next-key ${a}`)}catch(t){ke(t)}}function qs(){console.log(`
30
+ `);for(let t of e){if(console.log(` ${t.name} (${t.visibility})`),t.description){let o=t.description.length>80?`${t.description.slice(0,80)}...`:t.description;console.log(` ${o}`)}console.log(` ID: ${t.id}`),console.log("")}}function zr(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),To(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:cn(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function un(e){try{if(e.help){To();return}let t=await fe(),{accessToken:o,workspaceId:r}=t,n=e.action||"list",s=new V;if(n==="create"){let c=zr(e),d=await s.createAgent(o,r,c);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created agent: ${d.name}`),console.log(` ID: ${d.id}`);return}if(n==="update"){let c=e.agentId;if(!c)throw new Error("Missing agentId for update command");let d=await s.getAgent(o,r,c),k={name:e.name??d.name,description:e.description??d.description,systemPrompt:e.systemPrompt??d.systemPrompt??"",modelId:e.modelId??d.model?.id??"",connectorIds:e.connectorIds??d.connectors?.map(C=>C.id)??[],capabilities:e.capabilities?cn(e.capabilities):d.capabilities??[],conversationStarters:e.conversationStarters??d.conversationStarters??[],tools:e.tools??d.tools??[],iconId:e.iconId??d.iconId};await s.updateAgent(o,r,c,k),console.log(`Updated agent: ${c}`);return}if(n==="delete"){let c=e.agentId;if(!c)throw new Error("Missing agentId for delete command");await s.deleteAgent(o,r,c),console.log(`Deleted agent: ${c}`);return}if(n!=="list"&&(console.error(`Unknown agents command: ${n}`),To(),process.exit(1)),e.all&&e.nextKey&&(console.error("Cannot use --all and --next-key together."),process.exit(1)),e.all){let d=[],k;for(let C=0;;C++){C>=100&&(console.error("Reached maximum page limit (100). Use --limit and --next-key for manual pagination."),process.exit(1));let $=await s.getAgents(o,r,{limit:e.limit??100,nextKey:k});if(d.push(...$.agents),k=$.nextKey,!k)break}if(e.json){console.log(JSON.stringify({agents:d}));return}if(d.length===0){console.log("No agents found in this workspace.");return}ln(d);return}let{agents:i,nextKey:a}=await s.getAgents(o,r,{limit:e.limit,nextKey:e.nextKey});if(e.json){console.log(JSON.stringify({agents:i,nextKey:a}));return}if(i.length===0){console.log("No agents found in this workspace.");return}ln(i),a&&console.log(`Next page: --next-key ${a}`)}catch(t){ke(t)}}function qr(){console.log(`
31
31
  Usage: entrydesk budget [get|set|clear] [options]
32
32
 
33
33
  Commands:
@@ -37,7 +37,7 @@ Commands:
37
37
 
38
38
  Flags:
39
39
  --json Output JSON
40
- `)}async function dn(e){try{if(e.help){qs();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",r=new V;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await r.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await r.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let i=await r.getBudget(o,s);if(e.json){console.log(JSON.stringify(i));return}if(i.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${i.budget}`)}catch(t){ke(t)}}import{render as zr}from"ink";import{v4 as mo}from"uuid";import{exec as Ys}from"child_process";import Xs from"fs";import Qe from"fs/promises";import fn from"os";import Io from"path";import{promisify as Zs}from"util";import{glob as Qs}from"glob";var er=Zs(Ys),tr=`## Filesystem Tool Instructions
40
+ `)}async function dn(e){try{if(e.help){qr();return}let t=await fe(),{accessToken:o,workspaceId:r}=t,n=e.action||"get",s=new V;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 s.updateBudget(o,r,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await s.updateBudget(o,r,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let i=await s.getBudget(o,r);if(e.json){console.log(JSON.stringify(i));return}if(i.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${i.budget}`)}catch(t){ke(t)}}import{render as zs}from"ink";import{v4 as mo}from"uuid";import{exec as Yr}from"child_process";import Xr from"fs";import Qe from"fs/promises";import fn from"os";import Io from"path";import{promisify as Zr}from"util";import{glob as Qr}from"glob";var es=Zr(Yr),ts=`## Filesystem Tool Instructions
41
41
 
42
42
  You have access to filesystem tools that allow you to interact with the user's local filesystem.
43
43
 
@@ -62,23 +62,23 @@ You have access to filesystem tools that allow you to interact with the user's l
62
62
  - Execute Command has a default timeout of 30 seconds (max 5 minutes)
63
63
  - The current working directory is: ${process.cwd()}
64
64
  - The user's home directory is: ${fn.homedir()}
65
- `,or=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function pn(){return{name:"filesystem",systemPrompt:tr,tools:or}}function Ve(e){return e.startsWith("~/")?Io.join(fn.homedir(),e.slice(2)):e}function Qt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
65
+ `,os=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function pn(){return{name:"filesystem",systemPrompt:ts,tools:os}}function Ve(e){return e.startsWith("~/")?Io.join(fn.homedir(),e.slice(2)):e}function Qt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
66
66
 
67
- ... (truncated, ${e.length-t} more characters)`}async function mn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ve(t.path),s=await Qe.readFile(o,"utf-8");return{success:!0,result:Qt(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let r=Ve(n);try{let i=await Qe.readFile(r,"utf-8");s[n]=Qt(i,5e4)}catch(i){s[n]={error:i instanceof Error?i.message:String(i)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ve(t.path),s=t.content;return await Qe.mkdir(Io.dirname(o),{recursive:!0}),await Qe.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ve(t.path);return await Qe.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ve(t.path);return{success:!0,result:(await Qe.readdir(o,{withFileTypes:!0})).map(r=>({name:r.name,type:r.isDirectory()?"directory":r.isFile()?"file":r.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Ve(t.cwd):process.cwd(),n=await Qs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ve(t.path),s=await Qe.stat(o);return{success:!0,result:{path:o,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let o=Ve(t.source),s=Ve(t.destination);return await Qe.mkdir(Io.dirname(s),{recursive:!0}),await Qe.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Ve(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Xs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:r,stderr:i}=await er(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Qt(r,5e4),stderr:Qt(i,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function vo(e){return e.startsWith("filesystem__")}function gn(){return[pn()]}function eo(){return gn().flatMap(e=>e.tools)}function to(){return gn().map(e=>e.systemPrompt).filter(Boolean).join(`
67
+ ... (truncated, ${e.length-t} more characters)`}async function mn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ve(t.path),r=await Qe.readFile(o,"utf-8");return{success:!0,result:Qt(r)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),r={};for(let n of o){let s=Ve(n);try{let i=await Qe.readFile(s,"utf-8");r[n]=Qt(i,5e4)}catch(i){r[n]={error:i instanceof Error?i.message:String(i)}}}return{success:!0,result:r}}case"filesystem__write_file":{let o=Ve(t.path),r=t.content;return await Qe.mkdir(Io.dirname(o),{recursive:!0}),await Qe.writeFile(o,r,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ve(t.path);return await Qe.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ve(t.path);return{success:!0,result:(await Qe.readdir(o,{withFileTypes:!0})).map(s=>({name:s.name,type:s.isDirectory()?"directory":s.isFile()?"file":s.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,r=t.cwd?Ve(t.cwd):process.cwd(),n=await Qr(o,{cwd:r,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ve(t.path),r=await Qe.stat(o);return{success:!0,result:{path:o,type:r.isDirectory()?"directory":r.isFile()?"file":"other",size:r.size,created:r.birthtime.toISOString(),modified:r.mtime.toISOString(),accessed:r.atime.toISOString(),mode:r.mode.toString(8)}}}case"filesystem__move_file":{let o=Ve(t.source),r=Ve(t.destination);return await Qe.mkdir(Io.dirname(r),{recursive:!0}),await Qe.rename(o,r),{success:!0,result:{moved:{from:o,to:r}}}}case"filesystem__execute_command":{let o=t.command,r=t.cwd?Ve(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Xr.existsSync(r))return{success:!1,error:`Working directory does not exist: ${r}`};let{stdout:s,stderr:i}=await es(o,{cwd:r,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Qt(s,5e4),stderr:Qt(i,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function vo(e){return e.startsWith("filesystem__")}function gn(){return[pn()]}function eo(){return gn().flatMap(e=>e.tools)}function to(){return gn().map(e=>e.systemPrompt).filter(Boolean).join(`
68
68
 
69
- `)}function et(e){return vo(e)}async function oo(e,t){return vo(e)?mn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Ae,Text as H,useInput as Jo}from"ink";import Go from"ink-spinner";import{useCallback as Vo,useEffect as po,useRef as as,useState as Wr}from"react";import{Box as no,Text as Dt}from"ink";import{jsx as so,jsxs as Ot}from"react/jsx-runtime";function hn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function yn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:r,pageSize:i=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),k=Math.max(1,i),C=Math.floor(t/k)*k,$=Math.min(e.length,C+k),S=e.slice(C,$);return Ot(no,{flexDirection:"column",marginBottom:1,children:[so(Dt,{bold:!0,color:"cyan",children:r}),so(no,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:S.map((y,h)=>{let L=C+h===t,K=o?.has(y.id),F=hn(y.name,d),re=y.description?hn(y.description,Math.max(0,d-l)):"",Y=s?" ".repeat(l):"";return Ot(no,{paddingX:1,flexDirection:"column",children:[Ot(no,{children:[s&&so(Dt,{color:K?"green":"gray",children:K?"[\u2713] ":"[ ] "}),so(Dt,{backgroundColor:L?"cyan":void 0,color:L?"black":K?"green":"white",bold:!0,children:F})]}),re&&Ot(Dt,{dimColor:!0,children:[Y,"\xB7 ",re]})]},y.id)})}),Ot(Dt,{dimColor:!0,children:[s?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>k?` \xB7 Showing ${C+1}-${$} of ${e.length}`:""]})]})}import{Box as Ao,Text as Lt}from"ink";import{jsx as Rt,jsxs as Po}from"react/jsx-runtime";function wn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:Po(Ao,{flexDirection:"column",marginBottom:1,children:[Rt(Ao,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let r=n===t,i=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Po(Ao,{paddingX:1,children:[Po(Lt,{backgroundColor:r?"cyan":void 0,color:r?"black":"cyan",bold:r,children:["/",s.name]}),Rt(Lt,{dimColor:!0,children:i}),Rt(Lt,{children:" - "}),Rt(Lt,{color:r?"white":"gray",children:s.description})]},s.name)})}),Rt(Lt,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as nr,Text as kn,useInput as sr,useStdout as rr}from"ink";import{useCallback as xn,useEffect as bn,useMemo as No,useRef as Cn,useState as $n}from"react";import{jsx as Do}from"react/jsx-runtime";function ro(e,t){return e<0?0:e>t?t:e}function Eo(e){return Array.from(e)}function io(e){return/\s/.test(e)}function _o(e,t){let o=t;for(;o>0&&io(e[o-1]??"");)o-=1;for(;o>0&&!io(e[o-1]??"");)o-=1;return o}function Sn(e,t){let o=t;for(;o<e.length&&io(e[o]??"");)o+=1;for(;o<e.length&&!io(e[o]??"");)o+=1;return o}function ir(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((i,a)=>{if(i===`
70
- `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(i)}),t.push(s);let r=t.map(i=>i.length);return{lines:t,lineStarts:o,lineLengths:r}}function Tn(e,t,o){for(let n=0;n<t.length;n+=1){let r=t[n]??0,i=o[n]??0,a=r+i;if(e<=a)return{row:n,col:e-r}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ar=2;function In({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:r=0,multiline:i=!1}){let[a,l]=$n(()=>Eo(e).length),d=Cn(null),[k,C]=$n(0),$=Cn(null),{stdout:S}=rr(),y=No(()=>Eo(e),[e]),{lines:h,lineStarts:b,lineLengths:L}=No(()=>ir(y),[y]),{row:K,col:F}=No(()=>Tn(a,b,L),[a,b,L]),re=Math.max(1,(S?.columns??80)-r);bn(()=>{d.current!==e?(l(y.length),$.current=null):l(j=>ro(j,y.length)),d.current=e},[e,y.length]),bn(()=>{C(j=>{let A=j;F<A?A=F:F>=A+re&&(A=F-re+1);let N=L[K]??0,R=F===N?N+1:N,M=Math.max(0,R-re);return A>M&&(A=M),A<0&&(A=0),A})},[re,F,K,L]);let Y=xn((j,A)=>{d.current=j,t(j),l(A),$.current=null},[t]),$e=xn(async(j,A)=>{if(!n)return;let{row:N,col:R}=Tn(a,b,L),M=h[N]??[],E=L[N]??0,ge=h.length>1;if(i&&(A.meta&&A.return||A.ctrl&&j==="j"||A.shift&&A.return)){let _=[...y.slice(0,a),`
71
- `,...y.slice(a)].join("");Y(_,a+1);return}if(A.return){o(e);return}if(A.leftArrow){A.ctrl||A.meta?(R===0&&N>0?l(b[N]-1):l(b[N]+_o(M,R)),$.current=null):(R===0&&N>0?l(b[N]-1):l(_=>ro(_-1,y.length)),$.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(R>=E&&N<h.length-1?l(b[N+1]):l(b[N]+Sn(M,R)),$.current=null):(R>=E&&N<h.length-1?l(b[N+1]):l(_=>ro(_+1,y.length)),$.current=null);return}if(i&&ge&&A.upArrow){let _=$.current??R,p=Math.max(0,N-1),ie=Math.min(_,L[p]??0);l((b[p]??0)+ie),$.current=_;return}if(i&&ge&&A.downArrow){let _=$.current??R,p=Math.min(h.length-1,N+1),ie=Math.min(_,L[p]??0);l((b[p]??0)+ie),$.current=_;return}if(A.ctrl){if(j==="a"){l(b[N]??0),$.current=null;return}if(j==="e"){l((b[N]??0)+E),$.current=null;return}if(j==="u"){if(R>0){let _=b[N]??0,p=[...y.slice(0,_),...y.slice(a)].join("");Y(p,_)}return}if(j==="k"){if(R<E){let _=(b[N]??0)+E,p=[...y.slice(0,a),...y.slice(_)].join("");Y(p,a)}return}if(j==="w"){if(R===0&&N>0){let p=[...y.slice(0,a-1),...y.slice(a)].join("");Y(p,a-1);return}let _=_o(M,R);if(_!==R){let p=(b[N]??0)+_,ie=[...y.slice(0,p),...y.slice(a)].join("");Y(ie,p)}return}if(j==="d"){if(a<y.length){let _=[...y.slice(0,a),...y.slice(a+1)].join("");Y(_,a)}return}return}if(A.meta){j==="b"?(R===0&&N>0?l(b[N]-1):l(b[N]+_o(M,R)),$.current=null):j==="f"&&(R>=E&&N<h.length-1?l(b[N+1]):l(b[N]+Sn(M,R)),$.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let _=[...y.slice(0,a-1),...y.slice(a)].join("");Y(_,a-1);return}if(!(A.tab||A.escape)&&j.length>0){let _=i?j.replace(/\r\n/g,`
69
+ `)}function et(e){return vo(e)}async function oo(e,t){return vo(e)?mn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as H,useInput as Jo}from"ink";import Go from"ink-spinner";import{useCallback as Vo,useEffect as po,useRef as ar,useState as Bs}from"react";import{Box as no,Text as Dt}from"ink";import{jsx as ro,jsxs as Ot}from"react/jsx-runtime";function hn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function yn({items:e,activeIndex:t,selectedIds:o,multiSelect:r=!1,visible:n,title:s,pageSize:i=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,c=r?4:0,d=Math.max(20,a-2-2-c),k=Math.max(1,i),C=Math.floor(t/k)*k,$=Math.min(e.length,C+k),S=e.slice(C,$);return Ot(no,{flexDirection:"column",marginBottom:1,children:[ro(Dt,{bold:!0,color:"cyan",children:s}),ro(no,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:S.map((y,h)=>{let L=C+h===t,K=o?.has(y.id),j=hn(y.name,d),se=y.description?hn(y.description,Math.max(0,d-c)):"",Y=r?" ".repeat(c):"";return Ot(no,{paddingX:1,flexDirection:"column",children:[Ot(no,{children:[r&&ro(Dt,{color:K?"green":"gray",children:K?"[\u2713] ":"[ ] "}),ro(Dt,{backgroundColor:L?"cyan":void 0,color:L?"black":K?"green":"white",bold:!0,children:j})]}),se&&Ot(Dt,{dimColor:!0,children:[Y,"\xB7 ",se]})]},y.id)})}),Ot(Dt,{dimColor:!0,children:[r?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>k?` \xB7 Showing ${C+1}-${$} of ${e.length}`:""]})]})}import{Box as Po,Text as Lt}from"ink";import{jsx as Rt,jsxs as Ao}from"react/jsx-runtime";function wn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:Ao(Po,{flexDirection:"column",marginBottom:1,children:[Rt(Po,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((r,n)=>{let s=n===t,i=r.aliases.length>0?` (${r.aliases.join(", ")})`:"";return Ao(Po,{paddingX:1,children:[Ao(Lt,{backgroundColor:s?"cyan":void 0,color:s?"black":"cyan",bold:s,children:["/",r.name]}),Rt(Lt,{dimColor:!0,children:i}),Rt(Lt,{children:" - "}),Rt(Lt,{color:s?"white":"gray",children:r.description})]},r.name)})}),Rt(Lt,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as ns,Text as kn,useInput as rs,useStdout as ss}from"ink";import{useCallback as xn,useEffect as bn,useMemo as No,useRef as Cn,useState as $n}from"react";import{jsx as Do}from"react/jsx-runtime";function so(e,t){return e<0?0:e>t?t:e}function Eo(e){return Array.from(e)}function io(e){return/\s/.test(e)}function _o(e,t){let o=t;for(;o>0&&io(e[o-1]??"");)o-=1;for(;o>0&&!io(e[o-1]??"");)o-=1;return o}function Sn(e,t){let o=t;for(;o<e.length&&io(e[o]??"");)o+=1;for(;o<e.length&&!io(e[o]??"");)o+=1;return o}function is(e){let t=[],o=[],r=[],n=0;o.push(0),e.forEach((i,a)=>{if(i===`
70
+ `){t.push(r),r=[],n=a+1,o.push(n);return}r.push(i)}),t.push(r);let s=t.map(i=>i.length);return{lines:t,lineStarts:o,lineLengths:s}}function Tn(e,t,o){for(let n=0;n<t.length;n+=1){let s=t[n]??0,i=o[n]??0,a=s+i;if(e<=a)return{row:n,col:e-s}}let r=Math.max(0,t.length-1);return{row:r,col:o[r]??0}}var as=2;function In({value:e,onChange:t,onSubmit:o,onPaste:r,focus:n=!0,leadingOffset:s=0,multiline:i=!1}){let[a,c]=$n(()=>Eo(e).length),d=Cn(null),[k,C]=$n(0),$=Cn(null),{stdout:S}=ss(),y=No(()=>Eo(e),[e]),{lines:h,lineStarts:b,lineLengths:L}=No(()=>is(y),[y]),{row:K,col:j}=No(()=>Tn(a,b,L),[a,b,L]),se=Math.max(1,(S?.columns??80)-s);bn(()=>{d.current!==e?(c(y.length),$.current=null):c(F=>so(F,y.length)),d.current=e},[e,y.length]),bn(()=>{C(F=>{let A=F;j<A?A=j:j>=A+se&&(A=j-se+1);let N=L[K]??0,R=j===N?N+1:N,W=Math.max(0,R-se);return A>W&&(A=W),A<0&&(A=0),A})},[se,j,K,L]);let Y=xn((F,A)=>{d.current=F,t(F),c(A),$.current=null},[t]),$e=xn(async(F,A)=>{if(!n)return;let{row:N,col:R}=Tn(a,b,L),W=h[N]??[],E=L[N]??0,ge=h.length>1;if(i&&(A.meta&&A.return||A.ctrl&&F==="j"||A.shift&&A.return)){let D=[...y.slice(0,a),`
71
+ `,...y.slice(a)].join("");Y(D,a+1);return}if(A.return){o(e);return}if(A.leftArrow){A.ctrl||A.meta?(R===0&&N>0?c(b[N]-1):c(b[N]+_o(W,R)),$.current=null):(R===0&&N>0?c(b[N]-1):c(D=>so(D-1,y.length)),$.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(R>=E&&N<h.length-1?c(b[N+1]):c(b[N]+Sn(W,R)),$.current=null):(R>=E&&N<h.length-1?c(b[N+1]):c(D=>so(D+1,y.length)),$.current=null);return}if(i&&ge&&A.upArrow){let D=$.current??R,p=Math.max(0,N-1),ie=Math.min(D,L[p]??0);c((b[p]??0)+ie),$.current=D;return}if(i&&ge&&A.downArrow){let D=$.current??R,p=Math.min(h.length-1,N+1),ie=Math.min(D,L[p]??0);c((b[p]??0)+ie),$.current=D;return}if(A.ctrl){if(F==="a"){c(b[N]??0),$.current=null;return}if(F==="e"){c((b[N]??0)+E),$.current=null;return}if(F==="u"){if(R>0){let D=b[N]??0,p=[...y.slice(0,D),...y.slice(a)].join("");Y(p,D)}return}if(F==="k"){if(R<E){let D=(b[N]??0)+E,p=[...y.slice(0,a),...y.slice(D)].join("");Y(p,a)}return}if(F==="w"){if(R===0&&N>0){let p=[...y.slice(0,a-1),...y.slice(a)].join("");Y(p,a-1);return}let D=_o(W,R);if(D!==R){let p=(b[N]??0)+D,ie=[...y.slice(0,p),...y.slice(a)].join("");Y(ie,p)}return}if(F==="d"){if(a<y.length){let D=[...y.slice(0,a),...y.slice(a+1)].join("");Y(D,a)}return}return}if(A.meta){F==="b"?(R===0&&N>0?c(b[N]-1):c(b[N]+_o(W,R)),$.current=null):F==="f"&&(R>=E&&N<h.length-1?c(b[N+1]):c(b[N]+Sn(W,R)),$.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let D=[...y.slice(0,a-1),...y.slice(a)].join("");Y(D,a-1);return}if(!(A.tab||A.escape)&&F.length>0){let D=i?F.replace(/\r\n/g,`
72
72
  `).replace(/\r/g,`
73
- `):j.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=ar||_.includes(`
74
- `))&&s){let z=!1,P={text:_,preventDefault:()=>{z=!0}};if(await Promise.resolve(s(P)),z)return}let ie=Eo(_),we=[...y.slice(0,a),...ie,...y.slice(a)].join("");Y(we,a+ie.length)}},[y,a,n,L,b,h,i,s,o,Y,e]);return sr($e,{isActive:n}),Do(nr,{flexDirection:"column",children:h.map((j,A)=>{let N=A===K,M=(N&&F===j.length?[...j," "]:j).slice(k,k+re),E=M.join("");if(!N)return Do(kn,{children:E||" "},A);let ge=ro(F-k,Math.max(0,M.length-1)),_=M.slice(0,ge).join(""),p=M[ge]??" ",ie=M.slice(ge+1).join(""),P=`${_}\x1B[7m${p}\x1B[27m${ie}`;return Do(kn,{children:P},A)})})}import{Box as He,Text as ut}from"ink";import Uo from"react";import{Text as je}from"ink";import lr from"react";import{Fragment as dr,jsx as Me,jsxs as Pn}from"react/jsx-runtime";var Oo=2,Lo=1,Ro=2,cr=1,vn=3,An=4,ur=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Me(je,{color:n,children:e});let r=[],i=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>i&&r.push(Me(je,{color:n,children:e.slice(i,l.index)},`t-${i}`));let d=l[0],k=null,C=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Oo*2)k=Me(je,{bold:!0,color:n,children:d.slice(Oo,-Oo)},C);else if(d.length>Lo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(l.index-1,l.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(l.index-2,l.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))k=Me(je,{italic:!0,color:n,children:d.slice(Lo,-Lo)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Ro*2)k=Me(je,{strikethrough:!0,color:n,children:d.slice(Ro,-Ro)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>cr){let $=d.match(/^(`+)(.+?)\1$/s);$&&$[2]&&(k=Me(je,{color:s,children:$[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let $=d.match(/\[(.*?)\]\((.*?)\)/);if($){let S=$[1],y=$[2];k=Pn(je,{color:n,children:[S,Pn(je,{color:o,children:[" (",y,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>vn+An-1?k=Me(je,{underline:!0,color:n,children:d.slice(vn,-An)},C):d.match(/^https?:\/\//)&&(k=Me(je,{color:o,children:d},C))}catch{k=null}r.push(k??Me(je,{color:n,children:d},C)),i=a.lastIndex}return i<e.length&&r.push(Me(je,{color:n,children:e.slice(i)},`t-${i}`)),Me(dr,{children:r.filter(d=>d!==null)})},Ut=lr.memo(ur);import{Fragment as wr,jsx as ye,jsxs as Dn}from"react/jsx-runtime";var fr=1,_n=1,pr=1,mr=1,gr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(He,{paddingLeft:_n,flexDirection:"column",children:ye(ut,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,r=/^([ \t]*)([-*+]) +(.*)/,i=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],k=!1,C=!0,$=[],S="";function y(h){h&&(d.push(h),C=!1)}return o.forEach((h,b)=>{let L=`line-${b}`;if(k){let A=h.match(n);A&&A[1].startsWith(S[0])&&A[1].length>=S.length?(y(ye(Nn,{content:$},L)),k=!1,$=[],S=""):$.push(h);return}let K=h.match(n),F=h.match(s),re=h.match(r),Y=h.match(i),$e=h.match(a),j=h.match(l);if(K)k=!0,S=K[1];else if($e)y(ye(He,{children:ye(ut,{dimColor:!0,children:"---"})},L));else if(F){let A=F[1].length,N=F[2],R=A<=2?"cyan":"blue";y(ye(He,{children:ye(ut,{color:R,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Ut,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},L))}else if(j){let A=j[1];y(ye(He,{paddingLeft:1,children:Dn(ut,{dimColor:!0,children:["> ",ye(Ut,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},L))}else if(re){let A=re[1],N=re[2],R=re[3];y(ye(En,{itemText:R,type:"ul",marker:N,leadingWhitespace:A},L))}else if(Y){let A=Y[1],N=Y[2],R=Y[3];y(ye(En,{itemText:R,type:"ol",marker:N,leadingWhitespace:A},L))}else h.trim().length===0?C||(d.push(ye(He,{height:fr},`spacer-${b}`)),C=!0):y(ye(He,{children:ye(ut,{wrap:"wrap",children:ye(Ut,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},L))}),k&&y(ye(Nn,{content:$},"line-eof")),ye(wr,{children:d})},hr=({content:e})=>{let t=e.join(`
75
- `);return ye(He,{paddingLeft:_n,flexDirection:"column",children:ye(ut,{color:"yellow",children:t})})},Nn=Uo.memo(hr),yr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,r=n.length,i=s.length;return Dn(He,{paddingLeft:i+pr,flexDirection:"row",children:[ye(He,{width:r,children:ye(ut,{children:n})}),ye(He,{flexGrow:mr,children:ye(ut,{wrap:"wrap",children:ye(Ut,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},En=Uo.memo(yr),jo=Uo.memo(gr);import{execFile as kr}from"child_process";import xr from"fs";import Ct from"fs/promises";import On from"os";import lo from"path";import{promisify as br}from"util";var ao=br(kr);async function Cr(){let e=lo.join(On.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
73
+ `):F.replace(/\r?\n/g,"");if(!D||(D=D.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!D))return;if((D.length>=as||D.includes(`
74
+ `))&&r){let z=!1,P={text:D,preventDefault:()=>{z=!0}};if(await Promise.resolve(r(P)),z)return}let ie=Eo(D),we=[...y.slice(0,a),...ie,...y.slice(a)].join("");Y(we,a+ie.length)}},[y,a,n,L,b,h,i,r,o,Y,e]);return rs($e,{isActive:n}),Do(ns,{flexDirection:"column",children:h.map((F,A)=>{let N=A===K,W=(N&&j===F.length?[...F," "]:F).slice(k,k+se),E=W.join("");if(!N)return Do(kn,{children:E||" "},A);let ge=so(j-k,Math.max(0,W.length-1)),D=W.slice(0,ge).join(""),p=W[ge]??" ",ie=W.slice(ge+1).join(""),P=`${D}\x1B[7m${p}\x1B[27m${ie}`;return Do(kn,{children:P},A)})})}import{Box as He,Text as ut}from"ink";import Uo from"react";import{Text as Fe}from"ink";import ls from"react";import{Fragment as ds,jsx as We,jsxs as An}from"react/jsx-runtime";var Oo=2,Lo=1,Ro=2,cs=1,vn=3,Pn=4,us=({text:e,defaultColor:t,linkColor:o,codeColor:r})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return We(Fe,{color:n,children:e});let s=[],i=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,c;for(;(c=a.exec(e))!==null;){c.index>i&&s.push(We(Fe,{color:n,children:e.slice(i,c.index)},`t-${i}`));let d=c[0],k=null,C=`m-${c.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Oo*2)k=We(Fe,{bold:!0,color:n,children:d.slice(Oo,-Oo)},C);else if(d.length>Lo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(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)))k=We(Fe,{italic:!0,color:n,children:d.slice(Lo,-Lo)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Ro*2)k=We(Fe,{strikethrough:!0,color:n,children:d.slice(Ro,-Ro)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>cs){let $=d.match(/^(`+)(.+?)\1$/s);$&&$[2]&&(k=We(Fe,{color:r,children:$[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let $=d.match(/\[(.*?)\]\((.*?)\)/);if($){let S=$[1],y=$[2];k=An(Fe,{color:n,children:[S,An(Fe,{color:o,children:[" (",y,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>vn+Pn-1?k=We(Fe,{underline:!0,color:n,children:d.slice(vn,-Pn)},C):d.match(/^https?:\/\//)&&(k=We(Fe,{color:o,children:d},C))}catch{k=null}s.push(k??We(Fe,{color:n,children:d},C)),i=a.lastIndex}return i<e.length&&s.push(We(Fe,{color:n,children:e.slice(i)},`t-${i}`)),We(ds,{children:s.filter(d=>d!==null)})},Ut=ls.memo(us);import{Fragment as ws,jsx as ye,jsxs as Dn}from"react/jsx-runtime";var fs=1,_n=1,ps=1,ms=1,gs=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(He,{paddingLeft:_n,flexDirection:"column",children:ye(ut,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),r=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,s=/^([ \t]*)([-*+]) +(.*)/,i=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,c=/^ *> ?(.*)/,d=[],k=!1,C=!0,$=[],S="";function y(h){h&&(d.push(h),C=!1)}return o.forEach((h,b)=>{let L=`line-${b}`;if(k){let A=h.match(n);A&&A[1].startsWith(S[0])&&A[1].length>=S.length?(y(ye(Nn,{content:$},L)),k=!1,$=[],S=""):$.push(h);return}let K=h.match(n),j=h.match(r),se=h.match(s),Y=h.match(i),$e=h.match(a),F=h.match(c);if(K)k=!0,S=K[1];else if($e)y(ye(He,{children:ye(ut,{dimColor:!0,children:"---"})},L));else if(j){let A=j[1].length,N=j[2],R=A<=2?"cyan":"blue";y(ye(He,{children:ye(ut,{color:R,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Ut,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},L))}else if(F){let A=F[1];y(ye(He,{paddingLeft:1,children:Dn(ut,{dimColor:!0,children:["> ",ye(Ut,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},L))}else if(se){let A=se[1],N=se[2],R=se[3];y(ye(En,{itemText:R,type:"ul",marker:N,leadingWhitespace:A},L))}else if(Y){let A=Y[1],N=Y[2],R=Y[3];y(ye(En,{itemText:R,type:"ol",marker:N,leadingWhitespace:A},L))}else h.trim().length===0?C||(d.push(ye(He,{height:fs},`spacer-${b}`)),C=!0):y(ye(He,{children:ye(ut,{wrap:"wrap",children:ye(Ut,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},L))}),k&&y(ye(Nn,{content:$},"line-eof")),ye(ws,{children:d})},hs=({content:e})=>{let t=e.join(`
75
+ `);return ye(He,{paddingLeft:_n,flexDirection:"column",children:ye(ut,{color:"yellow",children:t})})},Nn=Uo.memo(hs),ys=({itemText:e,type:t,marker:o,leadingWhitespace:r=""})=>{let n=t==="ol"?`${o}. `:`${o} `,s=n.length,i=r.length;return Dn(He,{paddingLeft:i+ps,flexDirection:"row",children:[ye(He,{width:s,children:ye(ut,{children:n})}),ye(He,{flexGrow:ms,children:ye(ut,{wrap:"wrap",children:ye(Ut,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},En=Uo.memo(ys),Fo=Uo.memo(gs);import{execFile as ks}from"child_process";import xs from"fs";import Ct from"fs/promises";import On from"os";import lo from"path";import{promisify as bs}from"util";var ao=bs(ks);async function Cs(){let e=lo.join(On.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
76
76
  set imageData to the clipboard as "PNGf"
77
77
  set fileRef to open for access POSIX file "${e}" with write permission
78
78
  set eof fileRef to 0
79
79
  write imageData to fileRef
80
80
  close access fileRef
81
- `;return await ao("osascript",["-e",t]),(await Ct.stat(e)).size===0?void 0:{buffer:await Ct.readFile(e),mime:"image/png"}}catch{return}finally{try{xr.existsSync(e)&&await Ct.unlink(e)}catch{}}}async function $r(){try{let e=`
81
+ `;return await ao("osascript",["-e",t]),(await Ct.stat(e)).size===0?void 0:{buffer:await Ct.readFile(e),mime:"image/png"}}catch{return}finally{try{xs.existsSync(e)&&await Ct.unlink(e)}catch{}}}async function $s(){try{let e=`
82
82
  Add-Type -AssemblyName System.Windows.Forms
83
83
  $img = [System.Windows.Forms.Clipboard]::GetImage()
84
84
  if ($img) {
@@ -86,44 +86,44 @@ You have access to filesystem tools that allow you to interact with the user's l
86
86
  $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
87
87
  [System.Convert]::ToBase64String($ms.ToArray())
88
88
  }
89
- `,{stdout:t}=await ao("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function Sr(){try{let{stdout:e}=await ao("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await ao("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function Ln(){let e=On.platform();if(e==="darwin")return Cr();if(e==="win32")return $r();if(e==="linux")return Sr()}var Tr=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Rn(e){let t=lo.extname(e).toLowerCase();return Tr.has(t)}function Ir(e){let t=lo.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function co(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function Un(e){let t=co(e);if(/^https?:\/\//.test(t))return!1;try{return await Ct.access(t),!0}catch{return!1}}async function jn(e){let t=co(e);try{if(!(await Ct.stat(t)).isFile())return;let s=await Ct.readFile(t),n=Ir(t),r=lo.basename(t);return{buffer:s,mimeType:n,filename:r}}catch{return}}var Fe="\x1B[2m",se="\x1B[0m",ve="\x1B[36m",$t="\x1B[32m",Fn="\x1B[31m",pt="\x1B[38;2;59;91;204m",Fo="\x1B[38;2;126;200;248m",Wo="\x1B[38;2;244;196;78m";import{useState as tt}from"react";import{v4 as Wn}from"uuid";function Mn(e,t){let[o,s]=tt({status:"loading"}),[n,r]=tt([]),[i,a]=tt(""),[l,d]=tt(()=>e||Wn()),[k,C]=tt(t),[$,S]=tt(!!e),[y,h]=tt(null),[b,L]=tt(""),[K,F]=tt(!1),re=$e=>{r(j=>[...j,{role:"system",content:$e}])};return{state:o,setState:s,messages:n,setMessages:r,input:i,setInput:a,chatId:l,setChatId:d,currentChatTitle:k,setCurrentChatTitle:C,hasPersistedChat:$,setHasPersistedChat:S,credentials:y,setCredentials:h,currentResponse:b,setCurrentResponse:L,fullOutput:K,setFullOutput:F,addSystemMessage:re,startNewChat:$e=>{let j=Wn();d(j),C(void 0),S(!1),r([]),$e&&re($e)}}}import{useEffect as vr,useState as Bn}from"react";function Jn(e){let[t,o]=Bn(null),[s,n]=Bn(!0);return vr(()=>{let r=!1;async function i(){try{let a=await fe();if(r)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(r)return;if(a instanceof Xe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),n(!1)}}return i(),()=>{r=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Ar,useState as jt}from"react";function Gn(e){let[t,o]=jt([]),[s,n]=jt([]),[r,i]=jt([]),[a,l]=jt([]),[d,k]=jt(!1);return Ar(()=>{if(!e)return;let C=!1;k(!0);async function $(){if(e)try{let S=new V,[y,h,b,L]=await Promise.all([S.getConnectors(e.accessToken,e.workspaceId),S.getModels(e.accessToken,e.workspaceId),S.getAgents(e.accessToken,e.workspaceId),S.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;o(y.connectors),n(h.models),i(b.agents),l(L.providers??[])}catch{}finally{C||k(!1)}}return $(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:r,modelProviders:a,loading:d}}import St from"fs";import Hn from"path";import{useCallback as Pr}from"react";import{v4 as Nr}from"uuid";function Vn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let r=n.stdout.trim();return t||r.length<=200?r:r.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
90
- `);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function mt(e,t=!1){let o=[];for(let s of e)if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="reasoning"&&s.text)t?o.push(`${Fe}[Thinking]
91
- ${s.text}${se}`):o.push(`${Fe}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${ve}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let r=JSON.stringify(s.args,null,t?2:void 0),i=t||r.length<=100?r:r.slice(0,100)+"...";n.push(`${Fe}\u2502 Args: ${i}${se}`)}s.result!==void 0?(n.push(`${$t}\u2502 Result: ${Vn(s.result,t)}${se}`),n.push(`${ve}\u2514\u2500 completed${se}`)):n.push(`${ve}\u2514\u2500${se}`),o.push(n.join(`
92
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),r=[];if(r.push(`${ve}\u250C\u2500 Tool: ${n}${se}`),s.input){let i=JSON.stringify(s.input,null,t?2:void 0),a=t||i.length<=100?i:i.slice(0,100)+"...";r.push(`${Fe}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(r.push(`${$t}\u2502 Output: ${Vn(s.output,t)}${se}`),r.push(`${ve}\u2514\u2500 completed${se}`)):s.state==="error"?r.push(`${ve}\u2514\u2500 failed${se}`):r.push(`${ve}\u2514\u2500${se}`),o.push(r.join(`
89
+ `,{stdout:t}=await ao("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let r=Buffer.from(o,"base64");return r.length===0?void 0:{buffer:r,mime:"image/png"}}catch{return}}async function Ss(){try{let{stdout:e}=await ao("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await ao("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function Ln(){let e=On.platform();if(e==="darwin")return Cs();if(e==="win32")return $s();if(e==="linux")return Ss()}var Ts=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Rn(e){let t=lo.extname(e).toLowerCase();return Ts.has(t)}function Is(e){let t=lo.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function co(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function Un(e){let t=co(e);if(/^https?:\/\//.test(t))return!1;try{return await Ct.access(t),!0}catch{return!1}}async function Fn(e){let t=co(e);try{if(!(await Ct.stat(t)).isFile())return;let r=await Ct.readFile(t),n=Is(t),s=lo.basename(t);return{buffer:r,mimeType:n,filename:s}}catch{return}}var je="\x1B[2m",re="\x1B[0m",ve="\x1B[36m",$t="\x1B[32m",jn="\x1B[31m",pt="\x1B[38;2;59;91;204m",jo="\x1B[38;2;126;200;248m",Bo="\x1B[38;2;244;196;78m";import{useState as tt}from"react";import{v4 as Bn}from"uuid";function Wn(e,t){let[o,r]=tt({status:"loading"}),[n,s]=tt([]),[i,a]=tt(""),[c,d]=tt(()=>e||Bn()),[k,C]=tt(t),[$,S]=tt(!!e),[y,h]=tt(null),[b,L]=tt(""),[K,j]=tt(!1),se=$e=>{s(F=>[...F,{role:"system",content:$e}])};return{state:o,setState:r,messages:n,setMessages:s,input:i,setInput:a,chatId:c,setChatId:d,currentChatTitle:k,setCurrentChatTitle:C,hasPersistedChat:$,setHasPersistedChat:S,credentials:y,setCredentials:h,currentResponse:b,setCurrentResponse:L,fullOutput:K,setFullOutput:j,addSystemMessage:se,startNewChat:$e=>{let F=Bn();d(F),C(void 0),S(!1),s([]),$e&&se($e)}}}import{useEffect as vs,useState as Mn}from"react";function Jn(e){let[t,o]=Mn(null),[r,n]=Mn(!0);return vs(()=>{let s=!1;async function i(){try{let a=await fe();if(s)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(s)return;if(a instanceof Xe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let c=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:c}),n(!1)}}return i(),()=>{s=!0}},[e]),{credentials:t,loading:r}}import{useEffect as Ps,useState as Ft}from"react";function Gn(e){let[t,o]=Ft([]),[r,n]=Ft([]),[s,i]=Ft([]),[a,c]=Ft([]),[d,k]=Ft(!1);return Ps(()=>{if(!e)return;let C=!1;k(!0);async function $(){if(e)try{let S=new V,[y,h,b,L]=await Promise.all([S.getConnectors(e.accessToken,e.workspaceId),S.getModels(e.accessToken,e.workspaceId),S.getAgents(e.accessToken,e.workspaceId),S.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;o(y.connectors),n(h.models),i(b.agents),c(L.providers??[])}catch{}finally{C||k(!1)}}return $(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:r,availableAgents:s,modelProviders:a,loading:d}}import St from"fs";import Hn from"path";import{useCallback as As}from"react";import{v4 as Ns}from"uuid";function Vn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let s=n.stdout.trim();return t||s.length<=200?s:s.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(s=>s.type==="text"&&s.text).map(s=>s.text).join(`
90
+ `);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let r=JSON.stringify(e,null,t?2:void 0);return t||r.length<=200?r:r.slice(0,200)+"..."}function mt(e,t=!1){let o=[];for(let r of e)if(r.type==="text"&&r.text)o.push(r.text);else if(r.type==="reasoning"&&r.text)t?o.push(`${je}[Thinking]
91
+ ${r.text}${re}`):o.push(`${je}[Thinking...]${re}`);else if(r.type==="tool-call"&&r.toolName){let n=[];if(n.push(`${ve}\u250C\u2500 Tool: ${r.toolName}${re}`),r.args){let s=JSON.stringify(r.args,null,t?2:void 0),i=t||s.length<=100?s:s.slice(0,100)+"...";n.push(`${je}\u2502 Args: ${i}${re}`)}r.result!==void 0?(n.push(`${$t}\u2502 Result: ${Vn(r.result,t)}${re}`),n.push(`${ve}\u2514\u2500 completed${re}`)):n.push(`${ve}\u2514\u2500${re}`),o.push(n.join(`
92
+ `))}else if(r.type.startsWith("tool-")&&r.type!=="tool-call"){let n=r.title||r.type.slice(5).replace(/__/g," "),s=[];if(s.push(`${ve}\u250C\u2500 Tool: ${n}${re}`),r.input){let i=JSON.stringify(r.input,null,t?2:void 0),a=t||i.length<=100?i:i.slice(0,100)+"...";s.push(`${je}\u2502 Input: ${a}${re}`)}r.output!==void 0&&r.state==="output-available"?(s.push(`${$t}\u2502 Output: ${Vn(r.output,t)}${re}`),s.push(`${ve}\u2514\u2500 completed${re}`)):r.state==="error"?s.push(`${ve}\u2514\u2500 failed${re}`):s.push(`${ve}\u2514\u2500${re}`),o.push(s.join(`
93
93
  `))}return o.join(`
94
94
 
95
- `).trim()}var uo=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let s=o.toolName.replace(/__/g," "),n=`
96
-
97
- ${ve}\u250C\u2500 Tool: ${s}${se}`;if(o.args){let r=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
98
- ${Fe}\u2502 Input: ${r}${se}`}if(o.output){let r=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
99
- ${$t}\u2502 Output: ${r}${se}`}else if(o.status==="executing"){let r=o.startedAt??Date.now(),i=Math.floor((Date.now()-r)/1e3);n+=`
100
- ${ve}\u2502${se} (executing... ${i}s)`}else o.status==="preparing"&&(n+=`
101
- ${ve}\u2502${se} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,s]of this.pendingToolCalls){let n=s.toolName.replace(/__/g," "),r=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"";t+=`
102
-
103
- ${ve}\u250C\u2500 Tool: ${n}${se}`,r&&(t+=`
104
- ${Fe}\u2502 Input: ${r}${se}`),t+=`
105
- ${ve}\u2514\u2500 completed${se}
106
- `,this.pendingToolCalls.delete(o)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.args=(o.args||"")+t.inputTextDelta,o.status="executing",o.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output="",o.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output=(o.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,o){if(!t.toolCallId)return null;let s=this.pendingToolCalls.get(t.toolCallId);if(!s)return null;let n=s.toolName.replace(/__/g," "),r=typeof s.args=="string"&&s.args.length>100?s.args.slice(0,100)+"...":s.args||"",i=(s.output||"").length>200?(s.output||"").slice(0,200)+"...":s.output||"";return o+=`
107
-
108
- ${ve}\u250C\u2500 Tool: ${n}${se}`,r&&(o+=`
109
- ${Fe}\u2502 Input: ${r}${se}`),o+=`
110
- ${$t}\u2502 Output: ${i}${se}`,o+=`
111
- ${ve}\u2514\u2500 completed${se}
112
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),r=t.errorText||"Unknown error",i=r.length>200?r.slice(0,200)+"...":r;return o+=`
113
-
114
- ${ve}\u250C\u2500 Tool: ${n}${se}`,o+=`
115
- ${Fn}\u2502 Error: ${i}${se}`,o+=`
116
- ${ve}\u2514\u2500 failed${se}
117
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Ft=Hn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
118
- DATA: ${JSON.stringify(t,null,2)}`),s+=`
119
- `;try{St.appendFileSync(Ft,s)}catch{}}function Er(){try{if(St.existsSync(Ft)&&St.unlinkSync(Ft),process.env.DEBUG){let e=Hn.dirname(Ft);St.existsSync(e)||St.mkdirSync(e,{recursive:!0}),St.writeFileSync(Ft,`=== Debug session started at ${new Date().toISOString()} ===
120
- `)}}catch{}}function fo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Kn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:r,webSearch:i,imageGeneration:a,chart:l,localTools:d,fullOutput:k,setMessages:C,setState:$,setCurrentResponse:S,setCredentials:y,setHasPersistedChat:h,getFileIds:b,clearFiles:L}){let K=d?eo():void 0,F=d?to():void 0;return{sendMessage:Pr(async(Y,$e,j)=>{Er(),ae("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:K?.length});let A=$e||t?.accessToken,N=j||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,y(E)}catch(E){if(E instanceof Xe){if(E.code==="not-logged-in"){$({status:"not-logged-in"});return}if(E.code==="no-workspace"){$({status:"no-workspace"});return}}let ge=E instanceof Error?E.message:"Authentication failed";$({status:"error",message:ge});return}else try{let E=await ct();E!==A&&(A=E,y({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof Xe&&E.code==="not-logged-in"){$({status:"not-logged-in"});return}let ge=E instanceof Error?E.message:"Authentication failed";$({status:"error",message:ge});return}C(E=>[...E,{role:"user",content:Y}]),$({status:"sending"}),S("");let R=null,M=null;try{let E=new V,ge=b?.()??[],_={id:e,message:{id:Nr(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};ge.length>0&&(_.fileIds=ge),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=r,_.enableWebSearch=i,_.enableImageGeneration=a,_.enableChart=l),K&&(_.clientTools=K),F&&(_.clientToolSystemPrompt=F);let p=await E.chat(A,N,_);if(!p.ok){let W=await p.text();throw new Error(`API error ${p.status}: ${W}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let ie=new TextDecoder,we="",z="",P="",ee="",Q="",pe="",le="",B=new uo,Z=[],q=[],de=[],Te=()=>{let W=B.hasExecuting();W&&!M?M=setInterval(()=>{if(!B.hasExecuting()){M&&(clearInterval(M),M=null);return}S(z+B.buildToolDisplay())},1e3):!W&&M&&(clearInterval(M),M=null)};for(;;){let{done:W,value:ne}=await R.read();if(W)break;we+=ie.decode(ne,{stream:!0});let O=we.split(`
121
- `);we=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",P="";break;case"reasoning-delta":w.delta&&(P+=w.delta,S(`${Fe}[Thinking...]${se}
122
- ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let T={type:"reasoning",id:ee,text:P,state:"done"};Q&&(T.providerMetadata={anthropic:{signature:Q}}),q.push(T),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",S("");break;case"text-delta":w.delta&&(B.hasPending()&&(z=B.flushPending(z)),z+=w.delta,pe+=w.delta,S(z));break;case"tool-input-start":{let T=B.handleToolInputStart(w);T&&S(z+T),Te();break}case"tool-input-delta":{let T=B.handleToolInputDelta(w);T&&S(z+T),Te();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?et(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let T=fo(w.args??w.input);q.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added tool to messageParts",{messagePartsCount:q.length})}if(d&&w.toolCallId&&w.toolName&&et(w.toolName)){let T=fo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),S(z+B.buildToolDisplay()+`
123
- [Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?et(w.toolName):!1});break}case"tool-output-start":{let T=B.handleToolOutputStart(w);T&&S(z+T),Te();break}case"tool-output-delta":{let T=B.handleToolOutputDelta(w);T&&S(z+T),Te();break}case"tool-output-end":{let T=B.handleToolOutputEnd(w,z);T&&(z=T.fullResponse,S(z+T.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let T=B.handleToolError(w,z);T&&(z=T.fullResponse,S(z+T.toolDisplay)),Te();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let W=q.findIndex(O=>O.type!=="reasoning"),ne=W===-1?q.length:W;q.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:q.length,messageParts:q.map(W=>({type:W.type,toolCallId:W.toolCallId,toolName:W.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let W=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),B.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),B.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),S(z+B.buildToolDisplay()),Te();let w=await oo(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let T=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(W.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:T}],isError:!w.success}),w.success){B.handleToolOutputStart({toolCallId:f.toolCallId}),B.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=B.handleToolOutputEnd({toolCallId:f.toolCallId},z);te&&(z=te.fullResponse)}else{let te=B.handleToolError({toolCallId:f.toolCallId,errorText:w.error},z);te&&(z=te.fullResponse)}S(z+B.buildToolDisplay()),Te()}Z.length=0;for(let f of W){let w=q.find(T=>(T.type==="tool-input-available"||T.type==="tool-call")&&T.toolCallId===f.toolCallId);if(w){let T=[];for(let U of f.content)U.type==="text"?T.push(U.text):U.type==="image"?T.push("[Image]"):U.type==="audio"?T.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&T.push("[Resource]");let te=T.join(`
124
- `);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount:W.length,toolResults:W.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let ne={id:e,clientToolResults:W};o?ne.agentId=o:(s&&(ne.model=s),ne.connectorIds=n??[],ne.enableSandbox=r,ne.enableWebSearch=i,ne.enableImageGeneration=a,ne.enableChart=l),K&&(ne.clientTools=K),F&&(ne.clientToolSystemPrompt=F),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:W.length});let O=await E.chat(A,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),R=O.body.getReader(),q.length=0,pe="",P="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}we+=ie.decode(w,{stream:!0});let T=we.split(`
125
- `);we=T.pop()||"";for(let te of T)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let U=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":ee=U.id||"0",P="";break;case"reasoning-delta":U.delta&&(P+=U.delta,S(`${Fe}[Thinking...]${se}
126
- ${P}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let be={type:"reasoning",id:ee,text:P,state:"done"};Q&&(be.providerMetadata={anthropic:{signature:Q}}),q.push(be),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",S(z);break;case"text-delta":U.delta&&(z+=U.delta,pe+=U.delta,S(z));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let be=fo(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:be})}if(d&&U.toolCallId&&U.toolName&&et(U.toolName)){let be=fo(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:be}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(T=>T.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:z.length})}if(d&&K&&K.length>0){let W=[];for(let O of de)W.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of q)O.type==="text"&&O.text&&W.push({type:"text",text:O.text});let ne=mt(W,k);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(O=>O.type==="text").length,contentLength:ne.length}),C(O=>[...O,{role:"assistant",content:ne,parts:W}])}else{ae("=== Fetching message from API ===",{fullResponseLength:z.length,fullResponsePreview:z.slice(0,200)});try{let{messages:W}=await E.getMessages(A,N,e,10);ae("=== API messages received ===",{count:W.length,roles:W.map(O=>O.role)});let ne=W.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=mt(O,k);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),C(O=>[...O,{role:"assistant",content:z}])}catch(W){ae("=== API fetch failed, using fallback ===",{error:W instanceof Error?W.message:String(W)}),C(ne=>[...ne,{role:"assistant",content:z}])}}ae("=== Message handling complete ==="),S(""),$({status:"ready"}),h(!0),ge.length>0&&L?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let ge=E instanceof Error?E.message:"Failed to send message";$({status:"error",message:ge})}finally{if(M&&(clearInterval(M),M=null),R)try{R.releaseLock()}catch{}}},[t,e,o,s,n,r,i,a,l,d,K,F,k,C,$,S,y,h,b,L])}}import{useState as Wt}from"react";var zn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},qn=new Map(Object.values(zn).map(e=>[e.apiKey,e.name]));function Yn(){return Object.values(zn)}function Xn(e,t,o,s,n){let[r,i]=Wt(e),[a,l]=Wt(t),[d,k]=Wt(o),[C,$]=Wt(s),[S,y]=Wt(n);return{sandbox:r,setSandbox:i,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:k,chart:C,setChart:$,fileSystem:S,setFileSystem:y,capabilityLabelMap:qn}}import{useEffect as _r,useState as Dr}from"react";function Zn(e,t){let[o,s]=Dr(null);return _r(()=>{let n=!1;async function r(){if(!e||!t){s(null);return}try{let a=await new V().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return r(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Mo}from"react";function Qn(e,t,o){let[s,n]=Mo(e),[r,i]=Mo(t),[a,l]=Mo(o);return{currentModel:s,setCurrentModel:n,currentAgentId:r,setCurrentAgentId:i,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Lr,useInput as Rr}from"ink";import{useCallback as ot,useRef as Ur,useState as De}from"react";import{spawn as Or}from"child_process";function es(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let r=Or(s,n,{stdio:"ignore",detached:!0});r.once("error",i=>{o(i)}),r.once("spawn",()=>{r.unref(),t()})})}var ts=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function os(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?ts.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):ts}function ns(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(s){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"chats":case"c":return{type:"chats"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:t}}}var ss=`Available commands:
95
+ `).trim()}var uo=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let r=o.toolName.replace(/__/g," "),n=`
96
+
97
+ ${ve}\u250C\u2500 Tool: ${r}${re}`;if(o.args){let s=o.args.length>100?o.args.slice(0,100)+"...":o.args;n+=`
98
+ ${je}\u2502 Input: ${s}${re}`}if(o.output){let s=o.output.length>150?o.output.slice(0,150)+"...":o.output;n+=`
99
+ ${$t}\u2502 Output: ${s}${re}`}else if(o.status==="executing"){let s=o.startedAt??Date.now(),i=Math.floor((Date.now()-s)/1e3);n+=`
100
+ ${ve}\u2502${re} (executing... ${i}s)`}else o.status==="preparing"&&(n+=`
101
+ ${ve}\u2502${re} (preparing...)`);t.push(n)}return t.join("")}flushPending(t){if(this.pendingToolCalls.size===0)return t;for(let[o,r]of this.pendingToolCalls){let n=r.toolName.replace(/__/g," "),s=typeof r.args=="string"&&r.args.length>100?r.args.slice(0,100)+"...":r.args||"";t+=`
102
+
103
+ ${ve}\u250C\u2500 Tool: ${n}${re}`,s&&(t+=`
104
+ ${je}\u2502 Input: ${s}${re}`),t+=`
105
+ ${ve}\u2514\u2500 completed${re}
106
+ `,this.pendingToolCalls.delete(o)}return t}handleToolInputStart(t){return t.toolCallId&&t.toolName?(this.pendingToolCalls.set(t.toolCallId,{toolName:t.toolName,args:"",status:"preparing"}),this.buildToolDisplay()):null}handleToolInputDelta(t){if(t.toolCallId&&t.inputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.args=(o.args||"")+t.inputTextDelta,o.status="executing",o.startedAt??=Date.now(),this.buildToolDisplay()}return null}handleToolOutputStart(t){if(t.toolCallId){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output="",o.status="output",this.buildToolDisplay()}return null}handleToolOutputDelta(t){if(t.toolCallId&&t.outputTextDelta){let o=this.pendingToolCalls.get(t.toolCallId);if(o)return o.output=(o.output||"")+t.outputTextDelta,this.buildToolDisplay()}return null}handleToolOutputEnd(t,o){if(!t.toolCallId)return null;let r=this.pendingToolCalls.get(t.toolCallId);if(!r)return null;let n=r.toolName.replace(/__/g," "),s=typeof r.args=="string"&&r.args.length>100?r.args.slice(0,100)+"...":r.args||"",i=(r.output||"").length>200?(r.output||"").slice(0,200)+"...":r.output||"";return o+=`
107
+
108
+ ${ve}\u250C\u2500 Tool: ${n}${re}`,s&&(o+=`
109
+ ${je}\u2502 Input: ${s}${re}`),o+=`
110
+ ${$t}\u2502 Output: ${i}${re}`,o+=`
111
+ ${ve}\u2514\u2500 completed${re}
112
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),s=t.errorText||"Unknown error",i=s.length>200?s.slice(0,200)+"...":s;return o+=`
113
+
114
+ ${ve}\u250C\u2500 Tool: ${n}${re}`,o+=`
115
+ ${jn}\u2502 Error: ${i}${re}`,o+=`
116
+ ${ve}\u2514\u2500 failed${re}
117
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var jt=Hn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let r=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(r+=`
118
+ DATA: ${JSON.stringify(t,null,2)}`),r+=`
119
+ `;try{St.appendFileSync(jt,r)}catch{}}function Es(){try{if(St.existsSync(jt)&&St.unlinkSync(jt),process.env.DEBUG){let e=Hn.dirname(jt);St.existsSync(e)||St.mkdirSync(e,{recursive:!0}),St.writeFileSync(jt,`=== Debug session started at ${new Date().toISOString()} ===
120
+ `)}}catch{}}function fo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Kn({chatId:e,credentials:t,currentAgentId:o,currentModel:r,activeConnectorIds:n,sandbox:s,webSearch:i,imageGeneration:a,chart:c,localTools:d,fullOutput:k,setMessages:C,setState:$,setCurrentResponse:S,setCredentials:y,setHasPersistedChat:h,getFileIds:b,clearFiles:L}){let K=d?eo():void 0,j=d?to():void 0;return{sendMessage:As(async(Y,$e,F)=>{Es(),ae("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:K?.length});let A=$e||t?.accessToken,N=F||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,y(E)}catch(E){if(E instanceof Xe){if(E.code==="not-logged-in"){$({status:"not-logged-in"});return}if(E.code==="no-workspace"){$({status:"no-workspace"});return}}let ge=E instanceof Error?E.message:"Authentication failed";$({status:"error",message:ge});return}else try{let E=await ct();E!==A&&(A=E,y({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof Xe&&E.code==="not-logged-in"){$({status:"not-logged-in"});return}let ge=E instanceof Error?E.message:"Authentication failed";$({status:"error",message:ge});return}C(E=>[...E,{role:"user",content:Y}]),$({status:"sending"}),S("");let R=null,W=null;try{let E=new V,ge=b?.()??[],D={id:e,message:{id:Ns(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};ge.length>0&&(D.fileIds=ge),o?D.agentId=o:(r&&(D.model=r),D.connectorIds=n??[],D.enableSandbox=s,D.enableWebSearch=i,D.enableImageGeneration=a,D.enableChart=c),K&&(D.clientTools=K),j&&(D.clientToolSystemPrompt=j);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 ie=new TextDecoder,we="",z="",P="",ee="",Q="",pe="",le="",M=new uo,Z=[],q=[],de=[],Te=()=>{let B=M.hasExecuting();B&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}S(z+M.buildToolDisplay())},1e3):!B&&W&&(clearInterval(W),W=null)};for(;;){let{done:B,value:ne}=await R.read();if(B)break;we+=ie.decode(ne,{stream:!0});let O=we.split(`
121
+ `);we=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",P="";break;case"reasoning-delta":w.delta&&(P+=w.delta,S(`${je}[Thinking...]${re}
122
+ ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let T={type:"reasoning",id:ee,text:P,state:"done"};Q&&(T.providerMetadata={anthropic:{signature:Q}}),q.push(T),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",S("");break;case"text-delta":w.delta&&(M.hasPending()&&(z=M.flushPending(z)),z+=w.delta,pe+=w.delta,S(z));break;case"tool-input-start":{let T=M.handleToolInputStart(w);T&&S(z+T),Te();break}case"tool-input-delta":{let T=M.handleToolInputDelta(w);T&&S(z+T),Te();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?et(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let T=fo(w.args??w.input);q.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added tool to messageParts",{messagePartsCount:q.length})}if(d&&w.toolCallId&&w.toolName&&et(w.toolName)){let T=fo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:T}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),S(z+M.buildToolDisplay()+`
123
+ [Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?et(w.toolName):!1});break}case"tool-output-start":{let T=M.handleToolOutputStart(w);T&&S(z+T),Te();break}case"tool-output-delta":{let T=M.handleToolOutputDelta(w);T&&S(z+T),Te();break}case"tool-output-end":{let T=M.handleToolOutputEnd(w,z);T&&(z=T.fullResponse,S(z+T.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let T=M.handleToolError(w,z);T&&(z=T.fullResponse,S(z+T.toolDisplay)),Te();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let B=q.findIndex(O=>O.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)}),S(z+M.buildToolDisplay()),Te();let w=await oo(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let T=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(B.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:T}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=M.handleToolOutputEnd({toolCallId:f.toolCallId},z);te&&(z=te.fullResponse)}else{let te=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},z);te&&(z=te.fullResponse)}S(z+M.buildToolDisplay()),Te()}Z.length=0;for(let f of B){let w=q.find(T=>(T.type==="tool-input-available"||T.type==="tool-call")&&T.toolCallId===f.toolCallId);if(w){let T=[];for(let U of f.content)U.type==="text"?T.push(U.text):U.type==="image"?T.push("[Image]"):U.type==="audio"?T.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&T.push("[Resource]");let te=T.join(`
124
+ `);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount: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};o?ne.agentId=o:(r&&(ne.model=r),ne.connectorIds=n??[],ne.enableSandbox=s,ne.enableWebSearch=i,ne.enableImageGeneration=a,ne.enableChart=c),K&&(ne.clientTools=K),j&&(ne.clientToolSystemPrompt=j),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:B.length});let O=await E.chat(A,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),R=O.body.getReader(),q.length=0,pe="",P="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}we+=ie.decode(w,{stream:!0});let T=we.split(`
125
+ `);we=T.pop()||"";for(let te of T)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let U=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":ee=U.id||"0",P="";break;case"reasoning-delta":U.delta&&(P+=U.delta,S(`${je}[Thinking...]${re}
126
+ ${P}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let be={type:"reasoning",id:ee,text:P,state:"done"};Q&&(be.providerMetadata={anthropic:{signature:Q}}),q.push(be),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:q.length})}P="",Q="",S(z);break;case"text-delta":U.delta&&(z+=U.delta,pe+=U.delta,S(z));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let be=fo(U.args??U.input);q.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:be})}if(d&&U.toolCallId&&U.toolName&&et(U.toolName)){let be=fo(U.args??U.input);Z.push({toolCallId:U.toolCallId,toolName:U.toolName,args:be}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",U);break}}catch{}}if(pe){let f=q.findIndex(T=>T.type!=="reasoning"),w=f===-1?q.length:f;q.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:q.length,fullResponseLength:z.length})}if(d&&K&&K.length>0){let B=[];for(let O of de)B.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of q)O.type==="text"&&O.text&&B.push({type:"text",text:O.text});let ne=mt(B,k);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:q.filter(O=>O.type==="text").length,contentLength:ne.length}),C(O=>[...O,{role:"assistant",content:ne,parts: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(O=>O.role)});let ne=B.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=mt(O,k);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),C(O=>[...O,{role:"assistant",content:z}])}catch(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 ==="),S(""),$({status:"ready"}),h(!0),ge.length>0&&L?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let ge=E instanceof Error?E.message:"Failed to send message";$({status:"error",message:ge})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,o,r,n,s,i,a,c,d,K,j,k,C,$,S,y,h,b,L])}}import{useState as Bt}from"react";var zn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},qn=new Map(Object.values(zn).map(e=>[e.apiKey,e.name]));function Yn(){return Object.values(zn)}function Xn(e,t,o,r,n){let[s,i]=Bt(e),[a,c]=Bt(t),[d,k]=Bt(o),[C,$]=Bt(r),[S,y]=Bt(n);return{sandbox:s,setSandbox:i,webSearch:a,setWebSearch:c,imageGeneration:d,setImageGeneration:k,chart:C,setChart:$,fileSystem:S,setFileSystem:y,capabilityLabelMap:qn}}import{useEffect as _s,useState as Ds}from"react";function Zn(e,t){let[o,r]=Ds(null);return _s(()=>{let n=!1;async function s(){if(!e||!t){r(null);return}try{let a=await new V().getAgent(t.accessToken,t.workspaceId,e);n||r(a)}catch{n||r(null)}}return s(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Wo}from"react";function Qn(e,t,o){let[r,n]=Wo(e),[s,i]=Wo(t),[a,c]=Wo(o);return{currentModel:r,setCurrentModel:n,currentAgentId:s,setCurrentAgentId:i,activeConnectorIds:a,setActiveConnectorIds:c}}import{useApp as Ls,useInput as Rs}from"ink";import{useCallback as ot,useRef as Us,useState as De}from"react";import{spawn as Os}from"child_process";function er(e){return new Promise((t,o)=>{let r,n;process.platform==="darwin"?(r="open",n=[e]):process.platform==="win32"?(r="cmd",n=["/c","start","",e]):(r="xdg-open",n=[e]);let s=Os(r,n,{stdio:"ignore",detached:!0});s.once("error",i=>{o(i)}),s.once("spawn",()=>{s.unref(),t()})})}var tr=[{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 or(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?tr.filter(o=>o.name.startsWith(t)||o.aliases.some(r=>r.startsWith(t))):tr}function nr(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),r=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(r){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 rr=`Available commands:
127
127
  /help, /h, /? Show this help message
128
128
  /clear, /cls, /new Start a new chat
129
129
  /model [name], /m Show current model or switch to [name]
@@ -147,97 +147,97 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
147
147
 
148
148
  Keyboard shortcuts:
149
149
  Ctrl+O Toggle full output mode
150
- Ctrl+C Exit`;function Bo(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function rs({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:r,currentModel:i,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:k,setCurrentAgentDetails:C,activeConnectorIds:$,setActiveConnectorIds:S,sandbox:y,setSandbox:h,webSearch:b,setWebSearch:L,imageGeneration:K,setImageGeneration:F,chart:re,setChart:Y,fileSystem:$e,setFileSystem:j,availableModels:A,availableAgents:N,availableConnectors:R,messages:M,hasPersistedChat:E,setHasPersistedChat:ge,setMessages:_,addSystemMessage:p,startNewChat:ie,sendMessage:we,setFullOutput:z,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:B=!1}){let{exit:Z}=Lr(),[q,de]=De([]),[Te,W]=De(0),[ne,O]=De(!1),[f,w]=De(null),[T,te]=De([]),[U,be]=De(0),[nt,st]=De(new Set),[Le,rt]=De(new Set),[Co,zt]=De([]),[We,ht]=De([]),[ze,qt]=De([]),[it,$o]=De([]),[Ge,qe]=De(null),[Yt,yt]=De(""),ft=Ur(!1),[at,wt]=De(!1),kt=ot(async()=>{if(!P)return[];let v=new V,g=[],c;do{let u=await v.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.skills),c=u.nextKey}while(c);return ht(g),g},[P]),xt=ot(async()=>{if(!P)return[];let v=new V,g=[],c;do{let u=await v.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.schedules),c=u.nextKey}while(c);return qt(g),g},[P]),Ee=ot(async v=>{if(v==="model"){if(A.length===0){p("No models available.");return}let g=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=i?g.findIndex(u=>u.id===i):-1;be(Math.max(c,0)),w("model")}else if(v==="agent"){if(N.length===0){p("No agents available.");return}let g=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=l?g.findIndex(u=>u.id===l):-1;be(Math.max(c,0)),w("agent")}else if(v==="skills"){let g=We;if(g.length===0)try{g=await kt()}catch{p("Failed to load skills.");return}if(g.length===0){p("No skills available.");return}let c=g.map(u=>({id:u.id,name:u.name,description:u.description}));te(c),be(0),w("skills")}else if(v==="schedules"){let g=ze;if(g.length===0)try{g=await xt()}catch{p("Failed to load schedules.");return}if(g.length===0){p("No schedules found.");return}let c=g.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(c),be(0),w("schedules")}else if(v==="connectors"){if(R.length===0){p("No connectors available.");return}let g=R.map(c=>({id:c.id,name:c.name}));te(g),be(0),st(new Set($||[])),w("connectors")}else if(v==="capabilities"){let g=Yn().map(u=>({id:u.id,name:u.name,description:u.description}));te(g),be(0);let c=new Set;y&&c.add("sandbox"),b&&c.add("webSearch"),K&&c.add("imageGeneration"),re&&c.add("chart"),$e&&c.add("fileSystem"),rt(c),w("capabilities")}else if(v==="chats"){if(!P){p("Not authenticated.");return}try{let g=new V,{chats:c}=await g.getChats(P.accessToken,P.workspaceId,20);if(c.length===0){p("No chats available.");return}zt(c);let u=c.map(I=>({id:I.id,name:I.title||"Untitled",description:new Date(I.createdAt).toLocaleDateString()}));te(u);let m=u.findIndex(I=>I.id===o);be(Math.max(m,0)),w("chats")}catch{p("Failed to load chats.")}}else if(v==="profile"){let g=G.getProfileNames(),c=G.getCurrentProfileName(),u=g.map(I=>({id:I,name:I,description:I===c?"(current)":void 0}));te(u);let m=u.findIndex(I=>I.id===c);be(Math.max(m,0)),w("profile")}O(!1),de([])},[A,N,We,ze,R,$,i,l,kt,xt,y,b,K,re,$e,P,o,p]),he=ot(v=>{let g=oe.getAll(v);a(g.model?.default),d(void 0),C(null);let c=g.connectors?.defaults;S(c&&c.length>0?c:void 0);let u=g.capabilities;h(u?.sandbox??pe.sandbox),L(u?.webSearch??pe.webSearch),F(u?.imageGeneration??pe.imageGeneration),Y(u?.chart??pe.chart);let m=g.localTools;j(m?.fileSystem??pe.fileSystem)},[a,d,C,S,h,L,F,Y,j,pe]),Ye=ot(async()=>{try{let v=await fe();ee({accessToken:v.accessToken,workspaceId:v.workspaceId}),Q({status:"ready"})}catch(v){if(ee(null),v instanceof Xe){if(v.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(v.code==="no-workspace"){Q({status:"no-workspace"});return}}let g=v instanceof Error?v.message:"Failed to authenticate";Q({status:"error",message:g})}},[ee,Q]),bt=ot(async v=>{switch(v.type){case"help":return p(ss),!0;case"clear":return ie("Started a new chat."),!0;case"model":{if(v.value){let g=v.value.toLowerCase(),c=A.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(c)l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id);else{let u=A.map(m=>m.name).join(", ");p(`Model "${v.value}" not found.
151
- Available: ${u||"none"}`)}}else{let g=A.find(c=>c.id===i)?.name||i;p(i?`Current model: ${g}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!v.value)return N.length===0?(p("No agents available."),!0):(Ee("agent"),!0);let g=v.value.toLowerCase(),c=N.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(c)c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=N.map(m=>m.name).join(", ");p(`Agent "${v.value}" not found.
152
- Available: ${u||"none"}`)}return!0}case"skills":{if(!v.value)return Ee("skills"),!0;let g=v.value.toLowerCase();return(We.length>0?Promise.resolve(We):kt().catch(()=>[])).then(u=>{let m=u.find(I=>I.id.toLowerCase()===g||I.name.toLowerCase().includes(g));p(m?`Skill: ${m.name}
150
+ 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 sr({input:e,setInput:t,chatId:o,setChatId:r,currentChatTitle:n,setCurrentChatTitle:s,currentModel:i,setCurrentModel:a,currentAgentId:c,setCurrentAgentId:d,currentAgentDetails:k,setCurrentAgentDetails:C,activeConnectorIds:$,setActiveConnectorIds:S,sandbox:y,setSandbox:h,webSearch:b,setWebSearch:L,imageGeneration:K,setImageGeneration:j,chart:se,setChart:Y,fileSystem:$e,setFileSystem:F,availableModels:A,availableAgents:N,availableConnectors:R,messages:W,hasPersistedChat:E,setHasPersistedChat:ge,setMessages:D,addSystemMessage:p,startNewChat:ie,sendMessage:we,setFullOutput:z,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:M=!1}){let{exit:Z}=Ls(),[q,de]=De([]),[Te,B]=De(0),[ne,O]=De(!1),[f,w]=De(null),[T,te]=De([]),[U,be]=De(0),[nt,rt]=De(new Set),[Le,st]=De(new Set),[Co,zt]=De([]),[Be,ht]=De([]),[ze,qt]=De([]),[it,$o]=De([]),[Ge,qe]=De(null),[Yt,yt]=De(""),ft=Us(!1),[at,wt]=De(!1),kt=ot(async()=>{if(!P)return[];let I=new V,g=[],l;do{let u=await I.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:l});g.push(...u.skills),l=u.nextKey}while(l);return ht(g),g},[P]),xt=ot(async()=>{if(!P)return[];let I=new V,g=[],l;do{let u=await I.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:l});g.push(...u.schedules),l=u.nextKey}while(l);return qt(g),g},[P]),Ee=ot(async I=>{if(I==="model"){if(A.length===0){p("No models available.");return}let g=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let l=i?g.findIndex(u=>u.id===i):-1;be(Math.max(l,0)),w("model")}else if(I==="agent"){if(N.length===0){p("No agents available.");return}let g=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let l=c?g.findIndex(u=>u.id===c):-1;be(Math.max(l,0)),w("agent")}else if(I==="skills"){let g=Be;if(g.length===0)try{g=await kt()}catch{p("Failed to load skills.");return}if(g.length===0){p("No skills available.");return}let l=g.map(u=>({id:u.id,name:u.name,description:u.description}));te(l),be(0),w("skills")}else if(I==="schedules"){let g=ze;if(g.length===0)try{g=await xt()}catch{p("Failed to load schedules.");return}if(g.length===0){p("No schedules found.");return}let l=g.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(l),be(0),w("schedules")}else if(I==="connectors"){if(R.length===0){p("No connectors available.");return}let g=R.map(l=>({id:l.id,name:l.name}));te(g),be(0),rt(new Set($??[])),w("connectors")}else if(I==="capabilities"){let g=Yn().map(u=>({id:u.id,name:u.name,description:u.description}));te(g),be(0);let l=new Set;y&&l.add("sandbox"),b&&l.add("webSearch"),K&&l.add("imageGeneration"),se&&l.add("chart"),$e&&l.add("fileSystem"),st(l),w("capabilities")}else if(I==="chats"){if(!P){p("Not authenticated.");return}try{let g=new V,{chats:l}=await g.getChats(P.accessToken,P.workspaceId,20);if(l.length===0){p("No chats available.");return}zt(l);let u=l.map(v=>({id:v.id,name:v.title||"Untitled",description:new Date(v.createdAt).toLocaleDateString()}));te(u);let m=u.findIndex(v=>v.id===o);be(Math.max(m,0)),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let g=G.getProfileNames(),l=G.getCurrentProfileName(),u=g.map(v=>({id:v,name:v,description:v===l?"(current)":void 0}));te(u);let m=u.findIndex(v=>v.id===l);be(Math.max(m,0)),w("profile")}O(!1),de([])},[A,N,Be,ze,R,$,i,c,kt,xt,y,b,K,se,$e,P,o,p]),he=ot(I=>{let g=oe.getAll(I);a(g.model?.default),d(void 0),C(null);let l=g.connectors?.defaults;S(l&&l.length>0?l:void 0);let u=g.capabilities;h(u?.sandbox??pe.sandbox),L(u?.webSearch??pe.webSearch),j(u?.imageGeneration??pe.imageGeneration),Y(u?.chart??pe.chart);let m=g.localTools;F(m?.fileSystem??pe.fileSystem)},[a,d,C,S,h,L,j,Y,F,pe]),Ye=ot(async()=>{try{let I=await fe();ee({accessToken:I.accessToken,workspaceId:I.workspaceId}),Q({status:"ready"})}catch(I){if(ee(null),I instanceof Xe){if(I.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(I.code==="no-workspace"){Q({status:"no-workspace"});return}}let g=I instanceof Error?I.message:"Failed to authenticate";Q({status:"error",message:g})}},[ee,Q]),bt=ot(async I=>{switch(I.type){case"help":return p(rr),!0;case"clear":return ie("Started a new chat."),!0;case"model":{if(I.value){let g=I.value.toLowerCase(),l=A.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(l)c?ie(`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(m=>m.name).join(", ");p(`Model "${I.value}" not found.
151
+ Available: ${u||"none"}`)}}else{let g=A.find(l=>l.id===i)?.name||i;p(i?`Current model: ${g}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return N.length===0?(p("No agents available."),!0):(Ee("agent"),!0);let g=I.value.toLowerCase(),l=N.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(l)l.id!==c?ie(`Switched to agent: ${l.name} (new chat)`):p(`Switched to agent: ${l.name}`),d(l.id),a(void 0);else{let u=N.map(m=>m.name).join(", ");p(`Agent "${I.value}" not found.
152
+ Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return Ee("skills"),!0;let g=I.value.toLowerCase();return(Be.length>0?Promise.resolve(Be):kt().catch(()=>[])).then(u=>{let m=u.find(v=>v.id.toLowerCase()===g||v.name.toLowerCase().includes(g));p(m?`Skill: ${m.name}
153
153
  ${m.description}
154
154
  Provider: ${m.provider}
155
155
  Author: ${m.author.name}
156
- ID: ${m.id}`:`Skill "${v.value}" not found.`)}),!0}case"schedules":{if(!v.value)return Ee("schedules"),!0;let g=v.value.toLowerCase();return(ze.length>0?Promise.resolve(ze):xt().catch(()=>[])).then(u=>{let m=u.find(I=>I.id.toLowerCase()===g||I.name.toLowerCase().includes(g));if(m){let I=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
156
+ ID: ${m.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return Ee("schedules"),!0;let g=I.value.toLowerCase();return(ze.length>0?Promise.resolve(ze):xt().catch(()=>[])).then(u=>{let m=u.find(v=>v.id.toLowerCase()===g||v.name.toLowerCase().includes(g));if(m){let v=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
157
157
  Agent: ${m.agent.name}
158
158
  Status: ${m.isActive?"Active":"Paused"}
159
- Repeat: ${Bo(m.config)}
160
- Next Run: ${I}
161
- ID: ${m.id}`)}else p(`Schedule "${v.value}" not found.`)}),!0}case"connectors":{if(l){let c=k?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(m=>` - ${m.name}`).join(`
159
+ Repeat: ${Mo(m.config)}
160
+ Next Run: ${v}
161
+ ID: ${m.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(c){let l=k?.connectors??[];if(l.length===0)p("No agent connectors.");else{let u=l.map(m=>` - ${m.name}`).join(`
162
162
  `);p(`Agent connectors:
163
- ${u}`)}return!0}let g=R.filter(c=>$?.includes(c.id));if(g.length===0)p("No active connectors.");else{let c=g.map(u=>` - ${u.name}`).join(`
163
+ ${u}`)}return!0}let g=R.filter(l=>$?.includes(l.id));if(g.length===0)p("No active connectors.");else{let l=g.map(u=>` - ${u.name}`).join(`
164
164
  `);p(`Active connectors:
165
- ${c}`)}return!0}case"capabilities":{if(l){let u=(k?.capabilities||[]).map(m=>le.get(m)??m);return p(u.length>0?`Agent capabilities:
165
+ ${l}`)}return!0}case"capabilities":{if(c){let u=(k?.capabilities??[]).map(m=>le.get(m)??m);return p(u.length>0?`Agent capabilities:
166
166
  ${u.map(m=>` - ${m}`).join(`
167
- `)}`:"No agent capabilities."),!0}let g=[];return y&&g.push("Sandbox"),b&&g.push("Web Search"),K&&g.push("Image Generation"),re&&g.push("Chart"),$e&&g.push("FileSystem"),p(g.length>0?`Active capabilities:
168
- ${g.map(c=>` - ${c}`).join(`
169
- `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!P)return p("Not authenticated."),!0;let g=new V;if(!v.value){try{let{workspaces:u}=await g.getWorkspaces(P.accessToken);if(u.length===0)p("No workspaces found.");else{let m=u.map(I=>` ${I.id===P.workspaceId?"* ":" "}${I.name}
170
- ID: ${I.id}`);p(`Workspaces:
167
+ `)}`:"No agent capabilities."),!0}let g=[];return y&&g.push("Sandbox"),b&&g.push("Web Search"),K&&g.push("Image Generation"),se&&g.push("Chart"),$e&&g.push("FileSystem"),p(g.length>0?`Active capabilities:
168
+ ${g.map(l=>` - ${l}`).join(`
169
+ `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!P)return p("Not authenticated."),!0;let g=new V;if(!I.value){try{let{workspaces:u}=await g.getWorkspaces(P.accessToken);if(u.length===0)p("No workspaces found.");else{let m=u.map(v=>` ${v.id===P.workspaceId?"* ":" "}${v.name}
170
+ ID: ${v.id}`);p(`Workspaces:
171
171
  ${m.join(`
172
- `)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=v.value;try{let{workspaces:u}=await g.getWorkspaces(P.accessToken),m=u.find(I=>I.id===c);if(!m)return p(`Workspace not found: ${c}`),!0;await Se.saveWorkspaceId(c),p(`Switched to workspace: ${m.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let g=new V;if(!v.value){try{let m=await g.getBudget(P.accessToken,P.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let c=v.value.toLowerCase();if(c==="clear"||c==="null"){try{await g.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await g.updateBudget(P.accessToken,P.workspaceId,c),p(`Budget set to: $${c}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let g=new V;try{let c=[],u,m=0,I=10;do{let Ie=await g.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(c.push(...Ie.monthlyUsages),u=Ie.nextKey,m++,m>=I){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let x=0,D=0;for(let Ie of c)x+=parseFloat(Ie.totalCost),D+=Ie.operationCount;let me=[...c].toSorted((Ie,lt)=>parseFloat(lt.totalCost)-parseFloat(Ie.totalCost)),J=10,ce=me.slice(0,J),Re=[`Total Cost: $${x.toFixed(2)}`,`Total Operations: ${D.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Ie=>` ${Ie.user.name}: $${parseFloat(Ie.totalCost).toFixed(2)} (${Ie.operationCount.toLocaleString()} ops)`)];c.length>J&&(Re.push("",`... and ${c.length-J} more users`),Re.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Re.join(`
173
- `))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let g=G.getCurrentProfileName(),c=i?A.find(x=>x.id===i)?.name||i:null,u=l?N.find(x=>x.id===l)?.name||l:null,m=$?R.filter(x=>$.includes(x.id)).map(x=>x.name):[],I=[];return y&&I.push("Sandbox"),b&&I.push("Web Search"),K&&I.push("Image Gen"),re&&I.push("Chart"),$e&&I.push("FileSystem"),Se.getEmail().then(x=>{let D=[`Profile: ${g}${g!=="default"?" (non-default)":""}`,x?`Logged in as: ${x}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(D.join(`
174
- `))}).catch(()=>{let x=[`Profile: ${g}`,"Not logged in",E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(x.join(`
175
- `))}),!0}case"profile":{let g=v.value?v.value.split(/\s+/).filter(Boolean):[];if(g.length===0)return Ee("profile"),!0;let c=g[0]?.toLowerCase()||"list",u=g[1],m=g[2],I=G.getProfileNames(),x=G.getCurrentProfileName(),D=G.getOverrideProfile(),me=(J,ce=!1)=>{if(J)return J;if(ce&&I.length===1)return I[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let J=[`Profiles (${I.length}):`];for(let ce of I){let Re=ce===x?" (current)":"";J.push(` ${ce}${Re}`)}return p(J.join(`
176
- `)),!0}if(c==="current")return p(`Current profile: ${x}`),!0;if(c==="show"){let J=me(u,!0),ce=oe.getAll(J),Re=await Se.getAll(J),Ie=!!Re?.accessToken,lt=ce.capabilities?Object.entries(ce.capabilities).filter(([,So])=>So).map(([So])=>So):[],Hs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Ks=[`Profile: ${J}${J===x?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Hs}`,`Capabilities: ${lt.length>0?lt.join(", "):"none"}`,Ie?`Logged in as: ${Re?.email??"unknown"}`:"Not logged in",Ie&&Re?.workspaceId?`Workspace ID: ${Re.workspaceId}`:null].filter(Boolean);return p(Ks.join(`
177
- `)),!0}if(c==="create"){let J=u||G.DEFAULT_PROFILE;return G.createProfile(J),p(`Profile created: ${J}`),!0}if(c==="use"||c==="switch"){let J=me(u,!0);return G.setOverrideProfile(J),G.setCurrentProfile(J),he(J),await Ye(),ie(`Switched to profile: ${J} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let J=me(u,!0),ce=J===x,Re=G.deleteProfile(J),Ie=`Profile deleted: ${J}`;if(ce)G.setOverrideProfile(Re.currentProfile),he(Re.currentProfile),await Ye(),ie(`${Ie}
178
- Switched to profile: ${Re.currentProfile} (new chat)`);else if(D===J){let lt=G.getCurrentProfileName();G.setOverrideProfile(lt),he(lt),await Ye(),ie(`${Ie}
179
- Switched to profile: ${lt} (new chat)`)}else p(Ie);return!0}if(c==="rename"||c==="move"||c==="mv"){let J=me(u,!0);if(!m)throw new Error("New profile name is required.");let ce=G.renameProfile(J,m);return p(`Profile renamed: ${J} -> ${m}`),D===J?(G.setOverrideProfile(m),he(m)):ce.currentProfile===m&&he(m),!0}if(c==="clone"||c==="copy"){let J=me(u,!0);if(!m)throw new Error("Target profile name is required.");let ce=oe.getAll(J);return G.createProfile(m),oe.setAll(ce,m),await Se.clear(m),p(`Profile cloned: ${J} -> ${m}`),!0}p(`Unknown profile command: ${c}`)}catch(J){let ce=J instanceof Error?J.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let g=Ze().hubUrl.replace(/\/$/,""),u=E||M.some(x=>x.role!=="system")?`/chat/${o}`:"/chat/new",m=l?`?agentId=${encodeURIComponent(l)}`:"",I=`${g}${u}${m}`;try{await es(I),p(`Opened in browser: ${I}`)}catch(x){p(`Failed to open browser: ${x instanceof Error?x.message:"Unknown error"}
180
- URL: ${I}`)}return!0}case"share":{if(!P)return p("Not authenticated."),!0;if(!(E||M.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new V().createChatShare(P.accessToken,P.workspaceId,o,"public"),I=`${Ze().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${I}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return P?E?(wt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${v.input}
181
- Type /help for available commands.`),!0;default:return!1}},[p,A,N,R,We,ze,i,l,$,y,b,K,re,$e,o,n,Z,Ee,ie,le,k,E,M,kt,xt,_,a,d,C,a,he,Ye]),Xt=ot(v=>{if(ft.current=!1,at){(v===""||v.startsWith("/"))&&(t(v),v.startsWith("/")&&wt(!1));return}if(t(v),yt(v),Ge!==null&&qe(null),f&&(w(null),te([])),v.startsWith("/")&&!v.includes(" ")){let g=os(v);de(g),W(0),O(g.length>0)}else O(!1),de([])},[f,Ge,at,t]),Et=ot((v,g=!1)=>{if(v>=0&&v<q.length){let c=q[v];O(!1),de([]),c.name==="model"?(t("/model "),Ee("model")):c.name==="agent"?(t("/agent "),Ee("agent")):c.name==="skills"?(t("/skills "),Ee("skills")):c.name==="schedules"?(t("/schedules "),Ee("schedules")):c.name==="connectors"?(t("/connectors "),Ee("connectors")):c.name==="capabilities"?(t("/capabilities "),Ee("capabilities")):c.name==="chats"?(t("/chats "),Ee("chats")):c.name==="profile"?(t("/profile "),Ee("profile")):g?(t(""),bt({type:c.name})):t(`/${c.name}`)}},[q,Ee,t,bt]),Zt=ot(async v=>{ft.current=!1;let g=v.trim();if(!g||at)return;if(f==="model"&&T.length>0){let u=T[U];u&&(l?ie(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&T.length>0){let u=T[U];u&&(u.id!==l?ie(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&T.length>0){let u=T[U];if(u){let m=We.find(I=>I.id===u.id);m&&p(`Skill: ${m.name}
172
+ `)}`)}}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 g.getWorkspaces(P.accessToken),m=u.find(v=>v.id===l);if(!m)return p(`Workspace not found: ${l}`),!0;await Se.saveWorkspaceId(l),p(`Switched to workspace: ${m.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let g=new V;if(!I.value){try{let m=await g.getBudget(P.accessToken,P.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let l=I.value.toLowerCase();if(l==="clear"||l==="null"){try{await g.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(l);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await g.updateBudget(P.accessToken,P.workspaceId,l),p(`Budget set to: $${l}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let g=new V;try{let l=[],u,m=0,v=10;do{let Ie=await g.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(l.push(...Ie.monthlyUsages),u=Ie.nextKey,m++,m>=v){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 x=0,_=0;for(let Ie of l)x+=parseFloat(Ie.totalCost),_+=Ie.operationCount;let me=[...l].toSorted((Ie,lt)=>parseFloat(lt.totalCost)-parseFloat(Ie.totalCost)),J=10,ce=me.slice(0,J),Re=[`Total Cost: $${x.toFixed(2)}`,`Total Operations: ${_.toLocaleString()}`,`Users: ${l.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Ie=>` ${Ie.user.name}: $${parseFloat(Ie.totalCost).toFixed(2)} (${Ie.operationCount.toLocaleString()} ops)`)];l.length>J&&(Re.push("",`... and ${l.length-J} more users`),Re.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Re.join(`
173
+ `))}catch(l){p(`Failed to get usage: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"status":{let g=G.getCurrentProfileName(),l=i?A.find(x=>x.id===i)?.name||i:null,u=c?N.find(x=>x.id===c)?.name||c:null,m=$?R.filter(x=>$.includes(x.id)).map(x=>x.name):[],v=[];return y&&v.push("Sandbox"),b&&v.push("Web Search"),K&&v.push("Image Gen"),se&&v.push("Chart"),$e&&v.push("FileSystem"),Se.getEmail().then(x=>{let _=[`Profile: ${g}${g!=="default"?" (non-default)":""}`,x?`Logged in as: ${x}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${o}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${v.length>0?v.join(", "):"none"}`].filter(Boolean);p(_.join(`
174
+ `))}).catch(()=>{let x=[`Profile: ${g}`,"Not logged in",E?`Chat ID: ${o}`:null,l?`Model: ${l}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${v.length>0?v.join(", "):"none"}`].filter(Boolean);p(x.join(`
175
+ `))}),!0}case"profile":{let g=I.value?I.value.split(/\s+/).filter(Boolean):[];if(g.length===0)return Ee("profile"),!0;let l=g[0]?.toLowerCase()||"list",u=g[1],m=g[2],v=G.getProfileNames(),x=G.getCurrentProfileName(),_=G.getOverrideProfile(),me=(J,ce=!1)=>{if(J)return J;if(ce&&v.length===1)return v[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(l==="list"){let J=[`Profiles (${v.length}):`];for(let ce of v){let Re=ce===x?" (current)":"";J.push(` ${ce}${Re}`)}return p(J.join(`
176
+ `)),!0}if(l==="current")return p(`Current profile: ${x}`),!0;if(l==="show"){let J=me(u,!0),ce=oe.getAll(J),Re=await Se.getAll(J),Ie=!!Re?.accessToken,lt=ce.capabilities?Object.entries(ce.capabilities).filter(([,So])=>So).map(([So])=>So):[],Hr=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Kr=[`Profile: ${J}${J===x?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Hr}`,`Capabilities: ${lt.length>0?lt.join(", "):"none"}`,Ie?`Logged in as: ${Re?.email??"unknown"}`:"Not logged in",Ie&&Re?.workspaceId?`Workspace ID: ${Re.workspaceId}`:null].filter(Boolean);return p(Kr.join(`
177
+ `)),!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=me(u,!0);return G.setOverrideProfile(J),G.setCurrentProfile(J),he(J),await Ye(),ie(`Switched to profile: ${J} (new chat)`),!0}if(l==="delete"||l==="remove"||l==="rm"){let J=me(u,!0),ce=J===x,Re=G.deleteProfile(J),Ie=`Profile deleted: ${J}`;if(ce)G.setOverrideProfile(Re.currentProfile),he(Re.currentProfile),await Ye(),ie(`${Ie}
178
+ Switched to profile: ${Re.currentProfile} (new chat)`);else if(_===J){let lt=G.getCurrentProfileName();G.setOverrideProfile(lt),he(lt),await Ye(),ie(`${Ie}
179
+ Switched to profile: ${lt} (new chat)`)}else p(Ie);return!0}if(l==="rename"||l==="move"||l==="mv"){let J=me(u,!0);if(!m)throw new Error("New profile name is required.");let ce=G.renameProfile(J,m);return p(`Profile renamed: ${J} -> ${m}`),_===J?(G.setOverrideProfile(m),he(m)):ce.currentProfile===m&&he(m),!0}if(l==="clone"||l==="copy"){let J=me(u,!0);if(!m)throw new Error("Target profile name is required.");let ce=oe.getAll(J);return G.createProfile(m),oe.setAll(ce,m),await Se.clear(m),p(`Profile cloned: ${J} -> ${m}`),!0}p(`Unknown profile command: ${l}`)}catch(J){let ce=J instanceof Error?J.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let g=Ze().hubUrl.replace(/\/$/,""),l=E||W.some(_=>_.role!=="system"),u=P?`/${P.workspaceId}`:"",m=l?`${u}/chat/${o}`:`${u}/chat/new`,v=c?`?agentId=${encodeURIComponent(c)}`:"",x=`${g}${m}${v}`;try{await er(x),p(`Opened in browser: ${x}`)}catch(_){p(`Failed to open browser: ${_ instanceof Error?_.message:"Unknown error"}
180
+ URL: ${x}`)}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 V().createChatShare(P.accessToken,P.workspaceId,o,"public"),v=`${Ze().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${v}`)}catch(l){p(`Failed to create share link: ${l instanceof Error?l.message:"Unknown error"}`)}return!0}case"delete":return P?E?(wt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${I.input}
181
+ Type /help for available commands.`),!0;default:return!1}},[p,A,N,R,Be,ze,i,c,$,y,b,K,se,$e,o,n,Z,Ee,ie,le,k,E,W,kt,xt,D,a,d,C,a,he,Ye]),Xt=ot(I=>{if(ft.current=!1,at){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&wt(!1));return}if(t(I),yt(I),Ge!==null&&qe(null),f&&(w(null),te([])),I.startsWith("/")&&!I.includes(" ")){let g=or(I);de(g),B(0),O(g.length>0)}else O(!1),de([])},[f,Ge,at,t]),Et=ot((I,g=!1)=>{if(I>=0&&I<q.length){let l=q[I];O(!1),de([]),l.name==="model"?(t("/model "),Ee("model")):l.name==="agent"?(t("/agent "),Ee("agent")):l.name==="skills"?(t("/skills "),Ee("skills")):l.name==="schedules"?(t("/schedules "),Ee("schedules")):l.name==="connectors"?(t("/connectors "),Ee("connectors")):l.name==="capabilities"?(t("/capabilities "),Ee("capabilities")):l.name==="chats"?(t("/chats "),Ee("chats")):l.name==="profile"?(t("/profile "),Ee("profile")):g?(t(""),bt({type:l.name})):t(`/${l.name}`)}},[q,Ee,t,bt]),Zt=ot(async I=>{ft.current=!1;let g=I.trim();if(!g||at)return;if(f==="model"&&T.length>0){let u=T[U];u&&(c?ie(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&T.length>0){let u=T[U];u&&(u.id!==c?ie(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&T.length>0){let u=T[U];if(u){let m=Be.find(v=>v.id===u.id);m&&p(`Skill: ${m.name}
182
182
  ${m.description}
183
183
  Provider: ${m.provider}
184
184
  Author: ${m.author.name}
185
- ID: ${m.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&T.length>0){let u=T[U];if(u){let m=ze.find(I=>I.id===u.id);if(m){let I=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
185
+ ID: ${m.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&T.length>0){let u=T[U];if(u){let m=ze.find(v=>v.id===u.id);if(m){let v=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
186
186
  Agent: ${m.agent.name}
187
187
  Status: ${m.isActive?"Active":"Paused"}
188
- Repeat: ${Bo(m.config)}
189
- Next Run: ${I}
190
- ID: ${m.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(nt);S(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let m=R.filter(I=>nt.has(I.id)).map(I=>I.name);p(m.length>0?`Active connectors: ${m.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=Le.has("sandbox"),m=Le.has("webSearch"),I=Le.has("imageGeneration"),x=Le.has("chart"),D=Le.has("fileSystem");h(u),L(m),F(I),Y(x),j(D),oe.setCapabilities({sandbox:u,webSearch:m,imageGeneration:I,chart:x}),oe.setLocalTools({fileSystem:D});let me=[];u&&me.push("Sandbox"),m&&me.push("Web Search"),I&&me.push("Image Generation"),x&&me.push("Chart"),D&&me.push("FileSystem"),p(me.length>0?`Active capabilities: ${me.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&T.length>0){let u=T[U];if(u){let m=G.getCurrentProfileName();u.id!==m?(G.setOverrideProfile(u.id),G.setCurrentProfile(u.id),he(u.id),Ye(),ie(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&q.length>0){Et(Te,!0);return}qe(null),yt(""),$o(u=>u.length>0&&u.at(-1)===g?u:[...u,g]);let c=ns(g);if(c){await bt(c),t(""),O(!1);return}if(B){p("Please wait for file uploads to complete.");return}t(""),O(!1),we(g)},[we,bt,ne,q,Te,Et,f,T,U,nt,Le,R,We,ze,p,t,l,ie,a,d,C,S,h,L,F,Y,j,B,he,Ye,at,P,E,o]);return Rr((v,g)=>{if(g.ctrl&&v==="c"){if(e.length>0){Xt(""),ft.current=!0,p("Press Ctrl+C again to exit.");return}if(ft.current){Z();return}Z();return}if(g.ctrl&&v==="o"){z(c=>!c);return}if(at){if(g.escape||g.return||v==="n"||v==="N"){wt(!1),t(""),p("Chat deletion cancelled.");return}if(v==="y"||v==="Y"){wt(!1),t(""),P&&E&&new V().deleteChat(P.accessToken,P.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&T.length>0){if(g.upArrow){be(c=>c<=0?T.length-1:c-1);return}if(g.downArrow){be(c=>c>=T.length-1?0:c+1);return}if(g.escape){w(null),te([]),t("");return}if(g.return){if(f==="model"){let c=T[U];c&&(l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id))}else if(f==="agent"){let c=T[U];c&&(c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0))}else if(f==="skills"){let c=T[U];if(c){let u=We.find(m=>m.id===c.id);u&&p(`Skill: ${u.name}
188
+ Repeat: ${Mo(m.config)}
189
+ Next Run: ${v}
190
+ ID: ${m.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(nt);S(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let m=R.filter(v=>nt.has(v.id)).map(v=>v.name);p(m.length>0?`Active connectors: ${m.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=Le.has("sandbox"),m=Le.has("webSearch"),v=Le.has("imageGeneration"),x=Le.has("chart"),_=Le.has("fileSystem");h(u),L(m),j(v),Y(x),F(_),oe.setCapabilities({sandbox:u,webSearch:m,imageGeneration:v,chart:x}),oe.setLocalTools({fileSystem:_});let me=[];u&&me.push("Sandbox"),m&&me.push("Web Search"),v&&me.push("Image Generation"),x&&me.push("Chart"),_&&me.push("FileSystem"),p(me.length>0?`Active capabilities: ${me.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&T.length>0){let u=T[U];if(u){let m=G.getCurrentProfileName();u.id!==m?(G.setOverrideProfile(u.id),G.setCurrentProfile(u.id),he(u.id),Ye(),ie(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&q.length>0){Et(Te,!0);return}qe(null),yt(""),$o(u=>u.length>0&&u.at(-1)===g?u:[...u,g]);let l=nr(g);if(l){await bt(l),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),we(g)},[we,bt,ne,q,Te,Et,f,T,U,nt,Le,R,Be,ze,p,t,c,ie,a,d,C,S,h,L,j,Y,F,M,he,Ye,at,P,E,o]);return Rs((I,g)=>{if(g.ctrl&&I==="c"){if(e.length>0){Xt(""),ft.current=!0,p("Press Ctrl+C again to exit.");return}if(ft.current){Z();return}Z();return}if(g.ctrl&&I==="o"){z(l=>!l);return}if(at){if(g.escape||g.return||I==="n"||I==="N"){wt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){wt(!1),t(""),P&&E&&new V().deleteChat(P.accessToken,P.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&T.length>0){if(g.upArrow){be(l=>l<=0?T.length-1:l-1);return}if(g.downArrow){be(l=>l>=T.length-1?0:l+1);return}if(g.escape){w(null),te([]),t("");return}if(g.return){if(f==="model"){let l=T[U];l&&(c?ie(`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=T[U];l&&(l.id!==c?ie(`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=T[U];if(l){let u=Be.find(m=>m.id===l.id);u&&p(`Skill: ${u.name}
191
191
  ${u.description}
192
192
  Provider: ${u.provider}
193
193
  Author: ${u.author.name}
194
- ID: ${u.id}`)}}else if(f==="schedules"){let c=T[U];if(c){let u=ze.find(m=>m.id===c.id);if(u){let m=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
194
+ ID: ${u.id}`)}}else if(f==="schedules"){let l=T[U];if(l){let u=ze.find(m=>m.id===l.id);if(u){let m=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
195
195
  Agent: ${u.agent.name}
196
196
  Status: ${u.isActive?"Active":"Paused"}
197
- Repeat: ${Bo(u.config)}
197
+ Repeat: ${Mo(u.config)}
198
198
  Next Run: ${m}
199
- ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(nt);S(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=R.filter(m=>nt.has(m.id)).map(m=>m.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Le.has("sandbox"),u=Le.has("webSearch"),m=Le.has("imageGeneration"),I=Le.has("chart"),x=Le.has("fileSystem");h(c),L(u),F(m),Y(I),j(x),oe.setCapabilities({sandbox:c,webSearch:u,imageGeneration:m,chart:I}),oe.setLocalTools({fileSystem:x});let D=[];c&&D.push("Sandbox"),u&&D.push("Web Search"),m&&D.push("Image Generation"),I&&D.push("Chart"),x&&D.push("FileSystem"),p(D.length>0?`Active capabilities: ${D.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=T[U];if(c){let u=Co.find(m=>m.id===c.id);u&&P&&(s(u.id),r(u.title||void 0),ge(!0),new V().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:I})=>{let x=I.filter(D=>D.role==="user"||D.role==="assistant").map(D=>({role:D.role,content:mt(D.parts,!1),parts:D.parts})).filter(D=>D.content).toReversed();_(x),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=T[U];if(c){let u=G.getCurrentProfileName();c.id!==u?(G.setOverrideProfile(c.id),G.setCurrentProfile(c.id),he(c.id),Ye(),ie(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),te([]),t("");return}if(v===" "&&(f==="connectors"||f==="capabilities")){let c=T[U];c&&(f==="connectors"?st:rt)(m=>{let I=new Set(m);return I.has(c.id)?I.delete(c.id):I.add(c.id),I});return}if(v==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?st:rt)(new Set(T.map(u=>u.id)));return}if(v==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?st:rt)(new Set);return}return}if(ne&&q.length>0){if(g.upArrow){W(c=>c<=0?q.length-1:c-1);return}if(g.downArrow){W(c=>c>=q.length-1?0:c+1);return}if(g.escape){O(!1),de([]);return}if(g.tab){Et(Te);return}}if(g.upArrow){if(e.includes(`
200
- `)||it.length===0)return;if(Ge===null){yt(e);let u=it.length-1;qe(u),t(it[u]);return}let c=Math.max(0,Ge-1);qe(c),t(it[c]);return}if(g.downArrow){if(e.includes(`
201
- `)||Ge===null)return;if(Ge>=it.length-1){qe(null),t(Yt);return}let c=Ge+1;qe(c),t(it[c])}}),{suggestions:q,suggestionIndex:Te,showSuggestions:ne,argMode:f,argItems:T,argIndex:U,selectedConnectorIds:nt,selectedCapabilities:Le,deleteConfirmMode:at,handleInputChange:Xt,handleSubmit:Zt}}import{useCallback as Mt,useRef as jr,useState as Fr}from"react";function is({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[r,i]=Fr([]),a=jr(0),l=Mt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let b of o)if(b.models.some(K=>K.id===h))return b.id;return o[0]?.id}},[o]),d=Mt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let b=t?l(t):o[0]?.id;if(!b){n?.(h.filename,"No model provider available");return}let L=`file-${++a.current}`;i(K=>[...K,{id:L,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let F=await new V().uploadFile(e.accessToken,e.workspaceId,h,b);i(re=>re.map(Y=>Y.id===L?{...Y,status:"uploaded",fileId:F.id}:Y)),s?.(h.filename)}catch(K){let F=K instanceof Error?K.message:"Upload failed";i(re=>re.map(Y=>Y.id===L?{...Y,status:"error",error:F}:Y)),n?.(h.filename,F)}},[e,t,l,o,s,n]),k=Mt(h=>{i(b=>b.filter(L=>L.id!==h))},[]),C=Mt(()=>{i([])},[]),$=Mt(()=>r.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[r]),S=r.some(h=>h.status==="uploading"),y=r.length>0;return{pendingFiles:r,addFile:d,removeFile:k,clearFiles:C,getUploadedFileIds:$,hasUploadingFiles:S,hasFiles:y}}import{jsx as X,jsxs as ue}from"react/jsx-runtime";var Mr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Br=[Wo,Wo,Fo,Fo,pt,pt,pt,pt],ls=Mr.map((e,t)=>`${Br[t]??pt}${e}${se}`).join(`
202
- `),Jr=`${pt}EntryDesk${se}`,Gr=500;function Vr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Hr(e){let t=Vr(e);return Math.max(...t.split(`
203
- `).map(o=>o.length))}function Kr(e){let t=Hr(ls);return e>=t?ls:Jr}function cs({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:r,enableSandbox:i=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:k=!0}){let C=process.stdout.columns??80,$=Kr(C),S=as(null),y=Mn(s,n),{state:h,setState:b,messages:L,setMessages:K,input:F,setInput:re,chatId:Y,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:R,credentials:M,setCredentials:E,currentResponse:ge,setCurrentResponse:_,fullOutput:p,setFullOutput:ie,addSystemMessage:we,startNewChat:z}=y,{credentials:P}=Jn(b);po(()=>{P&&!M&&E(P)},[P,M,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:B}=Gn(M),{currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,activeConnectorIds:W,setActiveConnectorIds:ne}=Qn(t,e,r),O=as(!1);po(()=>{if(!O.current){if(O.current=!0,!t&&!e){let x=oe.getDefaultModel();x&&q(x)}if(!r&&!e){let x=oe.getDefaultConnectorIds();x&&ne(x.length>0?x:void 0)}}},[t,e,r,q,ne]);let{currentAgentDetails:f}=Zn(de,M),{sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:be,setImageGeneration:nt,chart:st,setChart:Le,fileSystem:rt,setFileSystem:Co,capabilityLabelMap:zt}=Xn(i,a,l,d,k),{pendingFiles:We,addFile:ht,removeFile:ze,clearFiles:qt,getUploadedFileIds:it,hasUploadingFiles:$o,hasFiles:Ge}=is({credentials:M,currentModel:Z,modelProviders:le,onUploadSuccess:x=>{we(`\u2713 Attached: ${x}`)},onUploadError:(x,D)=>{we(`\u2717 Failed to upload ${x}: ${D}`)}}),{sendMessage:qe}=Kn({chatId:Y,credentials:M,currentAgentId:de,currentModel:Z,activeConnectorIds:W,sandbox:w,webSearch:te,imageGeneration:be,chart:st,localTools:rt,fullOutput:p,setMessages:K,setState:b,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:R,getFileIds:it,clearFiles:qt}),Yt=Vo(x=>{z(x),_("")},[z]),[yt,ft]=Wr(!1),at=Vo(async x=>{let D=x.text.trim(),me=co(D);if(/^https?:\/\//.test(me))return;if(await Un(D)&&Rn(me)){let ce=await jn(D);ce&&(x.preventDefault(),await ht(ce))}},[ht]),wt=Vo(async()=>{if(!(yt||h.status!=="ready")){if(B||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),ft(!0);try{let x=await Ln();if(x){let D=`clipboard-${Date.now()}.png`;we(`Uploading: ${D} (${Math.round(x.buffer.length/1024)}KB)`),await ht({buffer:x.buffer,filename:D,mimeType:x.mime})}else we("No image found in clipboard. Copy an image first.")}catch(x){let D=x instanceof Error?x.message:"Failed to read clipboard";we(`Clipboard error: ${D}`)}finally{ft(!1)}}},[ht,we,yt,h.status,B,le.length]),{suggestions:kt,suggestionIndex:xt,showSuggestions:Ee,argMode:he,argItems:Ye,argIndex:bt,selectedConnectorIds:Xt,selectedCapabilities:Et,deleteConfirmMode:Zt,handleInputChange:v,handleSubmit:g}=rs({input:F,setInput:re,chatId:Y,setChatId:$e,currentChatTitle:j,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:W,setActiveConnectorIds:ne,sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:be,setImageGeneration:nt,chart:st,setChart:Le,fileSystem:rt,setFileSystem:Co,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:L,hasPersistedChat:N,setHasPersistedChat:R,setMessages:K,addSystemMessage:we,startNewChat:Yt,sendMessage:qe,setFullOutput:ie,credentials:M,setCredentials:E,setState:b,defaultCapabilities:{sandbox:i,webSearch:a,imageGeneration:l,chart:d,fileSystem:k},capabilityLabelMap:zt,hasUploadingFiles:$o});if(Jo((x,D)=>{(D.ctrl||D.meta)&&x==="v"&&wt()},{isActive:h.status==="ready"&&!he}),Jo((x,D)=>{if(!D.escape)return;let me=Date.now(),J=S.current;S.current=me,!(!J||me-J>Gr)&&(he||Ee||(S.current=null,Ge&&qt(),F.length>0&&v("")))},{isActive:h.status==="ready"}),Jo((x,D)=>{D.return&&(Yt("Started a new chat."),b({status:"ready"}))},{isActive:h.status==="error"}),po(()=>{if(M&&!B&&h.status==="loading")if(!Z&&!de){let x=oe.getDefaultModel(),D=x&&Q.some(J=>J.id===x),me=D?x:Q[0]?.id;me?(D||oe.setDefaultModel(me),q(me),b({status:"ready"})):pe.length===0?b({status:"no-model"}):b({status:"ready"})}else b({status:"ready"})},[M,B,Z,de,Q,pe,h.status,q,b]),po(()=>{o&&M&&h.status==="ready"&&qe(o)},[M,o]),h.status==="loading")return ue(Ae,{flexDirection:"column",children:[X(H,{children:$}),ue(Ae,{children:[X(H,{color:"cyan",children:X(Go,{type:"dots"})}),X(H,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return ue(Ae,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"Not logged in"}),X(H,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return ue(Ae,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"No workspace selected"}),X(H,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return ue(Ae,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"No model or agent specified"}),s&&X(H,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(H,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(H,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return ue(Ae,{flexDirection:"column",children:[X(H,{children:$}),ue(H,{color:"red",children:["Error: ",h.message]}),X(H,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(x=>x.name).join(", "):"none":"loading...":W&&W.length>0?ee.filter(x=>W.includes(x.id)).map(x=>x.name).join(", ")||`${W.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let x of f.capabilities)u.push(zt.get(x)??x);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),be&&u.push("Image"),st&&u.push("Chart");rt&&u.push("FileSystem");let m=G.getCurrentProfileName(),I=m!=="default";return ue(Ae,{flexDirection:"column",children:[ue(Ae,{marginBottom:1,flexDirection:"column",children:[X(H,{children:$}),ue(Ae,{children:[X(H,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),ue(H,{dimColor:!0,children:[" v","1.11.1"]}),I&&ue(H,{color:"magenta",children:[" [",m,"]"]}),X(H,{dimColor:!0,children:" (type /help for commands)"})]})]}),L.map((x,D)=>{let me=x.parts&&p?mt(x.parts,!0):x.content,J=x.role==="user"?"green":x.role==="system"?"yellow":"blue",ce=x.role==="user"?"You":x.role==="system"?"System":"Assistant";return ue(Ae,{flexDirection:"column",marginBottom:1,children:[ue(H,{bold:!0,color:J,children:[ce,":"]}),X(jo,{text:me})]},D)}),ge&&ue(Ae,{flexDirection:"column",marginBottom:1,children:[X(H,{bold:!0,color:"blue",children:"Assistant:"}),X(jo,{text:ge})]}),h.status==="ready"&&X(wn,{suggestions:kt,activeIndex:xt,visible:Ee}),h.status==="ready"&&he&&X(yn,{items:Ye,activeIndex:bt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?Xt:he==="capabilities"?Et:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),h.status==="sending"&&!ge?ue(Ae,{children:[X(H,{color:"cyan",children:X(Go,{type:"dots"})}),X(H,{children:" Thinking..."})]}):h.status==="ready"&&!he?ue(Ae,{flexDirection:"column",children:[Zt&&X(Ae,{marginBottom:1,children:X(H,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ge&&!Zt&&ue(Ae,{marginBottom:1,flexDirection:"row",gap:1,children:[X(H,{dimColor:!0,children:"Attachments:"}),We.map((x,D)=>ue(H,{children:[x.status==="uploading"?ue(H,{color:"yellow",children:[X(Go,{type:"dots"})," ",x.filename]}):x.status==="error"?ue(H,{color:"red",children:["\u2717 ",x.filename]}):ue(H,{color:"green",children:["\u2713 ",x.filename]}),D<We.length-1&&X(H,{children:", "})]},x.id))]}),ue(Ae,{children:[X(H,{color:"green",children:"> "}),X(In,{value:F,onChange:v,onSubmit:g,onPaste:at,leadingOffset:2,multiline:!0})]})]}):null,ue(Ae,{marginTop:1,flexDirection:"column",children:[ue(Ae,{gap:2,children:[ue(H,{children:[X(H,{dimColor:!0,children:"Model: "}),X(H,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(x=>x.id===Z)?.name||Z||"none"})]}),ue(H,{children:[X(H,{dimColor:!0,children:"Connectors: "}),X(H,{color:"cyan",children:c})]}),ue(H,{children:[X(H,{dimColor:!0,children:"Capabilities: "}),X(H,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(H,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Zr}from"react/jsx-runtime";async function qr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function Yr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let r=n[s-1],i;if(!r.agentId){let{messages:a}=await e.getMessages(t,o,r.id,10);i=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:r,modelId:i}}var Tt="\x1B[2m",Oe="\x1B[0m",Ho="\x1B[36m",ps="\x1B[33m",go="\x1B[32m",us="stream-json";function ds(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function ho(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
199
+ ID: ${u.id}`)}}}else if(f==="connectors"){let l=Array.from(nt);S(l.length>0?l:void 0),oe.setDefaultConnectorIds(l);let u=R.filter(m=>nt.has(m.id)).map(m=>m.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let l=Le.has("sandbox"),u=Le.has("webSearch"),m=Le.has("imageGeneration"),v=Le.has("chart"),x=Le.has("fileSystem");h(l),L(u),j(m),Y(v),F(x),oe.setCapabilities({sandbox:l,webSearch:u,imageGeneration:m,chart:v}),oe.setLocalTools({fileSystem:x});let _=[];l&&_.push("Sandbox"),u&&_.push("Web Search"),m&&_.push("Image Generation"),v&&_.push("Chart"),x&&_.push("FileSystem"),p(_.length>0?`Active capabilities: ${_.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let l=T[U];if(l){let u=Co.find(m=>m.id===l.id);u&&P&&(r(u.id),s(u.title||void 0),ge(!0),new V().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:v})=>{let x=v.filter(_=>_.role==="user"||_.role==="assistant").map(_=>({role:_.role,content:mt(_.parts,!1),parts:_.parts})).filter(_=>_.content).toReversed();D(x),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let l=T[U];if(l){let u=G.getCurrentProfileName();l.id!==u?(G.setOverrideProfile(l.id),G.setCurrentProfile(l.id),he(l.id),Ye(),ie(`Switched to profile: ${l.name}`)):p(`Already using profile: ${l.name}`)}}w(null),te([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let l=T[U];l&&(f==="connectors"?rt:st)(m=>{let v=new Set(m);return v.has(l.id)?v.delete(l.id):v.add(l.id),v});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?rt:st)(new Set(T.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?rt:st)(new Set);return}return}if(ne&&q.length>0){if(g.upArrow){B(l=>l<=0?q.length-1:l-1);return}if(g.downArrow){B(l=>l>=q.length-1?0:l+1);return}if(g.escape){O(!1),de([]);return}if(g.tab){Et(Te);return}}if(g.upArrow){if(e.includes(`
200
+ `)||it.length===0)return;if(Ge===null){yt(e);let u=it.length-1;qe(u),t(it[u]);return}let l=Math.max(0,Ge-1);qe(l),t(it[l]);return}if(g.downArrow){if(e.includes(`
201
+ `)||Ge===null)return;if(Ge>=it.length-1){qe(null),t(Yt);return}let l=Ge+1;qe(l),t(it[l])}}),{suggestions:q,suggestionIndex:Te,showSuggestions:ne,argMode:f,argItems:T,argIndex:U,selectedConnectorIds:nt,selectedCapabilities:Le,deleteConfirmMode:at,handleInputChange:Xt,handleSubmit:Zt}}import{useCallback as Wt,useRef as Fs,useState as js}from"react";function ir({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:r,onUploadError:n}){let[s,i]=js([]),a=Fs(0),c=Wt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let b of o)if(b.models.some(K=>K.id===h))return b.id;return o[0]?.id}},[o]),d=Wt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let b=t?c(t):o[0]?.id;if(!b){n?.(h.filename,"No model provider available");return}let L=`file-${++a.current}`;i(K=>[...K,{id:L,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let j=await new V().uploadFile(e.accessToken,e.workspaceId,h,b);i(se=>se.map(Y=>Y.id===L?{...Y,status:"uploaded",fileId:j.id}:Y)),r?.(h.filename)}catch(K){let j=K instanceof Error?K.message:"Upload failed";i(se=>se.map(Y=>Y.id===L?{...Y,status:"error",error:j}:Y)),n?.(h.filename,j)}},[e,t,c,o,r,n]),k=Wt(h=>{i(b=>b.filter(L=>L.id!==h))},[]),C=Wt(()=>{i([])},[]),$=Wt(()=>s.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[s]),S=s.some(h=>h.status==="uploading"),y=s.length>0;return{pendingFiles:s,addFile:d,removeFile:k,clearFiles:C,getUploadedFileIds:$,hasUploadingFiles:S,hasFiles:y}}import{jsx as X,jsxs as ue}from"react/jsx-runtime";var Ws=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Ms=[Bo,Bo,jo,jo,pt,pt,pt,pt],lr=Ws.map((e,t)=>`${Ms[t]??pt}${e}${re}`).join(`
202
+ `),Js=`${pt}EntryDesk${re}`,Gs=500;function Vs(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let r=e.charCodeAt(o);if(r>=64&&r<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Hs(e){let t=Vs(e);return Math.max(...t.split(`
203
+ `).map(o=>o.length))}function Ks(e){let t=Hs(lr);return e>=t?lr:Js}function cr({agentId:e,model:t,message:o,chatId:r,chatTitle:n,connectorIds:s,enableSandbox:i=!0,enableWebSearch:a=!1,enableImageGeneration:c=!1,enableChart:d=!1,enableFileSystem:k=!0}){let C=process.stdout.columns??80,$=Ks(C),S=ar(null),y=Wn(r,n),{state:h,setState:b,messages:L,setMessages:K,input:j,setInput:se,chatId:Y,setChatId:$e,currentChatTitle:F,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:R,credentials:W,setCredentials:E,currentResponse:ge,setCurrentResponse:D,fullOutput:p,setFullOutput:ie,addSystemMessage:we,startNewChat:z}=y,{credentials:P}=Jn(b);po(()=>{P&&!W&&E(P)},[P,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:M}=Gn(W),{currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,activeConnectorIds:B,setActiveConnectorIds:ne}=Qn(t,e,s),O=ar(!1);po(()=>{if(!O.current){if(O.current=!0,!t&&!e){let x=oe.getDefaultModel();x&&q(x)}if(!s&&!e){let x=oe.getDefaultConnectorIds();x&&ne(x.length>0?x:void 0)}}},[t,e,s,q,ne]);let{currentAgentDetails:f}=Zn(de,W),{sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:be,setImageGeneration:nt,chart:rt,setChart:Le,fileSystem:st,setFileSystem:Co,capabilityLabelMap:zt}=Xn(i,a,c,d,k),{pendingFiles:Be,addFile:ht,removeFile:ze,clearFiles:qt,getUploadedFileIds:it,hasUploadingFiles:$o,hasFiles:Ge}=ir({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:x=>{we(`\u2713 Attached: ${x}`)},onUploadError:(x,_)=>{we(`\u2717 Failed to upload ${x}: ${_}`)}}),{sendMessage:qe}=Kn({chatId:Y,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:B,sandbox:w,webSearch:te,imageGeneration:be,chart:rt,localTools:st,fullOutput:p,setMessages:K,setState:b,setCurrentResponse:D,setCredentials:E,setHasPersistedChat:R,getFileIds:it,clearFiles:qt}),Yt=Vo(x=>{z(x),D("")},[z]),[yt,ft]=Bs(!1),at=Vo(async x=>{let _=x.text.trim(),me=co(_);if(/^https?:\/\//.test(me))return;if(await Un(_)&&Rn(me)){let ce=await Fn(_);ce&&(x.preventDefault(),await ht(ce))}},[ht]),wt=Vo(async()=>{if(!(yt||h.status!=="ready")){if(M||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),ft(!0);try{let x=await Ln();if(x){let _=`clipboard-${Date.now()}.png`;we(`Uploading: ${_} (${Math.round(x.buffer.length/1024)}KB)`),await ht({buffer:x.buffer,filename:_,mimeType:x.mime})}else we("No image found in clipboard. Copy an image first.")}catch(x){let _=x instanceof Error?x.message:"Failed to read clipboard";we(`Clipboard error: ${_}`)}finally{ft(!1)}}},[ht,we,yt,h.status,M,le.length]),{suggestions:kt,suggestionIndex:xt,showSuggestions:Ee,argMode:he,argItems:Ye,argIndex:bt,selectedConnectorIds:Xt,selectedCapabilities:Et,deleteConfirmMode:Zt,handleInputChange:I,handleSubmit:g}=sr({input:j,setInput:se,chatId:Y,setChatId:$e,currentChatTitle:F,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:q,currentAgentId:de,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:B,setActiveConnectorIds:ne,sandbox:w,setSandbox:T,webSearch:te,setWebSearch:U,imageGeneration:be,setImageGeneration:nt,chart:rt,setChart:Le,fileSystem:st,setFileSystem:Co,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:L,hasPersistedChat:N,setHasPersistedChat:R,setMessages:K,addSystemMessage:we,startNewChat:Yt,sendMessage:qe,setFullOutput:ie,credentials:W,setCredentials:E,setState:b,defaultCapabilities:{sandbox:i,webSearch:a,imageGeneration:c,chart:d,fileSystem:k},capabilityLabelMap:zt,hasUploadingFiles:$o});if(Jo((x,_)=>{(_.ctrl||_.meta)&&x==="v"&&wt()},{isActive:h.status==="ready"&&!he}),Jo((x,_)=>{if(!_.escape)return;let me=Date.now(),J=S.current;S.current=me,!(!J||me-J>Gs)&&(he||Ee||(S.current=null,Ge&&qt(),j.length>0&&I("")))},{isActive:h.status==="ready"}),Jo((x,_)=>{_.return&&(Yt("Started a new chat."),b({status:"ready"}))},{isActive:h.status==="error"}),po(()=>{if(W&&!M&&h.status==="loading")if(!Z&&!de){let x=oe.getDefaultModel(),_=x&&Q.some(J=>J.id===x),me=_?x:Q[0]?.id;me?(_||oe.setDefaultModel(me),q(me),b({status:"ready"})):pe.length===0?b({status:"no-model"}):b({status:"ready"})}else b({status:"ready"})},[W,M,Z,de,Q,pe,h.status,q,b]),po(()=>{o&&W&&h.status==="ready"&&qe(o)},[W,o]),h.status==="loading")return ue(Pe,{flexDirection:"column",children:[X(H,{children:$}),ue(Pe,{children:[X(H,{color:"cyan",children:X(Go,{type:"dots"})}),X(H,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return ue(Pe,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"Not logged in"}),X(H,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return ue(Pe,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"No workspace selected"}),X(H,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return ue(Pe,{flexDirection:"column",children:[X(H,{children:$}),X(H,{color:"yellow",children:"No model or agent specified"}),r&&X(H,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(H,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(H,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return ue(Pe,{flexDirection:"column",children:[X(H,{children:$}),ue(H,{color:"red",children:["Error: ",h.message]}),X(H,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let l=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(x=>x.name).join(", "):"none":"loading...":B&&B.length>0?ee.filter(x=>B.includes(x.id)).map(x=>x.name).join(", ")||`${B.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let x of f.capabilities)u.push(zt.get(x)??x);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),be&&u.push("Image"),rt&&u.push("Chart");st&&u.push("FileSystem");let m=G.getCurrentProfileName(),v=m!=="default";return ue(Pe,{flexDirection:"column",children:[ue(Pe,{marginBottom:1,flexDirection:"column",children:[X(H,{children:$}),ue(Pe,{children:[X(H,{bold:!0,color:"cyan",children:F?`Continuing: ${F}`:"EntryDesk CLI"}),ue(H,{dimColor:!0,children:[" v","1.11.3"]}),v&&ue(H,{color:"magenta",children:[" [",m,"]"]}),X(H,{dimColor:!0,children:" (type /help for commands)"})]})]}),L.map((x,_)=>{let me=x.parts&&p?mt(x.parts,!0):x.content,J=x.role==="user"?"green":x.role==="system"?"yellow":"blue",ce=x.role==="user"?"You":x.role==="system"?"System":"Assistant";return ue(Pe,{flexDirection:"column",marginBottom:1,children:[ue(H,{bold:!0,color:J,children:[ce,":"]}),X(Fo,{text:me})]},_)}),ge&&ue(Pe,{flexDirection:"column",marginBottom:1,children:[X(H,{bold:!0,color:"blue",children:"Assistant:"}),X(Fo,{text:ge})]}),h.status==="ready"&&X(wn,{suggestions:kt,activeIndex:xt,visible:Ee}),h.status==="ready"&&he&&X(yn,{items:Ye,activeIndex:bt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?Xt:he==="capabilities"?Et:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),h.status==="sending"&&!ge?ue(Pe,{children:[X(H,{color:"cyan",children:X(Go,{type:"dots"})}),X(H,{children:" Thinking..."})]}):h.status==="ready"&&!he?ue(Pe,{flexDirection:"column",children:[Zt&&X(Pe,{marginBottom:1,children:X(H,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ge&&!Zt&&ue(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[X(H,{dimColor:!0,children:"Attachments:"}),Be.map((x,_)=>ue(H,{children:[x.status==="uploading"?ue(H,{color:"yellow",children:[X(Go,{type:"dots"})," ",x.filename]}):x.status==="error"?ue(H,{color:"red",children:["\u2717 ",x.filename]}):ue(H,{color:"green",children:["\u2713 ",x.filename]}),_<Be.length-1&&X(H,{children:", "})]},x.id))]}),ue(Pe,{children:[X(H,{color:"green",children:"> "}),X(In,{value:j,onChange:I,onSubmit:g,onPaste:at,leadingOffset:2,multiline:!0})]})]}):null,ue(Pe,{marginTop:1,flexDirection:"column",children:[ue(Pe,{gap:2,children:[ue(H,{children:[X(H,{dimColor:!0,children:"Model: "}),X(H,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(x=>x.id===Z)?.name||Z||"none"})]}),ue(H,{children:[X(H,{dimColor:!0,children:"Connectors: "}),X(H,{color:"cyan",children:l})]}),ue(H,{children:[X(H,{dimColor:!0,children:"Capabilities: "}),X(H,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(H,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Zs}from"react/jsx-runtime";async function qs(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function Ys(e,t,o,r){if(r<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(r>n.length)return console.error(`Chat number ${r} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let s=n[r-1],i;if(!s.agentId){let{messages:a}=await e.getMessages(t,o,s.id,10);i=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:s,modelId:i}}var Tt="\x1B[2m",Oe="\x1B[0m",Ho="\x1B[36m",pr="\x1B[33m",go="\x1B[32m",ur="stream-json";function dr(e,t,o,r){e&&t&&(console.error(`Error: Cannot use both ${o} and ${r}`),process.exit(1))}function ho(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
204
204
  `)}function yo(e,t){if(t)return e;let o=e.split(`
205
- `);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),r=o.length-10;return[...s,`${Tt}... (${r} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
206
- `)}function Xr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function fs(e,t){if(!e)return"(no result)";if(typeof e!="object")return yo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${ps}[stderr]${Oe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),yo(n.join(`
207
- `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
208
- `);return yo(n||JSON.stringify(e,null,2),t)}return yo(JSON.stringify(e,null,2),t)}async function ms(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){ke(ee)}let s=e.output===us;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${us}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),r=oe.getDefaultModel(),i=e.message;!i&&!process.stdin.isTTY&&(i=await qr());let a=new V;async function l(){if(!r)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),r=Q}catch{}}let d,k,C,$;if(e.continue){let ee=await Yr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,k=ee.chat.title??void 0,C=ee.chat.agentId??void 0,$=ee.modelId;let Q=e.agentId||e.model||C||$||r;!Q&&!e.interactive&&(await l(),Q=e.agentId||e.model||C||$||r),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
205
+ `);if(o.length<=20)return e;let r=o.slice(0,5),n=o.slice(-5),s=o.length-10;return[...r,`${Tt}... (${s} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
206
+ `)}function Xs(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function fr(e,t){if(!e)return"(no result)";if(typeof e!="object")return yo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let r=o.structuredContent,n=[];if(r.stdout&&typeof r.stdout=="string"&&r.stdout.trim()&&n.push(r.stdout.trim()),r.stderr&&typeof r.stderr=="string"&&r.stderr.trim()&&n.push(`${pr}[stderr]${Oe} ${r.stderr.trim()}`),r.urls&&Array.isArray(r.urls)){let s=r.urls;for(let i of s)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(r,null,2)),yo(n.join(`
207
+ `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(s=>s.type==="text"&&s.text).map(s=>s.text).join(`
208
+ `);return yo(n||JSON.stringify(e,null,2),t)}return yo(JSON.stringify(e,null,2),t)}async function mr(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){ke(ee)}let r=e.output===ur;e.output&&!r&&(console.error(`Invalid --output value. Supported: ${ur}`),process.exit(1));let n=!r&&(e.plain||!process.stdout.isTTY),s=oe.getDefaultModel(),i=e.message;!i&&!process.stdin.isTTY&&(i=await qs());let a=new V;async function c(){if(!s)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),s=Q}catch{}}let d,k,C,$;if(e.continue){let ee=await Ys(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,k=ee.chat.title??void 0,C=ee.chat.agentId??void 0,$=ee.modelId;let Q=e.agentId||e.model||C||$||s;!Q&&!e.interactive&&(await c(),Q=e.agentId||e.model||C||$||s),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
209
209
  Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
210
- `)}let S=e.agentId||C,y=e.model||$||r||void 0;!S&&!y&&(await l(),y=e.model||$||r||void 0),ds(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),ds(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let h=oe.getCapabilities(),b=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,L=e.webSearch??h?.webSearch??!1,K=e.imageGen??h?.imageGeneration??!1,F=e.chart??h?.chart??!1,re=oe.getDefaultConnectorIds(),Y=e.connectors??re??void 0,$e=oe.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:$e?.fileSystem??!0;if(e.interactive){zr(Zr(cs,{agentId:S,model:y,message:e.message,chatId:d,chatTitle:k??void 0,connectorIds:Y,enableSandbox:b,enableWebSearch:L,enableImageGeneration:K,enableChart:F,enableFileSystem:j}),{exitOnCtrlC:!1});return}let A=!e.continue&&!y&&!S;(!i||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||mo(),M=j?eo():void 0,E=j?to():void 0,ge=[],_=mo(),p=(ee,Q,pe)=>{let le={id:R};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),S?le.agentId=S:(y&&(le.model=y),le.connectorIds=Y??[],le.enableSandbox=b,le.enableWebSearch=L,le.enableImageGeneration=K,le.enableChart=F),M&&(le.clientTools=M),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},ie=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",B=new Map,Z=[],q=[];for(;;){let{done:de,value:Te}=await Q.read();if(de)break;le+=pe.decode(Te,{stream:!0});let W=le.split(`
211
- `);le=W.pop()||"";for(let ne of W){let O=ne.trimEnd();if(O==="data: [DONE]"){s&&ho("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&q.push(f),s){f.type==="text-delta"&&f.delta!==void 0?ho("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ho("reasoning-delta",f.delta):ho(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),j&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&et(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${Tt}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
210
+ `)}let S=e.agentId||C,y=e.model||$||s||void 0;!S&&!y&&(await c(),y=e.model||$||s||void 0),dr(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),dr(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let h=oe.getCapabilities(),b=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,L=e.webSearch??h?.webSearch??!1,K=e.imageGen??h?.imageGeneration??!1,j=e.chart??h?.chart??!1,se=oe.getDefaultConnectorIds(),Y=e.connectors??se??void 0,$e=oe.getLocalTools(),F=e.noFileSystem?!1:e.fileSystem?!0:$e?.fileSystem??!0;if(e.interactive){zs(Zs(cr,{agentId:S,model:y,message:e.message,chatId:d,chatTitle:k??void 0,connectorIds:Y,enableSandbox:b,enableWebSearch:L,enableImageGeneration:K,enableChart:j,enableFileSystem:F}),{exitOnCtrlC:!1});return}let A=!e.continue&&!y&&!S;(!i||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||mo(),W=F?eo():void 0,E=F?to():void 0,ge=[],D=mo(),p=(ee,Q,pe)=>{let le={id:R};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),S?le.agentId=S:(y&&(le.model=y),le.connectorIds=Y??[],le.enableSandbox=b,le.enableWebSearch=L,le.enableImageGeneration=K,le.enableChart=j),W&&(le.clientTools=W),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},ie=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",M=new Map,Z=[],q=[];for(;;){let{done:de,value:Te}=await Q.read();if(de)break;le+=pe.decode(Te,{stream:!0});let B=le.split(`
211
+ `);le=B.pop()||"";for(let ne of B){let O=ne.trimEnd();if(O==="data: [DONE]"){r&&ho("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&q.push(f),r){f.type==="text-delta"&&f.delta!==void 0?ho("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ho("reasoning-delta",f.delta):ho(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),F&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&et(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${Tt}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
212
212
 
213
- `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){B.set(f.toolCallId,{toolName:f.toolName});let T=j&&et(f.toolName)?`${go}[LOCAL]${Oe} `:"";console.log(`
214
- ${Ho}\u250C\u2500 ${T}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},T=Xr(w);console.log(`${ps}\u2502 Arguments:${Oe}`);for(let te of T.split(`
215
- `))console.log(`${Tt}\u2502 ${te}${Oe}`);j&&et(f.toolName)&&(B.set(f.toolCallId,{toolName:f.toolName,args:w}),Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=B.get(f.toolCallId),T=fs(f.result,N);console.log(`${go}\u2502 Result:${Oe}`);for(let te of T.split(`
213
+ `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let T=F&&et(f.toolName)?`${go}[LOCAL]${Oe} `:"";console.log(`
214
+ ${Ho}\u250C\u2500 ${T}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},T=Xs(w);console.log(`${pr}\u2502 Arguments:${Oe}`);for(let te of T.split(`
215
+ `))console.log(`${Tt}\u2502 ${te}${Oe}`);F&&et(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),T=fr(f.result,N);console.log(`${go}\u2502 Result:${Oe}`);for(let te of T.split(`
216
216
  `))console.log(`${Tt}\u2502 ${te}${Oe}`);console.log(`${Ho}\u2514\u2500 ${w?.toolName||"Tool"} completed${Oe}
217
- `),B.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${Tt}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:q}},we=p({id:mo(),text:i}),z=await a.chat(t,o,we),P=await ie(z);for(ge=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let B of P.pendingClientTools){!n&&!s&&console.log(`${go}\u2502 Executing locally...${Oe}`);let Z=await oo(B.toolName,B.args),q=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:B.toolCallId,toolName:B.toolName,content:[{type:"text",text:q}],isError:!Z.success}),!n&&!s){let de=fs(Z.success?Z.result:{error:Z.error},N);console.log(`${go}\u2502 Result:${Oe}`);for(let Te of de.split(`
218
- `))console.log(`${Tt}\u2502 ${Te}${Oe}`);console.log(`${Ho}\u2514\u2500 ${B.toolName} completed${Oe}
219
- `)}}let Q=ge.map(B=>{if(B.type==="tool-call"){let Z=ee.find(de=>de.toolCallId===B.toolCallId),q=Z?.content.filter(de=>de.type==="text").map(de=>de.text).join(`
220
- `);return{type:"tool-invocation",toolCallId:B.toolCallId,toolName:B.toolName,args:B.args,state:Z?.isError?"output-error":"output-available",output:q}}return B}),pe=[{id:_,role:"assistant",parts:Q}];_=mo();let le=p(void 0,ee,pe);z=await a.chat(t,o,le),P=await ie(z),ge=P.messageParts}s||console.log("")}var Bt="\x1B[2m",Pe="\x1B[0m",dt="\x1B[36m",zo="\x1B[33m",gs="\x1B[32m",hs="stream-json";function Ke(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
221
- `)}function Ko(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function wo(e,t){if(t)return e;let o=e.split(`
222
- `);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),r=o.length-10;return[...s,`... (${r} lines omitted, use --full-output to see all) ...`,...n].join(`
223
- `)}function qo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(qo);let t={};for(let[o,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[o]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[o]=qo(s):t[o]=s;return t}function ys(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ws(e,t){if(!e)return"(no result)";if(typeof e!="object")return wo(String(e),t);let o=t?e:qo(e);if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${zo}[stderr]${Pe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),wo(n.join(`
224
- `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
225
- `);return wo(n||JSON.stringify(e,null,2),t)}return wo(JSON.stringify(e,null,2),t)}function Qr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function ks(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Bt}${s.text}${Pe}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${dt}\u250C\u2500 Tool Call: ${s.toolName}${Pe}`),s.args){n.push(`${zo}\u2502 Arguments:${Pe}`);let r=ys(s.args);for(let i of r.split(`
226
- `))n.push(`${Bt}\u2502 ${i}${Pe}`)}if(s.result!==void 0){n.push(`${gs}\u2502 Result:${Pe}`);let r=ws(s.result,t);for(let i of r.split(`
227
- `))n.push(`${Bt}\u2502 ${i}${Pe}`);n.push(`${dt}\u2514\u2500 ${s.toolName} completed${Pe}`)}else s.state==="call"?n.push(`${dt}\u2514\u2500 (awaiting result)${Pe}`):n.push(`${dt}\u2514\u2500${Pe}`);o.push(n.join(`
228
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Qr(s),r=[];if(r.push(`${dt}\u250C\u2500 Tool: ${n}${Pe}`),s.input){r.push(`${zo}\u2502 Input:${Pe}`);let i=ys(s.input);for(let a of i.split(`
229
- `))r.push(`${Bt}\u2502 ${a}${Pe}`)}if(s.output!==void 0&&s.state==="output-available"){r.push(`${gs}\u2502 Output:${Pe}`);let i=ws(s.output,t);for(let a of i.split(`
230
- `))r.push(`${Bt}\u2502 ${a}${Pe}`);r.push(`${dt}\u2514\u2500 completed${Pe}`)}else s.state==="call"||s.state==="partial-call"?r.push(`${dt}\u2514\u2500 (in progress)${Pe}`):r.push(`${dt}\u2514\u2500${Pe}`);o.push(r.join(`
217
+ `),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${Tt}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:q}},we=p({id:mo(),text:i}),z=await a.chat(t,o,we),P=await ie(z);for(ge=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let M of P.pendingClientTools){!n&&!r&&console.log(`${go}\u2502 Executing locally...${Oe}`);let Z=await oo(M.toolName,M.args),q=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:q}],isError:!Z.success}),!n&&!r){let de=fr(Z.success?Z.result:{error:Z.error},N);console.log(`${go}\u2502 Result:${Oe}`);for(let Te of de.split(`
218
+ `))console.log(`${Tt}\u2502 ${Te}${Oe}`);console.log(`${Ho}\u2514\u2500 ${M.toolName} completed${Oe}
219
+ `)}}let Q=ge.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(`
220
+ `);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=mo();let le=p(void 0,ee,pe);z=await a.chat(t,o,le),P=await ie(z),ge=P.messageParts}r||console.log("")}var Mt="\x1B[2m",Ae="\x1B[0m",dt="\x1B[36m",zo="\x1B[33m",gr="\x1B[32m",hr="stream-json";function Ke(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
221
+ `)}function Ko(e){let t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function wo(e,t){if(t)return e;let o=e.split(`
222
+ `);if(o.length<=15)return e;let r=o.slice(0,6),n=o.slice(-4),s=o.length-10;return[...r,`... (${s} lines omitted, use --full-output to see all) ...`,...n].join(`
223
+ `)}function qo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(qo);let t={};for(let[o,r]of Object.entries(e))typeof r=="string"&&r.length>200?t[o]=r.slice(0,150)+"... (truncated)":typeof r=="object"&&r!==null?t[o]=qo(r):t[o]=r;return t}function yr(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function wr(e,t){if(!e)return"(no result)";if(typeof e!="object")return wo(String(e),t);let o=t?e:qo(e);if("structuredContent"in o&&o.structuredContent){let r=o.structuredContent,n=[];if(r.stdout&&typeof r.stdout=="string"&&r.stdout.trim()&&n.push(r.stdout.trim()),r.stderr&&typeof r.stderr=="string"&&r.stderr.trim()&&n.push(`${zo}[stderr]${Ae} ${r.stderr.trim()}`),r.urls&&Array.isArray(r.urls)){let s=r.urls;for(let i of s)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(r,null,2)),wo(n.join(`
224
+ `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(s=>s.type==="text"&&s.text).map(s=>s.text).join(`
225
+ `);return wo(n||JSON.stringify(e,null,2),t)}return wo(JSON.stringify(e,null,2),t)}function Qs(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 kr(e,t){let o=[];for(let r of e)if(r.type==="reasoning"&&r.text)o.push(`${Mt}${r.text}${Ae}`);else if(r.type==="text"&&r.text)o.push(r.text);else if(r.type==="tool-call"&&r.toolName){let n=[];if(n.push(`${dt}\u250C\u2500 Tool Call: ${r.toolName}${Ae}`),r.args){n.push(`${zo}\u2502 Arguments:${Ae}`);let s=yr(r.args);for(let i of s.split(`
226
+ `))n.push(`${Mt}\u2502 ${i}${Ae}`)}if(r.result!==void 0){n.push(`${gr}\u2502 Result:${Ae}`);let s=wr(r.result,t);for(let i of s.split(`
227
+ `))n.push(`${Mt}\u2502 ${i}${Ae}`);n.push(`${dt}\u2514\u2500 ${r.toolName} completed${Ae}`)}else r.state==="call"?n.push(`${dt}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${dt}\u2514\u2500${Ae}`);o.push(n.join(`
228
+ `))}else if(r.type.startsWith("tool-")&&r.type!=="tool-call"){let n=Qs(r),s=[];if(s.push(`${dt}\u250C\u2500 Tool: ${n}${Ae}`),r.input){s.push(`${zo}\u2502 Input:${Ae}`);let i=yr(r.input);for(let a of i.split(`
229
+ `))s.push(`${Mt}\u2502 ${a}${Ae}`)}if(r.output!==void 0&&r.state==="output-available"){s.push(`${gr}\u2502 Output:${Ae}`);let i=wr(r.output,t);for(let a of i.split(`
230
+ `))s.push(`${Mt}\u2502 ${a}${Ae}`);s.push(`${dt}\u2514\u2500 completed${Ae}`)}else r.state==="call"||r.state==="partial-call"?s.push(`${dt}\u2514\u2500 (in progress)${Ae}`):s.push(`${dt}\u2514\u2500${Ae}`);o.push(s.join(`
231
231
  `))}return o.join(`
232
232
 
233
- `).trim()}async function xs(e){let t=e.output===hs;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${hs}`),process.exit(1));let o=new V;if(e.shareId){let i;try{i=await ct()}catch{}try{let a=await o.getSharedChat(e.shareId,i),{messages:l}=await o.getSharedMessages(e.shareId,50,i);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(Ke("chat",a),l.length===0)Ke("info","No messages in this shared chat.");else for(let C of l.toReversed())Ke("message",C);Ke("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
234
- `),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),k=e.fullOutput??!1;for(let C of d){let $=ks(C.parts,k);if(!$)continue;let S=C.role==="user"?"You":"Assistant";console.log(`[${S}] ${Ko(C.createdAt)}`),console.log($),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let i=await fe();s=i.accessToken,n=i.workspaceId}catch(i){ke(i)}if(e.chatId){let i=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let y=d===0?1:d,{chats:h}=await o.getChats(s,n,20);y>h.length&&(console.error(`Chat number ${y} not found. You have ${h.length} recent chats.`),process.exit(1));let b=h[y-1];i=b.id,a=!0,l=b,t||console.log(`Chat: ${b.title||"Untitled"}
235
- `)}let{messages:C}=await o.getMessages(s,n,i,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(l&&Ke("chat",l),C.length===0)Ke("info","No messages in this chat.");else for(let y of C.toReversed())Ke("message",y);Ke("done");return}if(C.length===0){console.log("No messages in this chat.");return}let $=C.toReversed(),S=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
236
- `);for(let y of $){let h=ks(y.parts,S);if(!h)continue;let b=y.role==="user"?"You":"Assistant";console.log(`[${b}] ${Ko(y.createdAt)}`),console.log(h),console.log("")}return}let{chats:r}=await o.getChats(s,n,20);if(t){for(let i of r)Ke("chat",i);Ke("done");return}if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${r.length}):
237
- `),r.forEach((i,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${Ko(i.createdAt).padEnd(12)} ${i.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as ei,Text as Ne}from"ink";import{jsx as Ue,jsxs as It}from"react/jsx-runtime";var vt=["apiUrl","hubUrl"];function Yo(e){return vt.includes(e)}async function bs(e){let t=e.action||"list",o=e.configKey,s=e.value,n=G.getEffectiveProfileName();if(t==="list"){let r=oe.getAll(),i=Object.entries(r);if(e.json){console.log(JSON.stringify(r));return}if(console.log(`Profile: ${n}`),i.length===0){console.log("No configuration set."),console.log(`Available keys: ${vt.join(", ")}`);return}console.log(`Configuration:
238
- `);for(let[a,l]of i)console.log(` ${a}=${l}`);console.log(`
239
- Available keys: ${vt.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1));let r=oe.get(o);e.json?console.log(JSON.stringify({[o]:r??null})):console.log(r||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function Cs(){let e=Ze();return It(ei,{flexDirection:"column",children:[Ue(Ne,{bold:!0,children:"entrydesk config"}),Ue(Ne,{children:" "}),Ue(Ne,{children:"Manage CLI configuration"}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Usage:"}),Ue(Ne,{children:" entrydesk config List all configuration"}),It(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),It(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),It(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Available keys:"}),It(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),It(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Examples:"}),Ue(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),Ue(Ne,{children:" entrydesk config get apiUrl"}),Ue(Ne,{children:" entrydesk config unset apiUrl"})]})}async function $s(e){try{let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new V,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
240
- `);for(let r of n){let i=r.connected?"connected":"disconnected";console.log(` ${r.name} (${i})`),console.log(` Provider: ${r.provider}`),console.log(` ID: ${r.id}`),console.log("")}}catch(t){ke(t)}}function ko(){console.log(`
233
+ `).trim()}async function xr(e){let t=e.output===hr;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${hr}`),process.exit(1));let o=new V;if(e.shareId){let i;try{i=await ct()}catch{}try{let a=await o.getSharedChat(e.shareId,i),{messages:c}=await o.getSharedMessages(e.shareId,50,i);if(e.json){console.log(JSON.stringify({chat:a,messages:c}));return}if(t){if(Ke("chat",a),c.length===0)Ke("info","No messages in this shared chat.");else for(let C of c.toReversed())Ke("message",C);Ke("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${c.length} messages
234
+ `),c.length===0){console.log("No messages in this shared chat.");return}let d=c.toReversed(),k=e.fullOutput??!1;for(let C of d){let $=kr(C.parts,k);if(!$)continue;let S=C.role==="user"?"You":"Assistant";console.log(`[${S}] ${Ko(C.createdAt)}`),console.log($),console.log("")}return}catch(a){if(a instanceof Error){let 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 r,n;try{let i=await fe();r=i.accessToken,n=i.workspaceId}catch(i){ke(i)}if(e.chatId){let i=e.chatId,a=!1,c=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let y=d===0?1:d,{chats:h}=await o.getChats(r,n,20);y>h.length&&(console.error(`Chat number ${y} not found. You have ${h.length} recent chats.`),process.exit(1));let b=h[y-1];i=b.id,a=!0,c=b,t||console.log(`Chat: ${b.title||"Untitled"}
235
+ `)}let{messages:C}=await o.getMessages(r,n,i,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(c&&Ke("chat",c),C.length===0)Ke("info","No messages in this chat.");else for(let y of C.toReversed())Ke("message",y);Ke("done");return}if(C.length===0){console.log("No messages in this chat.");return}let $=C.toReversed(),S=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
236
+ `);for(let y of $){let h=kr(y.parts,S);if(!h)continue;let b=y.role==="user"?"You":"Assistant";console.log(`[${b}] ${Ko(y.createdAt)}`),console.log(h),console.log("")}return}let{chats:s}=await o.getChats(r,n,20);if(t){for(let i of s)Ke("chat",i);Ke("done");return}if(e.json){console.log(JSON.stringify(s));return}if(s.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${s.length}):
237
+ `),s.forEach((i,a)=>{let c=(a+1).toString().padStart(2," ");console.log(` ${c}. ${Ko(i.createdAt).padEnd(12)} ${i.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as ei,Text as Ne}from"ink";import{jsx as Ue,jsxs as It}from"react/jsx-runtime";var vt=["apiUrl","hubUrl"];function Yo(e){return vt.includes(e)}async function br(e){let t=e.action||"list",o=e.configKey,r=e.value,n=G.getEffectiveProfileName();if(t==="list"){let s=oe.getAll(),i=Object.entries(s);if(e.json){console.log(JSON.stringify(s));return}if(console.log(`Profile: ${n}`),i.length===0){console.log("No configuration set."),console.log(`Available keys: ${vt.join(", ")}`);return}console.log(`Configuration:
238
+ `);for(let[a,c]of i)console.log(` ${a}=${c}`);console.log(`
239
+ Available keys: ${vt.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1));let s=oe.get(o);e.json?console.log(JSON.stringify({[o]:s??null})):console.log(s||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1)),r||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,r),console.log(`Set ${o}=${r}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Yo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${vt.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function Cr(){let e=Ze();return It(ei,{flexDirection:"column",children:[Ue(Ne,{bold:!0,children:"entrydesk config"}),Ue(Ne,{children:" "}),Ue(Ne,{children:"Manage CLI configuration"}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Usage:"}),Ue(Ne,{children:" entrydesk config List all configuration"}),It(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),It(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),It(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Available keys:"}),It(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),It(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Ue(Ne,{children:" "}),Ue(Ne,{bold:!0,children:"Examples:"}),Ue(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),Ue(Ne,{children:" entrydesk config get apiUrl"}),Ue(Ne,{children:" entrydesk config unset apiUrl"})]})}async function $r(e){try{let t,o;try{let s=await fe();t=s.accessToken,o=s.workspaceId}catch(s){let i=s instanceof Error?s.message:"Authentication failed";console.error(i),process.exit(1)}let r=new V,{connectors:n}=await r.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
240
+ `);for(let s of n){let i=s.connected?"connected":"disconnected";console.log(` ${s.name} (${i})`),console.log(` Provider: ${s.provider}`),console.log(` ID: ${s.id}`),console.log("")}}catch(t){ke(t)}}function ko(){console.log(`
241
241
  EntryDesk CLI - Interact with EntryDesk from your terminal
242
242
 
243
243
  Usage: entrydesk <command> [options]
@@ -402,10 +402,10 @@ Local Development:
402
402
  $ entrydesk config set hubUrl http://localhost:3000
403
403
 
404
404
  For more information, visit https://entrydesk.com/docs/cli
405
- `)}async function Ss(e){if(process.env.DEBUG){let{getApiUrl:r,getHubUrl:i}=await import("./config-OY6KLQUX.js");console.log(`[DEBUG] Hub URL: ${i()}`),console.log(`[DEBUG] API URL: ${r()}`)}let t=await sn({onDeviceCodeReceived:(r,i)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${i}`),console.log(` 2. Enter code: ${r}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),o=new V,{workspaces:s}=await o.getWorkspaces(t.accessToken),n=s[0];await Se.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:n?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:n?.id,workspaceName:n?.name})):(console.log(`Logged in as ${t.email}`),n&&console.log(`Workspace: ${n.name}`))}async function Ts(e){try{let t=await Se.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new V().revokeOAuthToken({token:t.refreshToken,clientId:nn})}catch{}await Se.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import ti from"http";import{stderr as oi}from"process";import{Client as ni}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as si}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as ri}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ii}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ai}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as li,ListToolsRequestSchema as ci}from"@modelcontextprotocol/sdk/types.js";function Be(e){oi.write(`${e}
406
- `)}async function Is(e,t,o){let s=new ni({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),r=new si(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(r),s}function vs(e){let t=new ri({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(ci,async()=>({tools:(await(await e()).listTools()).tools})),t.setRequestHandler(li,async o=>{let{name:s,arguments:n}=o.params,i=await(await e()).callTool({name:s,arguments:n}),a=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&a.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:a,structuredContent:i.structuredContent,isError:i.isError}}),t}async function ui(e,t,o){let s=ti.createServer(async(n,r)=>{if(n.method==="OPTIONS"){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),r.writeHead(204),r.end();return}if(n.url!=="/mcp"){r.writeHead(404,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Not found"}));return}let i=vs(e),a=new ai({sessionIdGenerator:void 0});if(r.setHeader("Access-Control-Allow-Origin","*"),r.on("close",()=>{a.close(),i.close()}),await i.connect(a),n.method==="POST"){let l="";n.on("data",d=>{l+=d.toString()}),n.on("end",async()=>{try{let d=JSON.parse(l);await a.handleRequest(n,r,d)}catch{r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Invalid JSON"}))}})}else await a.handleRequest(n,r)});s.listen(o,()=>{Be(`EntryDesk MCP server running at http://localhost:${o}/mcp`),Be("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{Be(`
407
- Shutting down...`),s.close(),await t(),process.exit(0)}),process.on("SIGTERM",async()=>{s.close(),await t(),process.exit(0)})}async function di(e,t){let o=vs(e),s=new ii;s.onclose=async()=>{await t()},await o.connect(s)}async function As(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{Be("[entrydesk-mcp] Starting MCP server...");let t,o;try{let d=await fe();t=d.accessToken,o=d.workspaceId}catch(d){let k=d instanceof Error?d.message:"Authentication failed";console.error(k),process.exit(1)}let{apiUrl:s,mcp:n}=Ze();Be(`[entrydesk-mcp] Connecting to ${s}...`),Be(`[entrydesk-mcp] Workspace: ${o}`);let r=await Is(s,t,o);Be("[entrydesk-mcp] Connected to EntryDesk API");let i=null,a=async()=>rn(t)?i||(i=(async()=>{Be("[entrydesk-mcp] Token expiring soon, refreshing...");let d=await Se.getAll();if(!d?.accessToken)throw new Error("Not logged in. Please run `entrydesk login` again.");let k=await an(d);if(k!==t){t=k;try{await r.close()}catch{}r=await Is(s,t,o),Be("[entrydesk-mcp] Token refreshed, reconnected")}return r})().finally(()=>{i=null}),i):r,l=async()=>{try{await r.close()}catch{}};if(e.mode==="http"){let d=e.port??n.httpPort;await ui(a,l,d)}else Be("[entrydesk-mcp] Starting stdio server..."),await di(a,l),Be("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Ps(e){try{let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new V,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
408
- `);for(let r of n)console.log(` ${r.name}`),r.description&&console.log(` ${r.description.slice(0,80)}`),console.log(` ID: ${r.id}`),console.log("")}catch(t){ke(t)}}function fi(){console.log(`
405
+ `)}async function Sr(e){if(process.env.DEBUG){let{getApiUrl:s,getHubUrl:i}=await import("./config-VDFYOL6E.js");console.log(`[DEBUG] Hub URL: ${i()}`),console.log(`[DEBUG] API URL: ${s()}`)}let t=await rn({onDeviceCodeReceived:(s,i)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${i}`),console.log(` 2. Enter code: ${s}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),o=new V,{workspaces:r}=await o.getWorkspaces(t.accessToken),n=r[0];await Se.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:n?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:n?.id,workspaceName:n?.name})):(console.log(`Logged in as ${t.email}`),n&&console.log(`Workspace: ${n.name}`))}async function Tr(e){try{let t=await Se.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new V().revokeOAuthToken({token:t.refreshToken,clientId:nn})}catch{}await Se.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import ti from"http";import{stderr as oi}from"process";import{Client as ni}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ri}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as si}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ii}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ai}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as li,ListToolsRequestSchema as ci}from"@modelcontextprotocol/sdk/types.js";function Me(e){oi.write(`${e}
406
+ `)}async function Ir(e,t,o){let r=new ni({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),s=new ri(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await r.connect(s),r}function vr(e){let t=new si({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(ci,async()=>({tools:(await(await e()).listTools()).tools})),t.setRequestHandler(li,async o=>{let{name:r,arguments:n}=o.params,i=await(await e()).callTool({name:r,arguments:n}),a=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&a.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:a,structuredContent:i.structuredContent,isError:i.isError}}),t}async function ui(e,t,o){let r=ti.createServer(async(n,s)=>{if(n.method==="OPTIONS"){s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),s.writeHead(204),s.end();return}if(n.url!=="/mcp"){s.writeHead(404,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Not found"}));return}let i=vr(e),a=new ai({sessionIdGenerator:void 0});if(s.setHeader("Access-Control-Allow-Origin","*"),s.on("close",()=>{a.close(),i.close()}),await i.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,s,d)}catch{s.writeHead(400,{"Content-Type":"application/json"}),s.end(JSON.stringify({error:"Invalid JSON"}))}})}else await a.handleRequest(n,s)});r.listen(o,()=>{Me(`EntryDesk MCP server running at http://localhost:${o}/mcp`),Me("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{Me(`
407
+ Shutting down...`),r.close(),await t(),process.exit(0)}),process.on("SIGTERM",async()=>{r.close(),await t(),process.exit(0)})}async function di(e,t){let o=vr(e),r=new ii;r.onclose=async()=>{await t()},await o.connect(r)}async function Pr(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{Me("[entrydesk-mcp] Starting MCP server...");let t,o;try{let d=await fe();t=d.accessToken,o=d.workspaceId}catch(d){let k=d instanceof Error?d.message:"Authentication failed";console.error(k),process.exit(1)}let{apiUrl:r,mcp:n}=Ze();Me(`[entrydesk-mcp] Connecting to ${r}...`),Me(`[entrydesk-mcp] Workspace: ${o}`);let s=await Ir(r,t,o);Me("[entrydesk-mcp] Connected to EntryDesk API");let i=null,a=async()=>sn(t)?i||(i=(async()=>{Me("[entrydesk-mcp] Token expiring soon, refreshing...");let d=await Se.getAll();if(!d?.accessToken)throw new Error("Not logged in. Please run `entrydesk login` again.");let k=await an(d);if(k!==t){t=k;try{await s.close()}catch{}s=await Ir(r,t,o),Me("[entrydesk-mcp] Token refreshed, reconnected")}return s})().finally(()=>{i=null}),i):s,c=async()=>{try{await s.close()}catch{}};if(e.mode==="http"){let d=e.port??n.httpPort;await ui(a,c,d)}else Me("[entrydesk-mcp] Starting stdio server..."),await di(a,c),Me("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Ar(e){try{let t,o;try{let s=await fe();t=s.accessToken,o=s.workspaceId}catch(s){let i=s instanceof Error?s.message:"Authentication failed";console.error(i),process.exit(1)}let r=new V,{models:n}=await r.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
408
+ `);for(let s of n)console.log(` ${s.name}`),s.description&&console.log(` ${s.description.slice(0,80)}`),console.log(` ID: ${s.id}`),console.log("")}catch(t){ke(t)}}function fi(){console.log(`
409
409
  Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
410
410
 
411
411
  Commands:
@@ -420,7 +420,7 @@ Commands:
420
420
 
421
421
  Flags:
422
422
  --json Output JSON
423
- `)}function Jt(e,t){if(e)return e;if(t&&G.getProfileCount()===1)return G.getProfileNames()[0];throw new _t("Profile name is required when multiple profiles exist.")}function pi(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function Ns(e){try{let t=e.action||"list",o=G.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){fi();return}if(t==="list"){let r=G.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:r.map(i=>({name:i,isCurrent:i===o}))}));return}console.log(`Profiles (${r.length}):`);for(let i of r)console.log(` ${i}${i===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let r=Jt(s,!0),i=oe.getAll(r),a=await Se.getAll(r),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:r,isCurrent:r===o,config:i,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${r}${r===o?" (current)":""}`),console.log(` API URL: ${i.apiUrl??"default"}`),console.log(` Hub URL: ${i.hubUrl??"default"}`),console.log(` Model: ${i.model?.default??"unset"}`);let d=i.connectors?.defaults&&i.connectors.defaults.length>0?i.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${pi(i.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let r=s||G.DEFAULT_PROFILE;if(G.createProfile(r),e.json){console.log(JSON.stringify({name:r,created:!0}));return}console.log(`Profile created: ${r}`);return}if(t==="use"||t==="switch"){let r=Jt(s,!0);if(G.setCurrentProfile(r),e.json){console.log(JSON.stringify({name:r,current:!0}));return}console.log(`Switched to profile: ${r}`);return}if(t==="delete"||t==="remove"||t==="rm"){let r=Jt(s,!0),i=G.deleteProfile(r);if(e.json){console.log(JSON.stringify({deleted:r,currentProfile:i.currentProfile}));return}console.log(`Profile deleted: ${r}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let r=Jt(s,!0);if(!n)throw new _t("New profile name is required.");let i=G.renameProfile(r,n);if(e.json){console.log(JSON.stringify({renamed:r,name:n,currentProfile:i.currentProfile}));return}console.log(`Profile renamed: ${r} -> ${n}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="clone"||t==="copy"){let r=Jt(s,!0);if(!n)throw new _t("Target profile name is required.");let i=oe.getAll(r);if(G.createProfile(n),oe.setAll(i,n),await Se.clear(n),e.json){console.log(JSON.stringify({source:r,name:n,cloned:!0}));return}console.log(`Profile cloned: ${r} -> ${n}`);return}throw new _t(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Gt(){console.log(`
423
+ `)}function Jt(e,t){if(e)return e;if(t&&G.getProfileCount()===1)return G.getProfileNames()[0];throw new _t("Profile name is required when multiple profiles exist.")}function pi(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function Nr(e){try{let t=e.action||"list",o=G.getCurrentProfileName(),r=e.name??e.profile,n=e.value;if(e.help||t==="help"){fi();return}if(t==="list"){let s=G.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:s.map(i=>({name:i,isCurrent:i===o}))}));return}console.log(`Profiles (${s.length}):`);for(let i of s)console.log(` ${i}${i===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let s=Jt(r,!0),i=oe.getAll(s),a=await Se.getAll(s),c=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:s,isCurrent:s===o,config:i,auth:c?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${s}${s===o?" (current)":""}`),console.log(` API URL: ${i.apiUrl??"default"}`),console.log(` Hub URL: ${i.hubUrl??"default"}`),console.log(` Model: ${i.model?.default??"unset"}`);let d=i.connectors?.defaults&&i.connectors.defaults.length>0?i.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${pi(i.capabilities)}`),console.log(c?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),c&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let s=r||G.DEFAULT_PROFILE;if(G.createProfile(s),e.json){console.log(JSON.stringify({name:s,created:!0}));return}console.log(`Profile created: ${s}`);return}if(t==="use"||t==="switch"){let s=Jt(r,!0);if(G.setCurrentProfile(s),e.json){console.log(JSON.stringify({name:s,current:!0}));return}console.log(`Switched to profile: ${s}`);return}if(t==="delete"||t==="remove"||t==="rm"){let s=Jt(r,!0),i=G.deleteProfile(s);if(e.json){console.log(JSON.stringify({deleted:s,currentProfile:i.currentProfile}));return}console.log(`Profile deleted: ${s}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let s=Jt(r,!0);if(!n)throw new _t("New profile name is required.");let i=G.renameProfile(s,n);if(e.json){console.log(JSON.stringify({renamed:s,name:n,currentProfile:i.currentProfile}));return}console.log(`Profile renamed: ${s} -> ${n}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="clone"||t==="copy"){let s=Jt(r,!0);if(!n)throw new _t("Target profile name is required.");let i=oe.getAll(s);if(G.createProfile(n),oe.setAll(i,n),await Se.clear(n),e.json){console.log(JSON.stringify({source:s,name:n,cloned:!0}));return}console.log(`Profile cloned: ${s} -> ${n}`);return}throw new _t(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Gt(){console.log(`
424
424
  Usage: entrydesk schedules [list|get|create|delete] [options]
425
425
 
426
426
  Commands:
@@ -446,7 +446,7 @@ Create Options:
446
446
 
447
447
  Flags:
448
448
  --json Output JSON
449
- `)}function Es(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Vt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,r=parseInt(s[2],10),i=parseInt(s[3],10),a=n*(r*60+i)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function mi(e){console.log(`
449
+ `)}function Er(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"],r=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${r} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Vt(e,t){let o=new Date(e),r=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!r)return o.toISOString();let n=r[1]==="+"?1:-1,s=parseInt(r[2],10),i=parseInt(r[3],10),a=n*(s*60+i)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function mi(e){console.log(`
450
450
  Schedule: ${e.name}
451
451
  ${"\u2501".repeat(50)}
452
452
  ID: ${e.id}
@@ -458,13 +458,13 @@ Prompt:
458
458
  ${e.prompt.slice(0,200)}${e.prompt.length>200?"...":""}
459
459
 
460
460
  Schedule:
461
- ${Es(e.config)}
461
+ ${Er(e.config)}
462
462
 
463
463
  Next Run: ${e.nextRunAt?Vt(e.nextRunAt,e.utcOffset):"-"}
464
464
  Created: ${Vt(e.createdAt,e.utcOffset)}
465
465
  Updated: ${Vt(e.updatedAt,e.utcOffset)}
466
- `)}function gi(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,r]=s.split(":"),i={hour:parseInt(n,10),minute:parseInt(r,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:i.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:i}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:i}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:i}};default:return{type:"no-repeat"}}}async function _s(e){try{if(e.help){Gt();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new V;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Gt(),process.exit(1));let d=await r.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}mi(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Gt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:gi(e),utcOffset:e.utcOffset||"+00:00"},d=await r.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Vt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Gt(),process.exit(1)),await r.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Gt(),process.exit(1));let i=[],a;do{let l=await r.getSchedules(o,s,{nextKey:a,limit:100});i.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${i.length}):
467
- `);for(let l of i){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${Es(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?Vt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){ke(t)}}import hi from"crypto";import At from"fs";import _e from"fs/promises";import Xo from"os";import Ce from"path";import{Readable as yi}from"stream";import{pipeline as wi}from"stream/promises";import ki from"adm-zip";import xi from"archiver";function xo(){console.log(`
466
+ `)}function gi(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every??1,r=e.time||"09:00",[n,s]=r.split(":"),i={hour:parseInt(n,10),minute:parseInt(s,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:i.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:i}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek??[1],time:i}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth??[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:i}};default:return{type:"no-repeat"}}}async function _r(e){try{if(e.help){Gt();return}let t=await fe(),{accessToken:o,workspaceId:r}=t,n=e.action||"list",s=new V;if(n==="get"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Gt(),process.exit(1));let d=await s.getSchedule(o,r,c);if(e.json){console.log(JSON.stringify(d));return}mi(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Gt(),process.exit(1));let c={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:gi(e),utcOffset:e.utcOffset||"+00:00"},d=await s.createSchedule(o,r,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?Vt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let c=e.scheduleId;c||(console.error("Missing schedule ID."),Gt(),process.exit(1)),await s.deleteSchedule(o,r,c),console.log(`Deleted schedule: ${c}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Gt(),process.exit(1));let i=[],a;do{let c=await s.getSchedules(o,r,{nextKey:a,limit:100});i.push(...c.schedules),a=c.nextKey}while(a);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${i.length}):
467
+ `);for(let c of i){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: ${Er(c.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${c.nextRunAt?Vt(c.nextRunAt,c.utcOffset):"-"}`),console.log(` ID: ${c.id}`),console.log("")}}catch(t){ke(t)}}import hi from"crypto";import Pt from"fs";import _e from"fs/promises";import Xo from"os";import Ce from"path";import{Readable as yi}from"stream";import{pipeline as wi}from"stream/promises";import ki from"adm-zip";import xi from"archiver";function xo(){console.log(`
468
468
  Usage: entrydesk skills [list|upload|delete|download] [options]
469
469
 
470
470
  Commands:
@@ -478,16 +478,16 @@ Options:
478
478
  --me Only list skills created by me
479
479
  --force Overwrite an existing skill with the same name
480
480
  --json Output JSON (for list/upload)
481
- `)}function bi(e,t){let o=Ce.relative(e,t);return o===""||!o.startsWith("..")&&!Ce.isAbsolute(o)}async function Ci(e){let t=await _e.realpath(e),o=[process.cwd(),Xo.homedir()];if(!(await Promise.all(o.map(async r=>{try{return await _e.realpath(r)}catch{return Ce.resolve(r)}}))).some(r=>bi(r,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function $i(e){let t=await _e.mkdtemp(Ce.join(Xo.tmpdir(),"entrydesk-skill-")),o=Ce.join(t,`${Ce.basename(e)}.zip`);return await new Promise((s,n)=>{let r=At.createWriteStream(o),i=xi("zip",{zlib:{level:9}});r.on("close",()=>s()),r.on("error",n),i.on("error",n),i.pipe(r),i.directory(e,!1),i.finalize()}),{zipPath:o,cleanupDir:t}}async function Ds(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){ke(a)}let s=e.action||"list",n=new V;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),xo(),process.exit(1));let l=Ce.resolve(a),d;try{d=await _e.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let k=l,C=null;try{try{await Ci(l)}catch(h){let b=h instanceof Error?h.message:"Invalid upload path.";console.error(b),process.exit(1)}if(d.isDirectory()){let h=await $i(l);k=h.zipPath,C=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));Ce.extname(k).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let $=await _e.readFile(k),S=new FormData;S.append("file",new Blob([$],{type:"application/zip"}),Ce.basename(k)),e.force&&S.append("force","true");let y;try{y=await n.uploadSkill(t,o,S)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let b=h;if(b.response&&b.response.status===409){try{(await b.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw h}if(e.json){console.log(JSON.stringify(y));return}console.log(`Uploaded skill: ${y.name}`),console.log(` ID: ${y.id}`),console.log(` Version ID: ${y.versionId}`),console.log(` Description: ${y.description}`);return}finally{C&&await _e.rm(C,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),xo(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(s==="download"){let a=e.configKey;a||(console.error("Missing skill ID."),xo(),process.exit(1));let{url:l,name:d}=await n.downloadSkillCurrent(t,o,a);(d.includes("/")||d.includes(Ce.sep)||d==="."||d===".."||!d)&&(console.error(`Invalid skill name for output directory: ${d}`),process.exit(1));let k=Ce.resolve(d),C=await _e.mkdtemp(Ce.join(Xo.tmpdir(),"entrydesk-skill-download-")),$=Ce.join(C,`${d}.zip`);try{let S=await fetch(l);if(!S.ok)throw new Error(`Failed to download skill zip: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Response body is empty");let y=At.createWriteStream($);await wi(yi.fromWeb(S.body),y);let h=await _e.mkdtemp(Ce.join(Ce.dirname(k),".entrydesk-skill-extract-")),b=null;try{e.json||console.log("Extracting...");let L=new ki($),K=Ce.resolve(h)+Ce.sep;for(let F of L.getEntries()){if(F.isDirectory)continue;let re=Ce.resolve(h,F.entryName);if(!re.startsWith(K))throw new Error(`Zip entry contains path traversal: ${F.entryName}`);await _e.mkdir(Ce.dirname(re),{recursive:!0}),await _e.writeFile(re,F.getData())}At.existsSync(k)&&(b=Ce.join(Ce.dirname(k),`.entrydesk-backup-${hi.randomUUID()}`),e.json||console.log(`Replacing existing directory: ${k}`),await _e.rename(k,b));try{await _e.rename(h,k),b&&At.existsSync(b)&&(await _e.rm(b,{recursive:!0,force:!0}),b=null)}catch(F){throw b&&At.existsSync(b)&&(await _e.rename(b,k),b=null),F}}catch(L){if(await _e.rm(h,{recursive:!0,force:!0}),b&&At.existsSync(b))try{await _e.rename(b,k)}catch{console.error(`Warning: Could not restore backup. Your original files are at: ${b}`)}throw L}if(e.json){console.log(JSON.stringify({skillId:a,skillName:d,outputDir:k}));return}console.log(`Downloaded skill "${d}" to ${k}`)}finally{await _e.rm(C,{recursive:!0,force:!0})}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),xo(),process.exit(1));let r=[],i;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:i,limit:100});r.push(...a.skills),i=a.nextKey}while(i);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${r.length}):
482
- `);for(let a of r)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Os(e){try{let t=G.getEffectiveProfileName(),o=await Se.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let r=new V,i=await ct(),{workspaces:a}=await r.getWorkspaces(i);n=a.find(d=>d.id===o.workspaceId)?.name}catch(r){if(r instanceof Xe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){ke(t)}}import Li from"fs";import{Client as Si}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ti}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Ii(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Ze().apiUrl);let n=new Si({name:"entrydesk-cli",version:"1.0.0"}),r=new URL(`${t}/v1/workspaces/${s}/mcp`),i=new Ti(r,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(i),n}async function bo(){return Ii()}import Qo from"fs/promises";import vi from"os";import Ht from"path";var Zo=!process.env.NO_COLOR&&!!process.stdout.isTTY,Pt={green:Zo?"\x1B[32m":"",yellow:Zo?"\x1B[33m":"",reset:Zo?"\x1B[0m":""},Ai=10*1024,Ls=8*1024,Rs=2*1024,Pi=100,Ni=100;function Ei(){return Ht.join(vi.homedir(),".entrydesk","tool-results")}function _i(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Pi);return!t||t==="."||t===".."?"unnamed_tool":t}function Di(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Oi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=_i(e);return`${o}_${s}.json`}async function Us(e,t){try{return await Qo.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function js(e,t){try{let o=Ei();await Qo.mkdir(o,{recursive:!0});let s=Oi(e),n=Ht.extname(s),r=s.slice(0,-n.length),i=Di(t),a=Ht.join(o,s);if(await Us(a,i))return a;for(let k=1;k<=Ni;k++){let C=Ht.join(o,`${r}-${k}${n}`);if(await Us(C,i))return C}let l=Math.random().toString(36).slice(2,10),d=Ht.join(o,`${r}-${l}${n}`);return await Qo.writeFile(d,i,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Pt.yellow}Warning: Could not save result to file: ${s}${Pt.reset}`),null}}function Fs(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Ai)return e;let s=e.slice(0,Ls),n=e.slice(-Rs),i=((o-Ls-Rs)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${i}KB of ${a}KB) ...`;return t&&(l+=`
483
- Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
481
+ `)}function bi(e,t){let o=Ce.relative(e,t);return o===""||!o.startsWith("..")&&!Ce.isAbsolute(o)}async function Ci(e){let t=await _e.realpath(e),o=[process.cwd(),Xo.homedir()];if(!(await Promise.all(o.map(async s=>{try{return await _e.realpath(s)}catch{return Ce.resolve(s)}}))).some(s=>bi(s,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function $i(e){let t=await _e.mkdtemp(Ce.join(Xo.tmpdir(),"entrydesk-skill-")),o=Ce.join(t,`${Ce.basename(e)}.zip`);return await new Promise((r,n)=>{let s=Pt.createWriteStream(o),i=xi("zip",{zlib:{level:9}});s.on("close",()=>r()),s.on("error",n),i.on("error",n),i.pipe(s),i.directory(e,!1),i.finalize()}),{zipPath:o,cleanupDir:t}}async function Dr(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){ke(a)}let r=e.action||"list",n=new V;if(r==="upload"){let a=e.configKey;a||(console.error("Missing file path."),xo(),process.exit(1));let c=Ce.resolve(a),d;try{d=await _e.stat(c)}catch{console.error(`File not found: ${c}`),process.exit(1)}let k=c,C=null;try{try{await Ci(c)}catch(h){let b=h instanceof Error?h.message:"Invalid upload path.";console.error(b),process.exit(1)}if(d.isDirectory()){let h=await $i(c);k=h.zipPath,C=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${c}`),process.exit(1));Ce.extname(k).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let $=await _e.readFile(k),S=new FormData;S.append("file",new Blob([$],{type:"application/zip"}),Ce.basename(k)),e.force&&S.append("force","true");let y;try{y=await n.uploadSkill(t,o,S)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let b=h;if(b.response&&b.response.status===409){try{(await b.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw h}if(e.json){console.log(JSON.stringify(y));return}console.log(`Uploaded skill: ${y.name}`),console.log(` ID: ${y.id}`),console.log(` Version ID: ${y.versionId}`),console.log(` Description: ${y.description}`);return}finally{C&&await _e.rm(C,{recursive:!0,force:!0})}}if(r==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),xo(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(r==="download"){let a=e.configKey;a||(console.error("Missing skill ID."),xo(),process.exit(1));let{url:c,name:d}=await n.downloadSkillCurrent(t,o,a);(d.includes("/")||d.includes(Ce.sep)||d==="."||d===".."||!d)&&(console.error(`Invalid skill name for output directory: ${d}`),process.exit(1));let k=Ce.resolve(d),C=await _e.mkdtemp(Ce.join(Xo.tmpdir(),"entrydesk-skill-download-")),$=Ce.join(C,`${d}.zip`);try{let S=await fetch(c);if(!S.ok)throw new Error(`Failed to download skill zip: ${S.status} ${S.statusText}`);if(!S.body)throw new Error("Response body is empty");let y=Pt.createWriteStream($);await wi(yi.fromWeb(S.body),y);let h=await _e.mkdtemp(Ce.join(Ce.dirname(k),".entrydesk-skill-extract-")),b=null;try{e.json||console.log("Extracting...");let L=new ki($),K=Ce.resolve(h)+Ce.sep;for(let j of L.getEntries()){if(j.isDirectory)continue;let se=Ce.resolve(h,j.entryName);if(!se.startsWith(K))throw new Error(`Zip entry contains path traversal: ${j.entryName}`);await _e.mkdir(Ce.dirname(se),{recursive:!0}),await _e.writeFile(se,j.getData())}Pt.existsSync(k)&&(b=Ce.join(Ce.dirname(k),`.entrydesk-backup-${hi.randomUUID()}`),e.json||console.log(`Replacing existing directory: ${k}`),await _e.rename(k,b));try{await _e.rename(h,k),b&&Pt.existsSync(b)&&(await _e.rm(b,{recursive:!0,force:!0}),b=null)}catch(j){throw b&&Pt.existsSync(b)&&(await _e.rename(b,k),b=null),j}}catch(L){if(await _e.rm(h,{recursive:!0,force:!0}),b&&Pt.existsSync(b))try{await _e.rename(b,k)}catch{console.error(`Warning: Could not restore backup. Your original files are at: ${b}`)}throw L}if(e.json){console.log(JSON.stringify({skillId:a,skillName:d,outputDir:k}));return}console.log(`Downloaded skill "${d}" to ${k}`)}finally{await _e.rm(C,{recursive:!0,force:!0})}return}r!=="list"&&(console.error(`Unknown skills command: ${r}`),xo(),process.exit(1));let s=[],i;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:i,limit:100});s.push(...a.skills),i=a.nextKey}while(i);if(e.json){console.log(JSON.stringify(s));return}if(s.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${s.length}):
482
+ `);for(let a of s)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 Or(e){try{let t=G.getEffectiveProfileName(),o=await Se.getAll(),r={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:r})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let s=new V,i=await ct(),{workspaces:a}=await s.getWorkspaces(i);n=a.find(d=>d.id===o.workspaceId)?.name}catch(s){if(s instanceof Xe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:r})):(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:r})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){ke(t)}}import Li from"fs";import{Client as Si}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ti}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Ii(e={}){let t=e.apiUrl,o=e.accessToken,r=e.workspaceId;if(!o||!r){let a=await fe();o=o||a.accessToken,r=r||a.workspaceId}t||(t=Ze().apiUrl);let n=new Si({name:"entrydesk-cli",version:"1.0.0"}),s=new URL(`${t}/v1/workspaces/${r}/mcp`),i=new Ti(s,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(i),n}async function bo(){return Ii()}import Qo from"fs/promises";import vi from"os";import Ht from"path";var Zo=!process.env.NO_COLOR&&!!process.stdout.isTTY,At={green:Zo?"\x1B[32m":"",yellow:Zo?"\x1B[33m":"",reset:Zo?"\x1B[0m":""},Pi=10*1024,Lr=8*1024,Rr=2*1024,Ai=100,Ni=100;function Ei(){return Ht.join(vi.homedir(),".entrydesk","tool-results")}function _i(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Ai);return!t||t==="."||t===".."?"unnamed_tool":t}function Di(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Oi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),r=_i(e);return`${o}_${r}.json`}async function Ur(e,t){try{return await Qo.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function Fr(e,t){try{let o=Ei();await Qo.mkdir(o,{recursive:!0});let r=Oi(e),n=Ht.extname(r),s=r.slice(0,-n.length),i=Di(t),a=Ht.join(o,r);if(await Ur(a,i))return a;for(let k=1;k<=Ni;k++){let C=Ht.join(o,`${s}-${k}${n}`);if(await Ur(C,i))return C}let c=Math.random().toString(36).slice(2,10),d=Ht.join(o,`${s}-${c}${n}`);return await Qo.writeFile(d,i,{encoding:"utf8",flag:"wx"}),d}catch(o){let r=o instanceof Error?o.message:"unknown error";return console.error(`${At.yellow}Warning: Could not save result to file: ${r}${At.reset}`),null}}function jr(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Pi)return e;let r=e.slice(0,Lr),n=e.slice(-Rr),i=((o-Lr-Rr)/1024).toFixed(1),a=(o/1024).toFixed(1),c=` ... (skipped ${i}KB of ${a}KB) ...`;return t&&(c+=`
483
+ Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${r}
484
484
 
485
- ${l}
485
+ ${c}
486
486
 
487
- ${n}`}function Ws(e){console.log(`${Pt.green}Tool execution result saved to: ${e}${Pt.reset}`),console.log()}function Ms(){console.log(`${Pt.green}Tool execution result:${Pt.reset}`)}function Ri(e){return e.split("__")[0]??e}function gt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Nt(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?gt("AUTH_MISSING",s,t):gt(o,s,t)}async function Ui(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(i),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},r=k=>{s||(s=!0,n(),e(k))},i=setTimeout(()=>{o||r(null)},100),a=k=>{o=!0,clearTimeout(i),t.push(k)},l=()=>{t.length===0?r(null):r(Buffer.concat(t).toString("utf-8").trim())},d=()=>{r(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Kt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function ji(e,t){if(e)return e;if(t)try{return Li.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Kt(`Failed to read input file: ${n}`)}let o=await Ui();if(o)return o;throw new Kt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Fi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
488
- `)}function Wi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
489
- `)}async function Mi(e,t){let o=await bo().catch(s=>{Nt(s,e)});try{let n=(await o.listTools()).tools;if(t){let r=t.toLowerCase();n=n.filter(i=>Ri(i.name).toLowerCase().startsWith(r))}if(e)console.log(JSON.stringify(n,null,2));else{let r=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${r}:
490
- `);for(let i of n)console.log(Fi(i)),console.log()}}catch(s){Nt(s,e)}finally{await o.close().catch(()=>{})}}async function Bi(e,t){let o=await bo().catch(s=>{Nt(s,t)});try{let n=(await o.listTools()).tools.find(r=>r.name===e);n||gt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Wi(n))}catch(s){Nt(s,t)}finally{await o.close().catch(()=>{})}}async function Ji(e,t,o){let s;try{s=JSON.parse(t)}catch(i){let a=i instanceof Error?`Invalid JSON input: ${i.message}`:"Invalid JSON input";gt("INVALID_INPUT",a,o)}let n=await bo().catch(i=>{Nt(i,o,"TOOL_CALL_FAILED")}),r=!1;try{let i=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(i,null,2));else{let a=await js(e,i);a&&Ws(a),Ms();let l=i.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(i.structuredContent){let d=JSON.stringify(i.structuredContent,null,2),k=Fs(d,a);console.log(k)}}i.isError&&(r=!0)}catch(i){Nt(i,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}r&&process.exit(1)}async function Bs(e){let t=e.json??!1;switch(e.action){case"list":await Mi(t,e.prefix);break;case"get":e.name||gt("INVALID_INPUT","Tool name is required",t),await Bi(e.name,t);break;case"call":{e.name||gt("INVALID_INPUT","Tool name is required",t);let o;try{o=await ji(e.input,e.inputFile)}catch(s){throw s instanceof Kt&&gt("INVALID_INPUT",s.message,t),s}await Ji(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
487
+ ${n}`}function Br(e){console.log(`${At.green}Tool execution result saved to: ${e}${At.reset}`),console.log()}function Wr(){console.log(`${At.green}Tool execution result:${At.reset}`)}function Ri(e){return e.split("__")[0]??e}function gt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Nt(e,t,o="CONNECTION_FAILED"){let r=e instanceof Error?e.message:"Unknown error";r.includes("Not logged in")||r.includes("not-logged-in")?gt("AUTH_MISSING",r,t):gt(o,r,t)}async function Ui(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,r=!1,n=()=>{clearTimeout(i),process.stdin.removeListener("data",a),process.stdin.removeListener("end",c),process.stdin.removeListener("error",d)},s=k=>{r||(r=!0,n(),e(k))},i=setTimeout(()=>{o||s(null)},100),a=k=>{o=!0,clearTimeout(i),t.push(k)},c=()=>{t.length===0?s(null):s(Buffer.concat(t).toString("utf-8").trim())},d=()=>{s(null)};process.stdin.on("data",a),process.stdin.on("end",c),process.stdin.on("error",d),process.stdin.resume()})}var Kt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Fi(e,t){if(e)return e;if(t)try{return Li.readFileSync(t,"utf-8").trim()}catch(r){let n=r instanceof Error?r.message:"Failed to read input file";throw new Kt(`Failed to read input file: ${n}`)}let o=await Ui();if(o)return o;throw new Kt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function ji(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
488
+ `)}function Bi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
489
+ `)}async function Wi(e,t){let o=await bo().catch(r=>{Nt(r,e)});try{let n=(await o.listTools()).tools;if(t){let s=t.toLowerCase();n=n.filter(i=>Ri(i.name).toLowerCase().startsWith(s))}if(e)console.log(JSON.stringify(n,null,2));else{let s=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${s}:
490
+ `);for(let i of n)console.log(ji(i)),console.log()}}catch(r){Nt(r,e)}finally{await o.close().catch(()=>{})}}async function Mi(e,t){let o=await bo().catch(r=>{Nt(r,t)});try{let n=(await o.listTools()).tools.find(s=>s.name===e);n||gt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Bi(n))}catch(r){Nt(r,t)}finally{await o.close().catch(()=>{})}}async function Ji(e,t,o){let r;try{r=JSON.parse(t)}catch(i){let a=i instanceof Error?`Invalid JSON input: ${i.message}`:"Invalid JSON input";gt("INVALID_INPUT",a,o)}let n=await bo().catch(i=>{Nt(i,o,"TOOL_CALL_FAILED")}),s=!1;try{let i=await n.callTool({name:e,arguments:r});if(o)console.log(JSON.stringify(i,null,2));else{let a=await Fr(e,i);a&&Br(a),Wr();let c=i.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(i.structuredContent){let d=JSON.stringify(i.structuredContent,null,2),k=jr(d,a);console.log(k)}}i.isError&&(s=!0)}catch(i){Nt(i,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}s&&process.exit(1)}async function Mr(e){let t=e.json??!1;switch(e.action){case"list":await Wi(t,e.prefix);break;case"get":e.name||gt("INVALID_INPUT","Tool name is required",t),await Mi(e.name,t);break;case"call":{e.name||gt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Fi(e.input,e.inputFile)}catch(r){throw r instanceof Kt&&gt("INVALID_INPUT",r.message,t),r}await Ji(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
491
491
 
492
492
  Actions:
493
493
  list List all available tools
@@ -525,10 +525,10 @@ Examples:
525
525
  entrydesk usage --limit 10 # Show top 10 users
526
526
  entrydesk usage --sort-by operations # Sort by operation count
527
527
  entrydesk usage --json # JSON output
528
- `)}async function Js(e){if(e.help){Gi();return}let t,o;try{let y=await fe();t=y.accessToken,o=y.workspaceId}catch(y){let h=y instanceof Error?y.message:"Authentication failed";console.error(h),process.exit(1)}let s=new V,n=[],r,i=0,a=100;do{let y=await s.getMonthlyUsages(t,o,{nextKey:r,limit:100});if(n.push(...y.monthlyUsages),r=y.nextKey,i++,i>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(r);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
529
- `);let l=0,d=0;for(let y of n)l+=parseFloat(y.totalCost),d+=y.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
528
+ `)}async function Jr(e){if(e.help){Gi();return}let t,o;try{let y=await fe();t=y.accessToken,o=y.workspaceId}catch(y){let h=y instanceof Error?y.message:"Authentication failed";console.error(h),process.exit(1)}let r=new V,n=[],s,i=0,a=100;do{let y=await r.getMonthlyUsages(t,o,{nextKey:s,limit:100});if(n.push(...y.monthlyUsages),s=y.nextKey,i++,i>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(s);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
529
+ `);let c=0,d=0;for(let y of n)c+=parseFloat(y.totalCost),d+=y.operationCount;console.log(`Total Cost: $${c.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
530
530
  `);let k=e.sortBy||"cost",C=[...n].toSorted((y,h)=>k==="cost"?parseFloat(h.totalCost)-parseFloat(y.totalCost):h.operationCount-y.operationCount),$=e.limit&&e.limit>0?e.limit:C.length,S=C.slice(0,$);console.log(`Usage by User (sorted by ${k}, showing ${S.length} of ${n.length}):
531
- `);for(let y of S){let h=parseFloat(y.totalCost);console.log(` ${y.user.name} (${y.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${y.operationCount.toLocaleString()}`),console.log("")}S.length<n.length&&console.log(`... and ${n.length-S.length} more users`)}function en(){console.log("entrydesk 1.11.1")}function tn(){console.log(`
531
+ `);for(let y of S){let h=parseFloat(y.totalCost);console.log(` ${y.user.name} (${y.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${y.operationCount.toLocaleString()}`),console.log("")}S.length<n.length&&console.log(`... and ${n.length-S.length} more users`)}function en(){console.log("entrydesk 1.11.3")}function tn(){console.log(`
532
532
  Usage: entrydesk workspaces [list|switch|use] [options]
533
533
 
534
534
  Commands:
@@ -538,6 +538,6 @@ Commands:
538
538
 
539
539
  Flags:
540
540
  --json Output JSON
541
- `)}async function Gs(e){if(e.help){tn();return}let t,s=(await Se.getAll())?.workspaceId;try{t=await ct()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",r=new V;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),tn(),process.exit(1));let{workspaces:l}=await r.getWorkspaces(t),d=l.find(k=>k.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
542
- Available workspaces:`);for(let k of l)console.error(` ${k.name}: ${k.id}`);process.exit(1)}if(await Se.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),tn(),process.exit(1));let{workspaces:i}=await r.getWorkspaces(t);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${i.length}):
543
- `);for(let a of i){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Vs(e,t,o=!1){let s={},n={};for(let r=o?0:1;r<e.length;r++){let i=e[r];if(i==="--json")s.json=!0;else if(i==="--help"||i==="-h")s.help=!0;else if(i==="--profile")s.profile=e[++r];else switch(t){case"login":break;case"chat":if(i==="-m"||i==="--message")n.message=e[++r];else if(i==="-a"||i==="--agent")n.agentId=e[++r];else if(i==="--model")n.model=e[++r];else if(i==="--connectors"){let a=e[++r];n.connectors=a?.split(",").map(l=>l.trim())}else i==="-i"||i==="--interactive"?n.interactive=!0:i==="--full-output"?n.fullOutput=!0:i==="-c"||i==="--continue"?n.continue=parseInt(e[++r],10):i==="--plain"?n.plain=!0:i==="--output"?n.output=e[++r]:i==="--sandbox"?n.sandbox=!0:i==="--no-sandbox"?n.noSandbox=!0:i==="--web-search"?n.webSearch=!0:i==="--image-gen"?n.imageGen=!0:i==="--chart"?n.chart=!0:i==="--file-system"?n.fileSystem=!0:i==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(i==="--name")n.name=e[++r];else if(i==="--description")n.description=e[++r];else if(i==="--system-prompt")n.systemPrompt=e[++r];else if(i==="--model-id")n.modelId=e[++r];else if(i==="--connector-ids"){let a=e[++r];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--capabilities"){let a=e[++r];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--conversation-starters"){let a=e[++r];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--tools"){let a=e[++r];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--icon-id")n.iconId=e[++r];else if(i==="--limit"){let a=parseInt(e[++r],10);(isNaN(a)||a<1||a>100)&&(console.error("--limit must be an integer between 1 and 100"),process.exit(1)),n.limit=a}else if(i==="--next-key"){let a=e[++r];a||(console.error("--next-key requires a value"),process.exit(1)),n.nextKey=a}else i==="--all"?n.all=!0:i.startsWith("-")||(n.action?n.agentId=i:n.action=i);break;case"skills":i==="--force"?n.force=!0:i==="--me"||i==="--mine"?n.createdBy="me":i.startsWith("-")||(n.action?n.configKey=i:n.action=i);break;case"schedules":if(i==="--name")n.name=e[++r];else if(i==="--prompt")n.prompt=e[++r];else if(i==="--agent-id")n.agentId=e[++r];else if(i==="--starts-at")n.startsAt=e[++r];else if(i==="--utc-offset")n.utcOffset=e[++r];else if(i==="--repeat-type")n.repeatType=e[++r];else if(i==="--every")n.every=parseInt(e[++r],10);else if(i==="--time")n.time=e[++r];else if(i==="--days-of-week"){let a=e[++r];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(i==="--days-of-month"){let a=e[++r];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else i==="--last-day-of-month"?n.lastDayOfMonth=!0:i.startsWith("-")||(n.action?n.scheduleId=i:n.action=i);break;case"config":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")?n.configKey=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"profile":!n.action&&!i.startsWith("-")?n.action=i:!n.name&&!i.startsWith("-")?n.name=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"chats":i==="--share"||i==="-s"?n.shareId=e[++r]:i==="--full-output"?n.fullOutput=!0:i==="--output"?n.output=e[++r]:!n.chatId&&!i.startsWith("-")&&(n.chatId=i);break;case"budget":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")&&(n.configKey=i);break;case"usage":if(i==="--limit")n.limit=parseInt(e[++r],10);else if(i==="--sort-by"){let a=e[++r];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":i==="--http"?n.http=!0:(i==="-p"||i==="--port")&&(n.port=parseInt(e[++r],10));break;case"tool":i==="-i"||i==="--input"?n.input=e[++r]:i==="-f"||i==="--input-file"?n.inputFile=e[++r]:i==="-p"||i==="--prefix"?n.prefix=e[++r]:i.startsWith("-")||(n.action?n.name||(n.name=i):n.action=i);break;case"workspaces":!n.action&&!i.startsWith("-")&&(n.action=i);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as zi}from"react/jsx-runtime";var Je=process.argv.slice(2);(Je[0]==="--help"||Je[0]==="-h")&&(ko(),process.exit(0));(Je[0]==="--version"||Je[0]==="-v")&&(en(),process.exit(0));var on=!Je[0]||Je[0].startsWith("-"),Hi=on?"chat":Je[0],xe=Vs(Je,Hi,on);on&&xe.command==="chat"&&(xe.interactive=!0);async function Ki(){try{if(xe.command!=="profile"){let e=xe.profile||G.getCurrentProfileName();G.ensureProfileExists(e),G.setOverrideProfile(e)}switch(xe.command){case"login":await Ss(xe);break;case"logout":await Ts(xe);break;case"status":await Os(xe);break;case"workspaces":await Gs(xe);break;case"agents":await un(xe);break;case"models":await Ps(xe);break;case"connectors":await $s(xe);break;case"skills":await Ds(xe);break;case"schedules":await _s(xe);break;case"chats":await xs(xe);break;case"budget":await dn(xe);break;case"usage":await Js(xe);break;case"config":xe.action==="help"||Je[1]==="--help"?Vi(zi(Cs,{})):await bs(xe);break;case"profile":await Ns(xe);break;case"chat":Je[1]==="--help"||Je[1]==="-h"?ko():await ms(xe);break;case"mcp-server":await As({mode:xe.http?"http":"stdio",port:xe.port});break;case"tool":await Bs(xe);break;case"version":en();break;default:ko();break}}catch(e){ke(e)}}Ki();
541
+ `)}async function Gr(e){if(e.help){tn();return}let t,r=(await Se.getAll())?.workspaceId;try{t=await ct()}catch(a){let c=a instanceof Error?a.message:"Authentication failed";console.error(c),process.exit(1)}let n=e.action||"list",s=new V;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),tn(),process.exit(1));let{workspaces:c}=await s.getWorkspaces(t),d=c.find(k=>k.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
542
+ Available workspaces:`);for(let k of c)console.error(` ${k.name}: ${k.id}`);process.exit(1)}if(await Se.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),tn(),process.exit(1));let{workspaces:i}=await s.getWorkspaces(t);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${i.length}):
543
+ `);for(let a of i){let c=a.id===r?" (current)":"";console.log(` ${a.name}${c}`),console.log(` ID: ${a.id}`),console.log("")}}function Vr(e,t,o=!1){let r={},n={};for(let s=o?0:1;s<e.length;s++){let i=e[s];if(i==="--json")r.json=!0;else if(i==="--help"||i==="-h")r.help=!0;else if(i==="--profile")r.profile=e[++s];else switch(t){case"login":break;case"chat":if(i==="-m"||i==="--message")n.message=e[++s];else if(i==="-a"||i==="--agent")n.agentId=e[++s];else if(i==="--model")n.model=e[++s];else if(i==="--connectors"){let a=e[++s];n.connectors=a?.split(",").map(c=>c.trim())}else i==="-i"||i==="--interactive"?n.interactive=!0:i==="--full-output"?n.fullOutput=!0:i==="-c"||i==="--continue"?n.continue=parseInt(e[++s],10):i==="--plain"?n.plain=!0:i==="--output"?n.output=e[++s]:i==="--sandbox"?n.sandbox=!0:i==="--no-sandbox"?n.noSandbox=!0:i==="--web-search"?n.webSearch=!0:i==="--image-gen"?n.imageGen=!0:i==="--chart"?n.chart=!0:i==="--file-system"?n.fileSystem=!0:i==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(i==="--name")n.name=e[++s];else if(i==="--description")n.description=e[++s];else if(i==="--system-prompt")n.systemPrompt=e[++s];else if(i==="--model-id")n.modelId=e[++s];else if(i==="--connector-ids"){let a=e[++s];n.connectorIds=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(i==="--capabilities"){let a=e[++s];n.capabilities=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(i==="--conversation-starters"){let a=e[++s];n.conversationStarters=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(i==="--tools"){let a=e[++s];n.tools=a?.split(",").map(c=>c.trim()).filter(Boolean)}else if(i==="--icon-id")n.iconId=e[++s];else if(i==="--limit"){let a=parseInt(e[++s],10);(isNaN(a)||a<1||a>100)&&(console.error("--limit must be an integer between 1 and 100"),process.exit(1)),n.limit=a}else if(i==="--next-key"){let a=e[++s];a||(console.error("--next-key requires a value"),process.exit(1)),n.nextKey=a}else i==="--all"?n.all=!0:i.startsWith("-")||(n.action?n.agentId=i:n.action=i);break;case"skills":i==="--force"?n.force=!0:i==="--me"||i==="--mine"?n.createdBy="me":i.startsWith("-")||(n.action?n.configKey=i:n.action=i);break;case"schedules":if(i==="--name")n.name=e[++s];else if(i==="--prompt")n.prompt=e[++s];else if(i==="--agent-id")n.agentId=e[++s];else if(i==="--starts-at")n.startsAt=e[++s];else if(i==="--utc-offset")n.utcOffset=e[++s];else if(i==="--repeat-type")n.repeatType=e[++s];else if(i==="--every")n.every=parseInt(e[++s],10);else if(i==="--time")n.time=e[++s];else if(i==="--days-of-week"){let a=e[++s];n.daysOfWeek=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else if(i==="--days-of-month"){let a=e[++s];n.daysOfMonth=a?.split(",").map(c=>parseInt(c.trim(),10)).filter(c=>!isNaN(c))}else i==="--last-day-of-month"?n.lastDayOfMonth=!0:i.startsWith("-")||(n.action?n.scheduleId=i:n.action=i);break;case"config":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")?n.configKey=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"profile":!n.action&&!i.startsWith("-")?n.action=i:!n.name&&!i.startsWith("-")?n.name=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"chats":i==="--share"||i==="-s"?n.shareId=e[++s]:i==="--full-output"?n.fullOutput=!0:i==="--output"?n.output=e[++s]:!n.chatId&&!i.startsWith("-")&&(n.chatId=i);break;case"budget":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")&&(n.configKey=i);break;case"usage":if(i==="--limit")n.limit=parseInt(e[++s],10);else if(i==="--sort-by"){let a=e[++s];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":i==="--http"?n.http=!0:(i==="-p"||i==="--port")&&(n.port=parseInt(e[++s],10));break;case"tool":i==="-i"||i==="--input"?n.input=e[++s]:i==="-f"||i==="--input-file"?n.inputFile=e[++s]:i==="-p"||i==="--prefix"?n.prefix=e[++s]:i.startsWith("-")||(n.action?n.name||(n.name=i):n.action=i);break;case"workspaces":!n.action&&!i.startsWith("-")&&(n.action=i);break;default:break}}switch(t){case"login":return{command:"login",...r,...n};case"logout":return{command:"logout",...r,...n};case"status":return{command:"status",...r,...n};case"workspaces":return{command:"workspaces",...r,...n};case"agents":return{command:"agents",...r,...n};case"models":return{command:"models",...r,...n};case"connectors":return{command:"connectors",...r,...n};case"skills":return{command:"skills",...r,...n};case"schedules":return{command:"schedules",...r,...n};case"config":return{command:"config",...r,...n};case"profile":return{command:"profile",...r,...n};case"chat":return{command:"chat",...r,...n};case"chats":return{command:"chats",...r,...n};case"budget":return{command:"budget",...r,...n};case"usage":return{command:"usage",...r,...n};case"mcp-server":return{command:"mcp-server",...r,...n};case"tool":return{command:"tool",...r,...n};case"version":return{command:"version",...r,...n};default:return{command:"help",...r,...n}}}import{jsx as zi}from"react/jsx-runtime";var Je=process.argv.slice(2);(Je[0]==="--help"||Je[0]==="-h")&&(ko(),process.exit(0));(Je[0]==="--version"||Je[0]==="-v")&&(en(),process.exit(0));var on=!Je[0]||Je[0].startsWith("-"),Hi=on?"chat":Je[0],xe=Vr(Je,Hi,on);on&&xe.command==="chat"&&(xe.interactive=!0);async function Ki(){try{if(xe.command!=="profile"){let e=xe.profile||G.getCurrentProfileName();G.ensureProfileExists(e),G.setOverrideProfile(e)}switch(xe.command){case"login":await Sr(xe);break;case"logout":await Tr(xe);break;case"status":await Or(xe);break;case"workspaces":await Gr(xe);break;case"agents":await un(xe);break;case"models":await Ar(xe);break;case"connectors":await $r(xe);break;case"skills":await Dr(xe);break;case"schedules":await _r(xe);break;case"chats":await xr(xe);break;case"budget":await dn(xe);break;case"usage":await Jr(xe);break;case"config":xe.action==="help"||Je[1]==="--help"?Vi(zi(Cr,{})):await br(xe);break;case"profile":await Nr(xe);break;case"chat":Je[1]==="--help"||Je[1]==="-h"?ko():await mr(xe);break;case"mcp-server":await Pr({mode:xe.http?"http":"stdio",port:xe.port});break;case"tool":await Mr(xe);break;case"version":en();break;default:ko();break}}catch(e){ke(e)}}Ki();