@entrydesk/cli 1.11.2 → 1.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +67 -67
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -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 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 l=zr(e),d=await s.createAgent(o,r,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 s.getAgent(o,r,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 s.updateAgent(o,r,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 s.deleteAgent(o,r,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 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(`
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){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 l=parseFloat(a);if(isNaN(l)||l<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
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
 
@@ -66,12 +66,12 @@ You have access to filesystem tools that allow you to interact with the user's l
66
66
 
67
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 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,l=r?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:[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-l)):"",Y=r?" ".repeat(l):"";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,l]=$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?(l(y.length),$.current=null):l(F=>so(F,y.length)),d.current=e},[e,y.length]),bn(()=>{C(F=>{let P=F;j<P?P=j:j>=P+se&&(P=j-se+1);let N=L[K]??0,R=j===N?N+1:N,W=Math.max(0,R-se);return P>W&&(P=W),P<0&&(P=0),P})},[se,j,K,L]);let Y=xn((F,P)=>{d.current=F,t(F),l(P),$.current=null},[t]),$e=xn(async(F,P)=>{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&&(P.meta&&P.return||P.ctrl&&F==="j"||P.shift&&P.return)){let _=[...y.slice(0,a),`
71
- `,...y.slice(a)].join("");Y(_,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&N>0?l(b[N]-1):l(b[N]+_o(W,R)),$.current=null):(R===0&&N>0?l(b[N]-1):l(_=>so(_-1,y.length)),$.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=E&&N<h.length-1?l(b[N+1]):l(b[N]+Sn(W,R)),$.current=null):(R>=E&&N<h.length-1?l(b[N+1]):l(_=>so(_+1,y.length)),$.current=null);return}if(i&&ge&&P.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&&P.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(P.ctrl){if(F==="a"){l(b[N]??0),$.current=null;return}if(F==="e"){l((b[N]??0)+E),$.current=null;return}if(F==="u"){if(R>0){let _=b[N]??0,p=[...y.slice(0,_),...y.slice(a)].join("");Y(p,_)}return}if(F==="k"){if(R<E){let _=(b[N]??0)+E,p=[...y.slice(0,a),...y.slice(_)].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 _=_o(W,R);if(_!==R){let p=(b[N]??0)+_,ie=[...y.slice(0,p),...y.slice(a)].join("");Y(ie,p)}return}if(F==="d"){if(a<y.length){let _=[...y.slice(0,a),...y.slice(a+1)].join("");Y(_,a)}return}return}if(P.meta){F==="b"?(R===0&&N>0?l(b[N]-1):l(b[N]+_o(W,R)),$.current=null):F==="f"&&(R>=E&&N<h.length-1?l(b[N+1]):l(b[N]+Sn(W,R)),$.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let _=[...y.slice(0,a-1),...y.slice(a)].join("");Y(_,a-1);return}if(!(P.tab||P.escape)&&F.length>0){let _=i?F.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
- `):F.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=as||_.includes(`
74
- `))&&r){let z=!1,A={text:_,preventDefault:()=>{z=!0}};if(await Promise.resolve(r(A)),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,r,o,Y,e]);return rs($e,{isActive:n}),Do(ns,{flexDirection:"column",children:h.map((F,P)=>{let N=P===K,W=(N&&j===F.length?[...F," "]:F).slice(k,k+se),E=W.join("");if(!N)return Do(kn,{children:E||" "},P);let ge=so(j-k,Math.max(0,W.length-1)),_=W.slice(0,ge).join(""),p=W[ge]??" ",ie=W.slice(ge+1).join(""),A=`${_}\x1B[7m${p}\x1B[27m${ie}`;return Do(kn,{children:A},P)})})}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,l;for(;(l=a.exec(e))!==null;){l.index>i&&s.push(We(Fe,{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=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(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=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,} *$/,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 P=h.match(n);P&&P[1].startsWith(S[0])&&P[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(l);if(K)k=!0,S=K[1];else if($e)y(ye(He,{children:ye(ut,{dimColor:!0,children:"---"})},L));else if(j){let P=j[1].length,N=j[2],R=P<=2?"cyan":"blue";y(ye(He,{children:ye(ut,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Ut,{text:N,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},L))}else if(F){let P=F[1];y(ye(He,{paddingLeft:1,children:Dn(ut,{dimColor:!0,children:["> ",ye(Ut,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},L))}else if(se){let P=se[1],N=se[2],R=se[3];y(ye(En,{itemText:R,type:"ul",marker:N,leadingWhitespace:P},L))}else if(Y){let P=Y[1],N=Y[2],R=Y[3];y(ye(En,{itemText:R,type:"ol",marker:N,leadingWhitespace:P},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(`
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
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
@@ -86,7 +86,7 @@ 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 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(""),[l,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:l,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 l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),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,l]=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),l(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(`
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
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
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
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(`
@@ -117,13 +117,13 @@ ${ve}\u2514\u2500 failed${re}
117
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
118
  DATA: ${JSON.stringify(t,null,2)}`),r+=`
119
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:l,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 P=$e||t?.accessToken,N=F||t?.workspaceId;if(!P||!N)try{let E=await fe();P=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!==P&&(P=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?.()??[],_={id:e,message:{id:Ns(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};ge.length>0&&(_.fileIds=ge),o?_.agentId=o:(r&&(_.model=r),_.connectorIds=n??[],_.enableSandbox=s,_.enableWebSearch=i,_.enableImageGeneration=a,_.enableChart=l),K&&(_.clientTools=K),j&&(_.clientToolSystemPrompt=j);let p=await E.chat(P,N,_);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="",A="",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",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,S(`${je}[Thinking...]${re}
122
- ${A}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let T={type:"reasoning",id:ee,text:A,state:"done"};Q&&(T.providerMetadata={anthropic:{signature:Q}}),q.push(T),ae("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",Q="",S("");break;case"text-delta":w.delta&&(M.hasPending()&&(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()+`
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
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=l),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(P,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),R=O.body.getReader(),q.length=0,pe="",A="",ee="",Q="";;){let{done:f,value:w}=await R.read();if(f){ae("=== Continuation stream done ===");break}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",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,S(`${je}[Thinking...]${re}
126
- ${A}`)),U.providerMetadata?.anthropic?.signature&&(Q=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let be={type:"reasoning",id:ee,text:A,state:"done"};Q&&(be.providerMetadata={anthropic:{signature:Q}}),q.push(be),ae("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!Q,messagePartsCount:q.length})}A="",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(P,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,l,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,l]=Bt(t),[d,k]=Bt(o),[C,$]=Bt(r),[S,y]=Bt(n);return{sandbox:s,setSandbox:i,webSearch:a,setWebSearch:l,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,l]=Wo(o);return{currentModel:r,setCurrentModel:n,currentAgentId:s,setCurrentAgentId:i,activeConnectorIds:a,setActiveConnectorIds:l}}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:
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,77 +147,77 @@ 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 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:l,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:P,availableAgents:N,availableConnectors:R,messages:W,hasPersistedChat:E,setHasPersistedChat:ge,setMessages:_,addSystemMessage:p,startNewChat:ie,sendMessage:we,setFullOutput:z,credentials:A,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(!A)return[];let v=new V,g=[],c;do{let u=await v.listAvailableSkills(A.accessToken,A.workspaceId,{limit:100,nextKey:c});g.push(...u.skills),c=u.nextKey}while(c);return ht(g),g},[A]),xt=ot(async()=>{if(!A)return[];let v=new V,g=[],c;do{let u=await v.getSchedules(A.accessToken,A.workspaceId,{limit:100,nextKey:c});g.push(...u.schedules),c=u.nextKey}while(c);return qt(g),g},[A]),Ee=ot(async v=>{if(v==="model"){if(P.length===0){p("No models available.");return}let g=P.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=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 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),rt(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"),se&&c.add("chart"),$e&&c.add("fileSystem"),st(c),w("capabilities")}else if(v==="chats"){if(!A){p("Not authenticated.");return}try{let g=new V,{chats:c}=await g.getChats(A.accessToken,A.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([])},[P,N,Be,ze,R,$,i,l,kt,xt,y,b,K,se,$e,A,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),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 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(rr),!0;case"clear":return ie("Started a new chat."),!0;case"model":{if(v.value){let g=v.value.toLowerCase(),c=P.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=P.map(m=>m.name).join(", ");p(`Model "${v.value}" not found.
151
- Available: ${u||"none"}`)}}else{let g=P.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(Be.length>0?Promise.resolve(Be):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
159
  Repeat: ${Mo(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(`
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
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(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(!A)return p("Not authenticated."),!0;let g=new V;if(!v.value){try{let{workspaces:u}=await g.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let m=u.map(I=>` ${I.id===A.workspaceId?"* ":" "}${I.name}
170
- ID: ${I.id}`);p(`Workspaces:
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(A.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(!A)return p("Not authenticated."),!0;let g=new V;if(!v.value){try{let m=await g.getBudget(A.accessToken,A.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let c=v.value.toLowerCase();if(c==="clear"||c==="null"){try{await g.updateBudget(A.accessToken,A.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await g.updateBudget(A.accessToken,A.workspaceId,c),p(`Budget set to: $${c}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let g=new V;try{let c=[],u,m=0,I=10;do{let Ie=await g.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...Ie.monthlyUsages),u=Ie.nextKey,m++,m>=I){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let x=0,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?P.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"),se&&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",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${I.length>0?I.join(", "):"none"}`].filter(Boolean);p(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):[],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(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||W.some(x=>x.role!=="system")?`/chat/${o}`:"/chat/new",m=l?`?agentId=${encodeURIComponent(l)}`:"",I=`${g}${u}${m}`;try{await er(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(!A)return p("Not authenticated."),!0;if(!(E||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new V().createChatShare(A.accessToken,A.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 A?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,P,N,R,Be,ze,i,l,$,y,b,K,se,$e,o,n,Z,Ee,ie,le,k,E,W,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=or(v);de(g),B(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=Be.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
188
  Repeat: ${Mo(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),j(I),Y(x),F(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=nr(g);if(c){await bt(c),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,l,ie,a,d,C,S,h,L,j,Y,F,M,he,Ye,at,A,E,o]);return Rs((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(""),A&&E&&new V().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&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=Be.find(m=>m.id===c.id);u&&p(`Skill: ${u.name}
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
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),j(m),Y(I),F(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&&A&&(r(u.id),s(u.title||void 0),ge(!0),new V().getMessages(A.accessToken,A.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"?rt:st)(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"?rt:st)(new Set(T.map(u=>u.id)));return}if(v==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?rt:st)(new Set);return}return}if(ne&&q.length>0){if(g.upArrow){B(c=>c<=0?q.length-1:c-1);return}if(g.downArrow){B(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 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),l=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?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 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,l,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(`
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
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:l=!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:P,hasPersistedChat:N,setHasPersistedChat:R,credentials:W,setCredentials:E,currentResponse:ge,setCurrentResponse:_,fullOutput:p,setFullOutput:ie,addSystemMessage:we,startNewChat:z}=y,{credentials:A}=Jn(b);po(()=>{A&&!W&&E(A)},[A,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,l,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,D)=>{we(`\u2717 Failed to upload ${x}: ${D}`)}}),{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:_,setCredentials:E,setHasPersistedChat:R,getFileIds:it,clearFiles:qt}),Yt=Vo(x=>{z(x),_("")},[z]),[yt,ft]=Bs(!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 Fn(D);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 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,M,le.length]),{suggestions:kt,suggestionIndex:xt,showSuggestions:Ee,argMode:he,argItems:Ye,argIndex:bt,selectedConnectorIds:Xt,selectedCapabilities:Et,deleteConfirmMode:Zt,handleInputChange:v,handleSubmit:g}=sr({input:j,setInput:se,chatId:Y,setChatId:$e,currentChatTitle:F,setCurrentChatTitle:P,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: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>Gs)&&(he||Ee||(S.current=null,Ge&&qt(),j.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(W&&!M&&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"})},[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 c=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(),I=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.2"]}),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(Pe,{flexDirection:"column",marginBottom:1,children:[ue(H,{bold:!0,color:J,children:[ce,":"]}),X(Fo,{text:me})]},D)}),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,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<Be.length-1&&X(H,{children:", "})]},x.id))]}),ue(Pe,{children:[X(H,{color:"green",children:"> "}),X(In,{value:j,onChange:v,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: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 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)}
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.4"]}),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
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
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
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 l(){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 l(),Q=e.agentId||e.model||C||$||s),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
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||$||s||void 0;!S&&!y&&(await l(),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 P=!e.continue&&!y&&!S;(!i||P)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,R=d||mo(),W=F?eo():void 0,E=F?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=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(`
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
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
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
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
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
- `),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),A=await ie(z);for(ge=A.messageParts;A.pendingClientTools.length>0;){let ee=[];for(let M of A.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(`
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
218
  `))console.log(`${Tt}\u2502 ${Te}${Oe}`);console.log(`${Ho}\u2514\u2500 ${M.toolName} completed${Oe}
219
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:_,role:"assistant",parts:Q}];_=mo();let le=p(void 0,ee,pe);z=await a.chat(t,o,le),A=await ie(z),ge=A.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)}
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
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
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
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(`
@@ -230,12 +230,12 @@ ${Ho}\u250C\u2500 ${T}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case
230
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 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: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 $=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 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 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,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(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,l=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(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
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
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 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 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,l]of i)console.log(` ${a}=${l}`);console.log(`
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
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
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
@@ -403,8 +403,8 @@ Local Development:
403
403
 
404
404
  For more information, visit https://entrydesk.com/docs/cli
405
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 l="";n.on("data",d=>{l+=d.toString()}),n.on("end",async()=>{try{let d=JSON.parse(l);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,l=async()=>{try{await s.close()}catch{}};if(e.mode==="http"){let d=e.port??n.httpPort;await ui(a,l,d)}else Me("[entrydesk-mcp] Starting stdio server..."),await di(a,l),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}):
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
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
 
@@ -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 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),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:s,isCurrent:s===o,config:i,auth:l?{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(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&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(`
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:
@@ -463,8 +463,8 @@ Schedule:
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,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 l=e.scheduleId;l||(console.error("Missing schedule ID."),Gt(),process.exit(1));let d=await s.getSchedule(o,r,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 s.createSchedule(o,r,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 s.deleteSchedule(o,r,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 s.getSchedules(o,r,{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: ${Er(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 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(`
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 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 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(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: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=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 l=Math.random().toString(36).slice(2,10),d=Ht.join(o,`${s}-${l}${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),l=` ... (skipped ${i}KB of ${a}KB) ...`;return t&&(l+=`
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
483
  Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${r}
484
484
 
485
- ${l}
485
+ ${c}
486
486
 
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",l),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)},l=()=>{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",l),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(`
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
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
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 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=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]
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
@@ -526,9 +526,9 @@ Examples:
526
526
  entrydesk usage --sort-by operations # Sort by operation count
527
527
  entrydesk usage --json # JSON output
528
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 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}
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.2")}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.4")}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 Gr(e){if(e.help){tn();return}let t,r=(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",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:l}=await s.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 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 l=a.id===r?" (current)":"";console.log(` ${a.name}${l}`),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(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[++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(l=>l.trim()).filter(Boolean)}else if(i==="--capabilities"){let a=e[++s];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--conversation-starters"){let a=e[++s];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--tools"){let a=e[++s];n.tools=a?.split(",").map(l=>l.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(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(i==="--days-of-month"){let a=e[++s];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[++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();
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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entrydesk/cli",
3
- "version": "1.11.2",
3
+ "version": "1.11.4",
4
4
  "description": "EntryDesk CLI - Interact with EntryDesk from your terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,7 +31,7 @@
31
31
  "@types/node": "^24.12.0",
32
32
  "@types/react": "^19.2.9",
33
33
  "@vitest/coverage-v8": "^4.1.1",
34
- "happy-dom": "^20.0.11",
34
+ "happy-dom": "^20.8.9",
35
35
  "ink-testing-library": "^4.0.0",
36
36
  "memfs": "^4.51.1",
37
37
  "strip-ansi": "^7.1.2",