@entrydesk/cli 1.17.0 → 1.19.0

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 (34) hide show
  1. package/dist/agents-6IGSCA3S.js +43 -0
  2. package/dist/billing-SNTQDK4M.js +24 -0
  3. package/dist/{budget-LQAN6HWT.js → budget-7A4HH6LK.js} +1 -1
  4. package/dist/chunk-UXJD5BRR.js +4 -0
  5. package/dist/{config-SVZI7HKX.js → config-7SMTGR4C.js} +1 -1
  6. package/dist/{config-LOYERDQU.js → config-ZQUW7BQS.js} +1 -1
  7. package/dist/{config-help-BMF2KHCT.js → config-help-IJ6BGCBY.js} +1 -1
  8. package/dist/{connectors-JI4O4W5F.js → connectors-C35PPZM3.js} +1 -1
  9. package/dist/help-UAGSVZIZ.js +4 -0
  10. package/dist/index.js +1 -1
  11. package/dist/{login-WSBUXCFD.js → login-NL4DUGVI.js} +1 -1
  12. package/dist/{logout-ZBRMMAYT.js → logout-FVV6V2UU.js} +1 -1
  13. package/dist/{mcp-6V3TZE3Z.js → mcp-6JQHRC5J.js} +1 -1
  14. package/dist/{meeting-D6ASCE4N.js → meeting-I5NQ2V3L.js} +1 -1
  15. package/dist/{models-AFZZB3R5.js → models-YG7XKIZ2.js} +1 -1
  16. package/dist/{notifications-FAAD725V.js → notifications-NVWXUDN6.js} +1 -1
  17. package/dist/{profile-5AAPR2N6.js → profile-SYH6PEBO.js} +1 -1
  18. package/dist/{schedules-6OO7OBSJ.js → schedules-GPV52YWB.js} +1 -1
  19. package/dist/skills-E2JJSSGW.js +25 -0
  20. package/dist/{status-2WFXKYPI.js → status-JGVG5T6F.js} +1 -1
  21. package/dist/{task-5MMTKTBE.js → task-O7MFJEU2.js} +60 -35
  22. package/dist/tasks-VQ4SIVJG.js +41 -0
  23. package/dist/{tool-JW7GNF2H.js → tool-RZPDCROT.js} +6 -6
  24. package/dist/usage-LVG7HRCR.js +29 -0
  25. package/dist/{version-CU6Z4ZZC.js → version-4P4L2T22.js} +1 -1
  26. package/dist/{workflow-ZJTX5RAR.js → workflow-KHE2MKD5.js} +1 -1
  27. package/dist/{workspaces-PKE6XTQW.js → workspaces-ARL2DBCW.js} +1 -1
  28. package/package.json +1 -1
  29. package/dist/agents-PAPYAU3I.js +0 -30
  30. package/dist/chunk-TFQLXDTE.js +0 -4
  31. package/dist/help-B56RNLOB.js +0 -208
  32. package/dist/skills-GFCCO6ZE.js +0 -17
  33. package/dist/tasks-L7WU3FMX.js +0 -21
  34. package/dist/usage-AJA4SOXY.js +0 -18
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ import{h as I,q as A,r as O,t as v}from"./chunk-UXJD5BRR.js";import"./chunk-KURQCTT3.js";var h="\x1B[2m",c="\x1B[0m",p="\x1B[36m",T="\x1B[33m",b="\x1B[32m",R="stream-json";function f(t,n){let r=n===void 0?{event:t}:{event:t,data:n};process.stdout.write(`${JSON.stringify(r)}
3
+ `)}function S(t){let n=new Date(t),e=new Date().getTime()-n.getTime(),o=Math.floor(e/(1e3*60*60*24));return o===0?n.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):o===1?"Yesterday":o<7?`${o} days ago`:n.toLocaleDateString("en-US",{month:"short",day:"numeric"})}var M="\x1B[1m";function j(t){return t.replace(/<mark>/g,M).replace(/<\/mark>/g,c).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}function w(t,n){if(n)return t;let r=t.split(`
4
+ `);if(r.length<=15)return t;let e=r.slice(0,6),o=r.slice(-4),i=r.length-10;return[...e,`... (${i} lines omitted, use --full-output to see all) ...`,...o].join(`
5
+ `)}function N(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(N);let n={};for(let[r,e]of Object.entries(t))typeof e=="string"&&e.length>200?n[r]=e.slice(0,150)+"... (truncated)":typeof e=="object"&&e!==null?n[r]=N(e):n[r]=e;return n}function J(t){if(!t||typeof t!="object")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}}function E(t,n){if(!t)return"(no result)";if(typeof t!="object")return w(String(t),n);let r=n?t:N(t);if("structuredContent"in r&&r.structuredContent){let e=r.structuredContent,o=[];if(e.stdout&&typeof e.stdout=="string"&&e.stdout.trim()&&o.push(e.stdout.trim()),e.stderr&&typeof e.stderr=="string"&&e.stderr.trim()&&o.push(`${T}[stderr]${c} ${e.stderr.trim()}`),e.urls&&Array.isArray(e.urls)){let i=e.urls;for(let s of i)s.path&&s.url&&o.push(`${s.path}: ${s.url}`)}return o.length===0&&o.push(JSON.stringify(e,null,2)),w(o.join(`
6
+ `),n)}if("content"in r&&Array.isArray(r.content)){let o=r.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
7
+ `);return w(o||JSON.stringify(t,null,2),n)}return w(JSON.stringify(t,null,2),n)}function D(t){if(typeof t.title=="string")return t.title;if(typeof t.toolName=="string")return t.toolName;let n=t.type;return n.startsWith("tool-")?n.slice(5).replace(/__/g," ").replace(/_/g," "):n}function L(t,n){let r=[];for(let e of t)if(e.type==="reasoning"&&e.text)r.push(`${h}${e.text}${c}`);else if(e.type==="text"&&e.text)r.push(e.text);else if(e.type==="tool-call"&&e.toolName){let o=[];if(o.push(`${p}\u250C\u2500 Tool Call: ${e.toolName}${c}`),e.args){o.push(`${T}\u2502 Arguments:${c}`);let i=J(e.args);for(let s of i.split(`
8
+ `))o.push(`${h}\u2502 ${s}${c}`)}if(e.result!==void 0){o.push(`${b}\u2502 Result:${c}`);let i=E(e.result,n);for(let s of i.split(`
9
+ `))o.push(`${h}\u2502 ${s}${c}`);o.push(`${p}\u2514\u2500 ${e.toolName} completed${c}`)}else e.state==="call"?o.push(`${p}\u2514\u2500 (awaiting result)${c}`):o.push(`${p}\u2514\u2500${c}`);r.push(o.join(`
10
+ `))}else if(e.type.startsWith("tool-")&&e.type!=="tool-call"){let o=D(e),i=[];if(i.push(`${p}\u250C\u2500 Tool: ${o}${c}`),e.input){i.push(`${T}\u2502 Input:${c}`);let s=J(e.input);for(let l of s.split(`
11
+ `))i.push(`${h}\u2502 ${l}${c}`)}if(e.output!==void 0&&e.state==="output-available"){i.push(`${b}\u2502 Output:${c}`);let s=E(e.output,n);for(let l of s.split(`
12
+ `))i.push(`${h}\u2502 ${l}${c}`);i.push(`${p}\u2514\u2500 completed${c}`)}else e.state==="call"||e.state==="partial-call"?i.push(`${p}\u2514\u2500 (in progress)${c}`):i.push(`${p}\u2514\u2500${c}`);r.push(i.join(`
13
+ `))}return r.join(`
14
+
15
+ `).trim()}function U(){console.log(`
16
+ Usage: entrydesk tasks [taskId] [options]
17
+
18
+ List your tasks, search them, or view a single task's messages.
19
+
20
+ Options:
21
+ -q, --search <query> Filter tasks by a search query
22
+ --limit <n> Max tasks to return (1-50)
23
+ --next-key <key> Pagination cursor from a previous page
24
+ -s, --share <shareId> View a shared task's messages (no login needed)
25
+ --output stream-json Stream a task's messages as JSON events
26
+ --full-output Show full tool outputs when viewing a task
27
+ --json Output JSON
28
+
29
+ Examples:
30
+ entrydesk tasks # List recent tasks
31
+ entrydesk tasks -q "deploy" --limit 20 # Search tasks
32
+ entrydesk tasks <taskId> # View a task's messages
33
+ entrydesk tasks <taskId> --full-output # ...with full tool outputs
34
+ entrydesk tasks -s <shareId> # View a shared task
35
+ `)}async function q(t){if(t.help){U();return}let n=t.output===R;t.output&&!n&&(console.error(`Invalid --output value. Supported: ${R}`),process.exit(1));let r=new I;if(t.shareId){let s;try{s=await A()}catch{}try{let l=await r.getSharedTask(t.shareId,s),{messages:a}=await r.getSharedMessages(t.shareId,50,s);if(t.json){console.log(JSON.stringify({task:l,messages:a}));return}if(n){if(f("task",l),a.length===0)f("info","No messages in this shared task.");else for(let u of a.toReversed())f("message",u);f("done");return}if(console.log(`Shared Task: ${l.title||"Untitled"}`),console.log(`Visibility: ${l.visibility}`),l.agent&&console.log(`Agent: ${l.agent.name}`),console.log(`${a.length} messages
36
+ `),a.length===0){console.log("No messages in this shared task.");return}let d=a.toReversed(),$=t.fullOutput??!1;for(let u of d){let y=L(u.parts,$);if(!y)continue;let x=u.role==="user"?"You":"Assistant";console.log(`[${x}] ${S(u.createdAt)}`),console.log(y),console.log("")}return}catch(l){if(l instanceof Error){let a=l.message.toLowerCase();a.includes("401")||a.includes("unauthorized")?console.error("Access denied. This shared task requires authentication or is not accessible to you."):a.includes("404")||a.includes("not found")?console.error("Shared task not found. The share ID may be invalid or the task was deleted."):console.error(`Failed to fetch shared task: ${l.message}`)}else console.error("Failed to fetch shared task");process.exit(1)}}let e,o;try{let s=await O();e=s.accessToken,o=s.workspaceId}catch(s){v(s)}if(t.taskId){let s=t.taskId,l=!1,a=null,d=parseInt(t.taskId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(t.taskId)){let g=d===0?1:d,{tasks:k}=await r.getTasks(e,o,20);g>k.length&&(console.error(`Task number ${g} not found. You have ${k.length} recent tasks.`),process.exit(1));let m=k[g-1];s=m.id,l=!0,a=m,n||console.log(`Task: ${m.title||"Untitled"}
37
+ `)}let{messages:u}=await r.getMessages(e,o,s,50);if(t.json){console.log(JSON.stringify(u));return}if(n){if(a&&f("task",a),u.length===0)f("info","No messages in this task.");else for(let g of u.toReversed())f("message",g);f("done");return}if(u.length===0){console.log("No messages in this task.");return}let y=u.toReversed(),x=t.fullOutput??!1;l||console.log(`Task: ${t.taskId.slice(0,8)}...`),console.log(`${u.length} messages
38
+ `);for(let g of y){let k=L(g.parts,x);if(!k)continue;let m=g.role==="user"?"You":"Assistant";console.log(`[${m}] ${S(g.createdAt)}`),console.log(k),console.log("")}return}if(t.search){let{results:s,nextKey:l}=await r.searchTasks(e,o,t.search,{limit:t.limit,nextKey:t.nextKey});if(n){for(let a of s)f("task",a);f("done");return}if(t.json){console.log(JSON.stringify({results:s,nextKey:l}));return}if(s.length===0){console.log(`No tasks match "${t.search}".`);return}console.log(`Search results for "${t.search}" (${s.length}):
39
+ `),s.forEach((a,d)=>{let $=(d+1).toString().padStart(2," "),u=a.titleHighlight?j(a.titleHighlight):a.title||"Untitled";console.log(` ${$}. ${h}${S(a.createdAt)}${c} ${u}`),a.contentSnippet&&console.log(` ${j(a.contentSnippet)}`),console.log(` ${h}ID: ${a.id}${c}`)}),l&&console.log(`
40
+ Next page: --next-key ${l}`);return}let{tasks:i}=await r.getTasks(e,o,20);if(n){for(let s of i)f("task",s);f("done");return}if(t.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No tasks found.");return}console.log(`Recent Tasks (${i.length}):
41
+ `),i.forEach((s,l)=>{let a=(l+1).toString().padStart(2," ");console.log(` ${a}. ${S(s.createdAt).padEnd(12)} ${s.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk tasks 1` to view the most recent task"),console.log('Use `entrydesk task -c 1 -m "message"` to continue it')}export{U as printTasksHelp,j as renderHighlight,q as runTasks};
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{c as S,q as _}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";import B from"fs";import{Client as L}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as x}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function A(e={}){let t=e.apiUrl,n=e.accessToken,o=e.workspaceId;if(!n||!o){let l=await _();n=n||l.accessToken,o=o||l.workspaceId}t||(t=S().apiUrl);let i=new L({name:"entrydesk-cli",version:"1.0.0"}),s=new URL(`${t}/v1/workspaces/${o}/mcp`),r=new x(s,{requestInit:{headers:{Authorization:`Bearer ${n}`}}});return await i.connect(r),i}async function T(){return A()}import h from"fs/promises";import v from"os";import d from"path";var y=!process.env.NO_COLOR&&!!process.stdout.isTTY,p={green:y?"\x1B[32m":"",yellow:y?"\x1B[33m":"",reset:y?"\x1B[0m":""},D=10*1024,O=8*1024,I=2*1024,P=100,b=100;function M(){return d.join(v.homedir(),".entrydesk","tool-results")}function F(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,P);return!t||t==="."||t===".."?"unnamed_tool":t}function J(e){try{return JSON.stringify(e,(t,n)=>typeof n=="bigint"?`${n}n`:typeof n=="function"?"[Function]":typeof n=="symbol"?n.toString():n,2)}catch{return String(e)}}function U(e){let t=new Date,n=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),o=F(e);return`${n}_${o}.json`}async function N(e,t){try{return await h.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="EEXIST")return!1;throw n}}async function C(e,t){try{let n=M();await h.mkdir(n,{recursive:!0});let o=U(e),i=d.extname(o),s=o.slice(0,-i.length),r=J(t),l=d.join(n,o);if(await N(l,r))return l;for(let c=1;c<=b;c++){let w=d.join(n,`${s}-${c}${i}`);if(await N(w,r))return w}let u=Math.random().toString(36).slice(2,10),a=d.join(n,`${s}-${u}${i}`);return await h.writeFile(a,r,{encoding:"utf8",flag:"wx"}),a}catch(n){let o=n instanceof Error?n.message:"unknown error";return console.error(`${p.yellow}Warning: Could not save result to file: ${o}${p.reset}`),null}}function k(e,t){let n=Buffer.byteLength(e,"utf8");if(n<=D)return e;let o=e.slice(0,O),i=e.slice(-I),r=((n-O-I)/1024).toFixed(1),l=(n/1024).toFixed(1),u=` ... (skipped ${r}KB of ${l}KB) ...`;return t&&(u+=`
2
+ import{c as S,r as _}from"./chunk-UXJD5BRR.js";import"./chunk-KURQCTT3.js";import R from"fs";import{Client as L}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as v}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function A(e={}){let t=e.apiUrl,n=e.accessToken,o=e.workspaceId;if(!n||!o){let l=await _();n=n||l.accessToken,o=o||l.workspaceId}t||(t=S().apiUrl);let i=new L({name:"entrydesk-cli",version:"1.0.0"}),s=new URL(`${t}/v1/workspaces/${o}/mcp`),r=new v(s,{requestInit:{headers:{Authorization:`Bearer ${n}`}}});return await i.connect(r),i}async function T(){return A()}import h from"fs/promises";import D from"os";import d from"path";var y=!process.env.NO_COLOR&&!!process.stdout.isTTY,p={green:y?"\x1B[32m":"",yellow:y?"\x1B[33m":"",reset:y?"\x1B[0m":""},P=10*1024,O=8*1024,I=2*1024,b=100,M=100;function U(){return d.join(D.homedir(),".entrydesk","tool-results")}function F(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,b);return!t||t==="."||t===".."?"unnamed_tool":t}function J(e){try{return JSON.stringify(e,(t,n)=>typeof n=="bigint"?`${n}n`:typeof n=="function"?"[Function]":typeof n=="symbol"?n.toString():n,2)}catch{return String(e)}}function B(e){let t=new Date,n=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),o=F(e);return`${n}_${o}.json`}async function N(e,t){try{return await h.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n instanceof Error&&"code"in n&&n.code==="EEXIST")return!1;throw n}}async function C(e,t){try{let n=U();await h.mkdir(n,{recursive:!0});let o=B(e),i=d.extname(o),s=o.slice(0,-i.length),r=J(t),l=d.join(n,o);if(await N(l,r))return l;for(let c=1;c<=M;c++){let w=d.join(n,`${s}-${c}${i}`);if(await N(w,r))return w}let u=Math.random().toString(36).slice(2,10),a=d.join(n,`${s}-${u}${i}`);return await h.writeFile(a,r,{encoding:"utf8",flag:"wx"}),a}catch(n){let o=n instanceof Error?n.message:"unknown error";return console.error(`${p.yellow}Warning: Could not save result to file: ${o}${p.reset}`),null}}function k(e,t){let n=Buffer.byteLength(e,"utf8");if(n<=P)return e;let o=e.slice(0,O),i=e.slice(-I),r=((n-O-I)/1024).toFixed(1),l=(n/1024).toFixed(1),u=` ... (skipped ${r}KB of ${l}KB) ...`;return t&&(u+=`
3
3
  Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${o}
4
4
 
5
5
  ${u}
6
6
 
7
- ${i}`}function $(e){console.log(`${p.green}Tool execution result saved to: ${e}${p.reset}`),console.log()}function E(){console.log(`${p.green}Tool execution result:${p.reset}`)}function R(e){return e.split("__")[0]??e}function f(e,t,n){console.error(n?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function g(e,t,n="CONNECTION_FAILED"){let o=e instanceof Error?e.message:"Unknown error";o.includes("Not logged in")||o.includes("not-logged-in")?f("AUTH_MISSING",o,t):f(n,o,t)}async function H(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],n=!1,o=!1,i,s,r,l,u=()=>{clearTimeout(i),process.stdin.removeListener("data",s),process.stdin.removeListener("end",r),process.stdin.removeListener("error",l)},a=c=>{o||(o=!0,u(),e(c))};s=c=>{n=!0,clearTimeout(i),t.push(c)},r=()=>{t.length===0?a(null):a(Buffer.concat(t).toString("utf-8").trim())},l=()=>{a(null)},i=setTimeout(()=>{n||a(null)},100),process.stdin.on("data",s),process.stdin.on("end",r),process.stdin.on("error",l),process.stdin.resume()})}var m=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Y(e,t){if(e)return e;if(t)try{return B.readFileSync(t,"utf-8").trim()}catch(o){let i=o instanceof Error?o.message:"Failed to read input file";throw new m(`Failed to read input file: ${i}`)}let n=await H();if(n)return n;throw new m("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function V(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
8
- `)}function q(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(`
9
- `)}async function X(e,t){let n=await T().catch(o=>{g(o,e)});try{let i=(await n.listTools()).tools;if(t){let s=t.toLowerCase();i=i.filter(r=>R(r.name).toLowerCase().startsWith(s))}if(e)console.log(JSON.stringify(i,null,2));else{let s=t?` (prefix: ${t})`:"";console.log(`Available Tools (${i.length})${s}:
10
- `);for(let r of i)console.log(V(r)),console.log()}}catch(o){g(o,e)}finally{await n.close().catch(()=>{})}}async function z(e,t){let n=await T().catch(o=>{g(o,t)});try{let i=(await n.listTools()).tools.find(s=>s.name===e);i||f("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(i,null,2):q(i))}catch(o){g(o,t)}finally{await n.close().catch(()=>{})}}async function G(e,t,n){let o;try{o=JSON.parse(t)}catch(r){let l=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";f("INVALID_INPUT",l,n)}let i=await T().catch(r=>{g(r,n,"TOOL_CALL_FAILED")}),s=!1;try{let r=await i.callTool({name:e,arguments:o});if(n)console.log(JSON.stringify(r,null,2));else{let l=await C(e,r);l&&$(l),E();let u=r.content;for(let a of u)a.type==="text"?console.log(a.text):a.type==="image"?console.log(`[Image: ${a.mimeType}]`):a.type==="resource"?console.log(`[Resource: ${a.resource?.uri??"unknown"}]`):console.log(JSON.stringify(a,null,2));if(r.structuredContent){let a=JSON.stringify(r.structuredContent,null,2),c=k(a,l);console.log(c)}}r.isError&&(s=!0)}catch(r){g(r,n,"TOOL_CALL_FAILED")}finally{await i.close().catch(()=>{})}s&&process.exit(1)}async function lt(e){let t=e.json??!1;switch(e.action){case"list":await X(t,e.prefix);break;case"get":e.name||f("INVALID_INPUT","Tool name is required",t),await z(e.name,t);break;case"call":{e.name||f("INVALID_INPUT","Tool name is required",t);let n;try{n=await Y(e.input,e.inputFile)}catch(o){throw o instanceof m&&f("INVALID_INPUT",o.message,t),o}await G(e.name,n,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
7
+ ${i}`}function $(e){console.log(`${p.green}Tool execution result saved to: ${e}${p.reset}`),console.log()}function E(){console.log(`${p.green}Tool execution result:${p.reset}`)}function H(e){return e.split("__")[0]??e}function f(e,t,n){console.error(n?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function g(e,t,n="CONNECTION_FAILED"){let o=e instanceof Error?e.message:"Unknown error";o.includes("Not logged in")||o.includes("not-logged-in")?f("AUTH_MISSING",o,t):f(n,o,t)}async function Y(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],n=!1,o=!1,i,s,r,l,u=()=>{clearTimeout(i),process.stdin.removeListener("data",s),process.stdin.removeListener("end",r),process.stdin.removeListener("error",l)},a=c=>{o||(o=!0,u(),e(c))};s=c=>{n=!0,clearTimeout(i),t.push(c)},r=()=>{t.length===0?a(null):a(Buffer.concat(t).toString("utf-8").trim())},l=()=>{a(null)},i=setTimeout(()=>{n||a(null)},100),process.stdin.on("data",s),process.stdin.on("end",r),process.stdin.on("error",l),process.stdin.resume()})}var m=class extends Error{constructor(t){super(t),this.name="InputError"}};async function V(e,t){if(e)return e;if(t)try{return R.readFileSync(t,"utf-8").trim()}catch(o){let i=o instanceof Error?o.message:"Failed to read input file";throw new m(`Failed to read input file: ${i}`)}let n=await Y();if(n)return n;throw new m("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function q(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
8
+ `)}function X(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(`
9
+ `)}async function z(e,t){let n=await T().catch(o=>{g(o,e)});try{let i=(await n.listTools()).tools;if(t){let s=t.toLowerCase();i=i.filter(r=>H(r.name).toLowerCase().startsWith(s))}if(e)console.log(JSON.stringify(i,null,2));else{let s=t?` (prefix: ${t})`:"";console.log(`Available Tools (${i.length})${s}:
10
+ `);for(let r of i)console.log(q(r)),console.log()}}catch(o){g(o,e)}finally{await n.close().catch(()=>{})}}async function G(e,t){let n=await T().catch(o=>{g(o,t)});try{let i=(await n.listTools()).tools.find(s=>s.name===e);i||f("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(i,null,2):X(i))}catch(o){g(o,t)}finally{await n.close().catch(()=>{})}}async function K(e,t,n){let o;try{o=JSON.parse(t)}catch(r){let l=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";f("INVALID_INPUT",l,n)}let i=await T().catch(r=>{g(r,n,"TOOL_CALL_FAILED")}),s=!1;try{let r=await i.callTool({name:e,arguments:o});if(n)console.log(JSON.stringify(r,null,2));else{let l=await C(e,r);l&&$(l),E();let u=r.content;for(let a of u)a.type==="text"?console.log(a.text):a.type==="image"?console.log(`[Image: ${a.mimeType}]`):a.type==="resource"?console.log(`[Resource: ${a.resource?.uri??"unknown"}]`):console.log(JSON.stringify(a,null,2));if(r.structuredContent){let a=JSON.stringify(r.structuredContent,null,2),c=k(a,l);console.log(c)}}r.isError&&(s=!0)}catch(r){g(r,n,"TOOL_CALL_FAILED")}finally{await i.close().catch(()=>{})}s&&process.exit(1)}function x(){console.log(`Usage: entrydesk tool <action> [options]
11
11
 
12
12
  Actions:
13
13
  list List all available tools
@@ -32,4 +32,4 @@ Examples:
32
32
  entrydesk tool call agent__search_agents --input '{"limit": 5}'
33
33
  entrydesk tool call agent__search_agents --input-file input.json
34
34
  echo '{"limit": 5}' | entrydesk tool call agent__search_agents
35
- `);break}}export{m as InputError,Y as getInputJson,H as readStdin,lt as runTool};
35
+ `)}async function at(e){let t=e.json??!1;if(e.help){x();return}switch(e.action){case"list":await z(t,e.prefix);break;case"get":e.name||f("INVALID_INPUT","Tool name is required",t),await G(e.name,t);break;case"call":{e.name||f("INVALID_INPUT","Tool name is required",t);let n;try{n=await V(e.input,e.inputFile)}catch(o){throw o instanceof m&&f("INVALID_INPUT",o.message,t),o}await K(e.name,n,t);break}default:x();break}}export{m as InputError,V as getInputJson,x as printToolUsage,Y as readStdin,at as runTool};
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ import{h as d,r as y,t as U}from"./chunk-UXJD5BRR.js";import"./chunk-KURQCTT3.js";import{writeFileSync as S}from"fs";function $(){console.log(`
3
+ Usage: entrydesk usage [balance|me|consumptions|export] [options]
4
+
5
+ Commands:
6
+ (default) Per-user monthly cost/operations summary
7
+ balance Workspace USD balance, spend, and limits
8
+ me Your own usage and availability
9
+ consumptions Per-user extra-usage breakdown (--limit/--offset)
10
+ export Export per-user usage as CSV (-o <file>, else stdout)
11
+
12
+ Options:
13
+ --limit <number> Limit rows (default: all for summary; 20 for consumptions)
14
+ --sort-by cost|operations Sort the summary by cost or operations (default: cost)
15
+ --offset <number> Offset for consumptions pagination
16
+ --period-start <ISO> Period start for consumptions/export
17
+ -o, --output <file> Write export CSV to a file (default: stdout)
18
+ --json Output JSON
19
+
20
+ Examples:
21
+ entrydesk usage balance
22
+ entrydesk usage me
23
+ entrydesk usage consumptions --limit 20
24
+ entrydesk usage export -o usage.csv
25
+ `)}function s(o){return`$${o.toFixed(2)}`}function C(o){console.log(`Extra-usage balance: ${s(o.balanceUsd)}`);let n=o.currentSpentUsedPercent!=null?` (${o.currentSpentUsedPercent}% of limit)`:"";console.log(`Spent this period: ${s(o.currentSpentUsd)}${n}`),o.monthlyExtraUsageLimitUsd!=null&&console.log(`Workspace limit: ${s(o.monthlyExtraUsageLimitUsd)} / month`),o.memberMonthlyExtraUsageLimitUsd!=null&&console.log(`Per-member limit: ${s(o.memberMonthlyExtraUsageLimitUsd)} / month`),o.nextExpiry&&console.log(`Next expiry: ${s(o.nextExpiry.amountUsd)} at ${new Date(o.nextExpiry.expiresAt).toLocaleString()}`),console.log(`Period: ${new Date(o.period.startAt).toLocaleDateString()} \u2013 ${new Date(o.period.endAt).toLocaleDateString()}`)}function b(o){console.log(`Seat type: ${o.seatType}`),o.hourly&&console.log(`Hourly used: ${o.hourly.usedPercent}%`),console.log(`Weekly used: ${o.weekly.usedPercent}%`),console.log(`Extra spent: ${s(o.extraUsage.spentUsd)}`),console.log(`Available: ${o.availability.allowed?"yes":`no (${o.availability.reason??"unknown"})`}`),o.trial&&console.log(`Trial: ${o.trial.remainingDays} days remaining`)}function k(o){console.log(`Consumptions (${o.items.length} of ${o.total}):
26
+ `);for(let n of o.items)console.log(` ${n.user.name} (${n.user.email})`),console.log(` Seat: ${n.seatType} \xB7 Extra usage: ${s(n.extraUsage)}`),console.log(` User ID: ${n.user.id}`),console.log("")}async function P(o){if(o.help){$();return}let n,i;try{let e=await y();n=e.accessToken,i=e.workspaceId}catch(e){let a=e instanceof Error?e.message:"Authentication failed";console.error(a),process.exit(1)}let r=new d;try{if(o.action==="balance"){let t=await r.getUsageOverview(n,i);if(o.json){console.log(JSON.stringify(t));return}C(t);return}if(o.action==="me"){let t=await r.getUsageMe(n,i);if(o.json){console.log(JSON.stringify(t));return}b(t);return}if(o.action==="consumptions"){let t=await r.getUsageConsumptions(n,i,{limit:o.limit,offset:o.offset,periodStart:o.periodStart});if(o.json){console.log(JSON.stringify(t));return}if(t.items.length===0){console.log("No consumptions for this period.");return}k(t);return}if(o.action==="export"){let t=await r.exportUsageCsv(n,i,o.periodStart);o.output?(S(o.output,t),console.log(`Wrote usage CSV to ${o.output}`)):process.stdout.write(t);return}o.action&&(console.error(`Unknown usage command: ${o.action}`),$(),process.exit(1));let e=[],a,u=0,h=100;do{let t=await r.getMonthlyUsages(n,i,{nextKey:a,limit:100});if(e.push(...t.monthlyUsages),a=t.nextKey,u++,u>=h){console.error(`Warning: Showing first ${e.length} entries (pagination limit reached)`);break}}while(a);if(o.json){console.log(JSON.stringify(e));return}if(e.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
27
+ `);let g=0,p=0;for(let t of e)g+=parseFloat(t.totalCost),p+=t.operationCount;console.log(`Total Cost: $${g.toFixed(2)}`),console.log(`Total Operations: ${p.toLocaleString()}`),console.log(`Users: ${e.length}
28
+ `);let m=o.sortBy||"cost",f=[...e].toSorted((t,c)=>m==="cost"?parseFloat(c.totalCost)-parseFloat(t.totalCost):c.operationCount-t.operationCount),x=o.limit&&o.limit>0?o.limit:f.length,l=f.slice(0,x);console.log(`Usage by User (sorted by ${m}, showing ${l.length} of ${e.length}):
29
+ `);for(let t of l){let c=parseFloat(t.totalCost);console.log(` ${t.user.name} (${t.user.email})`),console.log(` Cost: $${c.toFixed(2)}`),console.log(` Operations: ${t.operationCount.toLocaleString()}`),console.log("")}l.length<e.length&&console.log(`... and ${e.length-l.length} more users`)}catch(e){U(e)}}export{P as runUsage};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import"./chunk-KURQCTT3.js";function n(){console.log("entrydesk 1.17.0")}export{n as printVersion};
2
+ import"./chunk-KURQCTT3.js";function n(){console.log("entrydesk 1.19.0")}export{n as printVersion};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{h as u,q as p,s as g}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";import{readFileSync as $}from"fs";var k=262144,x=new Set(["completed","failed","cancelled"]);function f(){console.log(`
2
+ import{h as u,r as p,t as g}from"./chunk-UXJD5BRR.js";import"./chunk-KURQCTT3.js";import{readFileSync as $}from"fs";var k=262144,x=new Set(["completed","failed","cancelled"]);function f(){console.log(`
3
3
  Usage: entrydesk workflow [list|get|create|update|run|runs|run-get|share] [options]
4
4
 
5
5
  Commands:
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{g as a,h as w,p as k}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";function l(){console.log(`
2
+ import{g as a,h as w,q as k}from"./chunk-UXJD5BRR.js";import"./chunk-KURQCTT3.js";function l(){console.log(`
3
3
  Usage: entrydesk workspaces [list|switch|use] [options]
4
4
 
5
5
  Commands:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entrydesk/cli",
3
- "version": "1.17.0",
3
+ "version": "1.19.0",
4
4
  "description": "EntryDesk CLI - Interact with EntryDesk from your terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env node
2
- import{h as f,q as u,s as y}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";function g(){console.log(`
3
- Usage: entrydesk agents [list|create|update|delete] [options]
4
-
5
- Commands:
6
- list List available agents (default)
7
- create Create a new agent
8
- update <agentId> Update an agent you own
9
- delete <agentId> Delete an agent you own
10
-
11
- Create/Update Options:
12
- --name <name>
13
- --description <text>
14
- --system-prompt <text>
15
- --model-id <modelId>
16
- --connector-ids id1,id2
17
- --capabilities sandbox,web_search,image_generation,chart
18
- --conversation-starters s1,s2,s3
19
- --tools prefix__tool1,prefix__tool2
20
- --icon-id <iconId>
21
-
22
- List Options:
23
- --limit <number> Max agents per page; also page size for --all (default: 100)
24
- --next-key <cursor> Fetch next page using cursor
25
- --all Fetch all agents (auto-paginate)
26
-
27
- Flags:
28
- --json Output JSON
29
- `)}function I(e){if(!e)return[];let n=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=>n.get(o)??o)}function A(e){console.log(`Available Agents (${e.length}):
30
- `);for(let n of e){if(console.log(` ${n.name} (${n.visibility})`),n.description){let o=n.description.length>80?`${n.description.slice(0,80)}...`:n.description;console.log(` ${o}`)}console.log(` ID: ${n.id}`),console.log("")}}function w(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),g(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:I(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function _(e){try{if(e.help){g();return}let n=await u(),{accessToken:o,workspaceId:s}=n,r=e.action||"list",a=new f;if(r==="create"){let i=w(e),t=await a.createAgent(o,s,i);if(e.json){console.log(JSON.stringify(t));return}console.log(`Created agent: ${t.name}`),console.log(` ID: ${t.id}`);return}if(r==="update"){let i=e.agentId;if(!i)throw new Error("Missing agentId for update command");let t=await a.getAgent(o,s,i),c={name:e.name??t.name,description:e.description??t.description,systemPrompt:e.systemPrompt??t.systemPrompt??"",modelId:e.modelId??t.model?.id??"",connectorIds:e.connectorIds??t.connectors?.map(l=>l.id)??[],capabilities:e.capabilities?I(e.capabilities):t.capabilities??[],conversationStarters:e.conversationStarters??t.conversationStarters??[],tools:e.tools??t.tools??[],iconId:e.iconId??t.iconId};await a.updateAgent(o,s,i,c),console.log(`Updated agent: ${i}`);return}if(r==="delete"){let i=e.agentId;if(!i)throw new Error("Missing agentId for delete command");await a.deleteAgent(o,s,i),console.log(`Deleted agent: ${i}`);return}if(r!=="list"&&(console.error(`Unknown agents command: ${r}`),g(),process.exit(1)),e.all&&e.nextKey&&(console.error("Cannot use --all and --next-key together."),process.exit(1)),e.all){let t=[],c;for(let l=0;;l++){l>=100&&(console.error("Reached maximum page limit (100). Use --limit and --next-key for manual pagination."),process.exit(1));let m=await a.getAgents(o,s,{limit:e.limit??100,nextKey:c});if(t.push(...m.agents),c=m.nextKey,!c)break}if(e.json){console.log(JSON.stringify({agents:t}));return}if(t.length===0){console.log("No agents found in this workspace.");return}A(t);return}let{agents:d,nextKey:p}=await a.getAgents(o,s,{limit:e.limit,nextKey:e.nextKey});if(e.json){console.log(JSON.stringify({agents:d,nextKey:p}));return}if(d.length===0){console.log("No agents found in this workspace.");return}A(d),p&&console.log(`Next page: --next-key ${p}`)}catch(n){y(n)}}export{_ as runAgents};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import M from"fs";import y from"fs";import Me from"os";import E from"path";import{HTTPError as Ie,TimeoutError as Ue}from"ky";import{HTTPError as xe}from"ky";import we,{TimeoutError as ke,isHTTPError as ve}from"ky";import C from"crypto";import u from"fs";import de from"path";var ue="ENTRYDESK_FORCE_FILE_STORAGE",R="EntryDesk CLI",pe="__entrydesk_keychain_test__",fe="profile:",he=".credentials.key",Q={keychain:!1,permissions:!1,corruptFile:!1,windowsFile:!1};function k(r,e){Q[r]||(Q[r]=!0,console.error(e))}function ye(){return process.env.ENTRYDESK_DEBUG?.toLowerCase()==="true"}function ee(r){if(!r||typeof r!="object")return!1;let e=r;return!(!("accessToken"in e||"refreshToken"in e||"email"in e||"workspaceId"in e)||"accessToken"in e&&typeof e.accessToken!="string"||"refreshToken"in e&&typeof e.refreshToken!="string"||"email"in e&&typeof e.email!="string"||"workspaceId"in e&&typeof e.workspaceId!="string")}function me(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.getPassword=="function"&&typeof e.setPassword=="function"&&typeof e.deletePassword=="function"}function j(r){return o.getProfileCredentialsFile(r)}var z=class{getKeyFilePath(e){return de.join(o.getProfileDir(e),he)}loadEncryptionKey(e){let t=this.getKeyFilePath(e);try{if(!u.existsSync(t))return null;let s=u.readFileSync(t);return s.length!==32?null:(this.ensureSecureFilePermissions(t),s)}catch{return null}}createEncryptionKey(e){o.ensureProfileDir(e);let t=this.getKeyFilePath(e),s=C.randomBytes(32);return u.writeFileSync(t,s,{mode:384}),this.ensureSecureFilePermissions(t),s}getOrCreateEncryptionKey(e){let t=this.loadEncryptionKey(e);return t||this.createEncryptionKey(e)}encrypt(e,t){let s=C.randomBytes(16),n=C.createCipheriv("aes-256-gcm",t,s),i=n.update(e,"utf8","hex");i+=n.final("hex");let a=n.getAuthTag();return`${s.toString("hex")}:${a.toString("hex")}:${i}`}decrypt(e,t){let s=e.split(":");if(s.length!==3)throw new Error("Invalid encrypted data format");let n=Buffer.from(s[0],"hex"),i=Buffer.from(s[1],"hex"),a=s[2],S=C.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});S.setAuthTag(i);let d=S.update(a,"hex","utf8");return d+=S.final("utf8"),d}tryDecrypt(e,t){try{return this.decrypt(e,t)}catch{return null}}tryParseCredentials(e){try{let t=JSON.parse(e);return ee(t)?t:null}catch{return null}}ensureSecureFilePermissions(e){if(process.platform!=="win32"){try{u.chmodSync(e,384)}catch{k("permissions","Warning: Failed to set secure permissions on credentials file.");return}try{(u.statSync(e).mode&511)!==384&&k("permissions","Warning: Credentials file permissions are too permissive.")}catch{k("permissions","Warning: Failed to verify credentials file permissions.")}}}async getCredentials(e){let t=j(e);try{if(!u.existsSync(t))return null;let s=u.readFileSync(t,"utf-8").trim();if(!s)return null;let n=this.loadEncryptionKey(e),i=n?this.tryDecrypt(s,n):null;if(i){let a=this.tryParseCredentials(i);if(a)return a}return k("corruptFile","Warning: Credentials file is unreadable. Please run `entrydesk login` again."),null}catch{return null}}async setCredentials(e,t){o.ensureProfileDir(e);let s=j(e),n=this.getOrCreateEncryptionKey(e),i=this.encrypt(JSON.stringify(t),n);u.writeFileSync(s,i,{mode:384}),this.ensureSecureFilePermissions(s)}async deleteCredentials(e){let t=j(e);try{u.existsSync(t)&&u.unlinkSync(t)}catch{}}},N=class{keytarModule=null;keytarLoadAttempted=!1;keychainAvailable=null;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar"),s=t&&typeof t=="object"&&"default"in t?t.default:t;this.keytarModule=me(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${fe}${e}`}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${pe}${C.randomBytes(8).toString("hex")}`,s="test";await e.setPassword(R,t,s);let n=await e.getPassword(R,t),i=await e.deletePassword(R,t);return this.keychainAvailable=!!(i&&n===s),this.keychainAvailable}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let s=await t.getPassword(R,this.getAccount(e));if(!s)return null;let n=this.tryParseKeychainPayload(s);return n||k("corruptFile",`Warning: Keychain entry for profile "${e}" is unreadable.`),n}async setCredentials(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let s=await this.getKeytar();if(!s)throw new Error("Keytar module not available");let n=JSON.stringify(t);await s.setPassword(R,this.getAccount(e),n)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");await t.deletePassword(R,this.getAccount(e))}tryParseKeychainPayload(e){try{let t=JSON.parse(e);return ee(t)?t:null}catch{return null}}},O=class{keychainStorage=null;fileStorage=new z;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[ue]?.toLowerCase()==="true"}async initializeStorage(){if(this.shouldForceFileStorage()){this.keychainAvailable=!1,this.keychainStorage=null;return}try{let e=new N,t=await e.isAvailable();this.keychainAvailable=t,this.keychainStorage=t?e:null}catch{this.keychainAvailable=!1,this.keychainStorage=null}!this.keychainAvailable&&!this.shouldForceFileStorage()&&(ye()&&k("keychain","Keychain unavailable. Falling back to file-based credentials."),process.platform==="win32"&&k("windowsFile","Warning: File-based credentials on Windows may be readable by other users."))}async ensureInitialized(){if(this.shouldForceFileStorage()){this.keychainAvailable=!1,this.keychainStorage=null;return}this.keychainAvailable===null&&(this.initPromise??=this.initializeStorage(),await this.initPromise)}disableKeychain(){this.shouldForceFileStorage()||k("keychain","Keychain error encountered. Falling back to file-based credentials."),this.keychainAvailable=!1,this.keychainStorage=null}async getKeychainStorage(){return await this.ensureInitialized(),this.shouldForceFileStorage()?null:this.keychainAvailable?this.keychainStorage:null}async getCredentials(e){let t=await this.getKeychainStorage();if(!t)return this.fileStorage.getCredentials(e);try{let n=await t.getCredentials(e);if(n)return n}catch{return this.disableKeychain(),this.fileStorage.getCredentials(e)}let s=await this.fileStorage.getCredentials(e);if(s)try{await t.setCredentials(e,s),await this.fileStorage.deleteCredentials(e)}catch{}return s}async setCredentials(e,t){let s=await this.getKeychainStorage();if(!s){await this.fileStorage.setCredentials(e,t);return}try{await s.setCredentials(e,t),await this.fileStorage.deleteCredentials(e)}catch{this.disableKeychain(),await this.fileStorage.setCredentials(e,t)}}async deleteCredentials(e){let t=await this.getKeychainStorage();if(t)try{await t.deleteCredentials(e)}catch{this.disableKeychain()}await this.fileStorage.deleteCredentials(e)}},l=new O,p={async saveAccessToken(r,e){let t=o.getEffectiveProfileName(e),s=await l.getCredentials(t)??{};s.accessToken=r,await l.setCredentials(t,s)},async getAccessToken(r){let e=o.getEffectiveProfileName(r);return(await l.getCredentials(e))?.accessToken??null},async saveRefreshToken(r,e){let t=o.getEffectiveProfileName(e),s=await l.getCredentials(t)??{};s.refreshToken=r,await l.setCredentials(t,s)},async getRefreshToken(r){let e=o.getEffectiveProfileName(r);return(await l.getCredentials(e))?.refreshToken??null},async saveEmail(r,e){let t=o.getEffectiveProfileName(e),s=await l.getCredentials(t)??{};s.email=r,await l.setCredentials(t,s)},async getEmail(r){let e=o.getEffectiveProfileName(r);return(await l.getCredentials(e))?.email??null},async saveWorkspaceId(r,e){let t=o.getEffectiveProfileName(e),s=await l.getCredentials(t)??{};s.workspaceId=r,await l.setCredentials(t,s)},async getWorkspaceId(r){let e=o.getEffectiveProfileName(r);return(await l.getCredentials(e))?.workspaceId??null},async saveAll(r,e){let t=o.getEffectiveProfileName(e);await l.setCredentials(t,r)},async getAll(r){let e=o.getEffectiveProfileName(r);return l.getCredentials(e)},async clear(r){let e=o.getEffectiveProfileName(r);await l.deleteCredentials(e)},async isLoggedIn(r){let e=o.getEffectiveProfileName(r);return(await l.getCredentials(e))?.accessToken!=null}};var x=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||B(t),K().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=we.create({baseUrl:this.baseUrl.replace(/\/?$/,"/"),timeout:3e4,retry:{limit:3,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504]},hooks:{beforeError:[({error:n})=>(ve(n)&&(n.request.headers.delete("authorization"),n.request.headers.delete("Authorization")),n)]}})}getBaseUrl(){return this.baseUrl}async refreshOAuthToken(e){return this.client.post("v1/oauth/token",{json:{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}}).json()}async revokeOAuthToken(e){await this.client.post("v1/oauth/revoke",{json:{token:e.token,token_type_hint:"refresh_token",client_id:e.clientId}})}async getWorkspaces(e){try{return process.env.DEBUG&&console.log(`[DEBUG] Calling getWorkspaces API: ${this.baseUrl}/v1/workspaces`),await this.client.get("v1/workspaces",{headers:{Authorization:`Bearer ${e}`}}).json()}catch(t){throw process.env.DEBUG&&(console.error("[DEBUG] getWorkspaces error:",t),t instanceof Error&&"cause"in t&&console.error("[DEBUG] Error cause:",t.cause)),t}}async getAgents(e,t,s){let n={limit:s?.limit??100};return s?.nextKey&&(n.nextKey=s.nextKey),s?.search&&(n.search=s.search),await this.client.get(`v1/workspaces/${t}/availableAgents`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async createAgent(e,t,s){return await this.client.post(`v1/workspaces/${t}/agents`,{headers:{Authorization:`Bearer ${e}`},json:s}).json()}async updateAgent(e,t,s,n){await this.client.put(`v1/workspaces/${t}/agents/${s}`,{headers:{Authorization:`Bearer ${e}`},json:n})}async deleteAgent(e,t,s){await this.client.delete(`v1/workspaces/${t}/agents/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async getMeetings(e,t,s){let n={limit:s?.limit??20};return s?.nextKey&&(n.nextKey=s.nextKey),s?.search&&(n.search=s.search),s?.filter&&(n.filter=s.filter),s?.sortBy&&(n.sortBy=s.sortBy),await this.client.get(`v1/workspaces/${t}/meetings`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async getMeeting(e,t,s){return await this.client.get(`v1/workspaces/${t}/meetings/${s}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async createMeeting(e,t,s){return await this.client.post(`v1/workspaces/${t}/meetings`,{headers:{Authorization:`Bearer ${e}`},json:s}).json()}async updateMeeting(e,t,s,n){return await this.client.patch(`v1/workspaces/${t}/meetings/${s}`,{headers:{Authorization:`Bearer ${e}`},json:n}).json()}async deleteMeeting(e,t,s){await this.client.delete(`v1/workspaces/${t}/meetings/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async getMeetingPreviousBrief(e,t,s){return await this.client.get(`v1/workspaces/${t}/meetings/${s}/previous`,{headers:{Authorization:`Bearer ${e}`}}).json()}async getRecording(e,t,s){return await this.client.get(`v1/workspaces/${t}/recordings/${s}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async getMeetingShares(e,t,s){return await this.client.get(`v1/workspaces/${t}/meetings/${s}/shares`,{headers:{Authorization:`Bearer ${e}`}}).json()}async upsertMeetingUserGrant(e,t,s,n,i){return await this.client.put(`v1/workspaces/${t}/meetings/${s}/shares/users/${n}`,{headers:{Authorization:`Bearer ${e}`},json:{role:i}}).json()}async removeMeetingUserGrant(e,t,s,n){await this.client.delete(`v1/workspaces/${t}/meetings/${s}/shares/users/${n}`,{headers:{Authorization:`Bearer ${e}`}})}async upsertMeetingTeamGrant(e,t,s,n,i){return await this.client.put(`v1/workspaces/${t}/meetings/${s}/shares/teams/${n}`,{headers:{Authorization:`Bearer ${e}`},json:{role:i}}).json()}async removeMeetingTeamGrant(e,t,s,n){await this.client.delete(`v1/workspaces/${t}/meetings/${s}/shares/teams/${n}`,{headers:{Authorization:`Bearer ${e}`}})}async getWorkflows(e,t,s){let n={limit:s?.limit??20};return s?.nextKey&&(n.nextKey=s.nextKey),s?.search&&(n.search=s.search),await this.client.get(`v1/workspaces/${t}/workflows`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async getWorkflow(e,t,s){return await this.client.get(`v1/workspaces/${t}/workflows/${s}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async createWorkflow(e,t,s){return await this.client.post(`v1/workspaces/${t}/workflows`,{headers:{Authorization:`Bearer ${e}`},json:s}).json()}async updateWorkflow(e,t,s,n){await this.client.put(`v1/workspaces/${t}/workflows/${s}`,{headers:{Authorization:`Bearer ${e}`},json:n})}async triggerWorkflowRun(e,t,s,n){return await this.client.post(`v1/workspaces/${t}/workflows/${s}/runs`,{headers:{Authorization:`Bearer ${e}`},json:n===void 0?{}:{args:n}}).json()}async getWorkflowRuns(e,t,s,n){let i={limit:n?.limit??20};return n?.nextKey&&(i.nextKey=n.nextKey),await this.client.get(`v1/workspaces/${t}/workflows/${s}/runs`,{headers:{Authorization:`Bearer ${e}`},searchParams:i}).json()}async getWorkflowRun(e,t,s,n){return await this.client.get(`v1/workspaces/${t}/workflows/${s}/runs/${n}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async getWorkflowGrants(e,t,s){return await this.client.get(`v1/workspaces/${t}/workflows/${s}/grants`,{headers:{Authorization:`Bearer ${e}`}}).json()}async upsertWorkflowGrant(e,t,s,n,i){return await this.client.put(`v1/workspaces/${t}/workflows/${s}/grants/${n}`,{headers:{Authorization:`Bearer ${e}`},json:{role:i}}).json()}async removeWorkflowGrant(e,t,s,n){await this.client.delete(`v1/workspaces/${t}/workflows/${s}/grants/${n}`,{headers:{Authorization:`Bearer ${e}`}})}async getNotifications(e,t,s){let n={limit:s?.limit??20};return s?.tab&&(n.tab=s.tab),s?.eventType&&(n.eventType=s.eventType),s?.cursor&&(n.cursor=s.cursor),await this.client.get(`v1/workspaces/${t}/notifications`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async getNotificationUnreadCount(e,t){return await this.client.get(`v1/workspaces/${t}/notifications/unreadCount`,{headers:{Authorization:`Bearer ${e}`}}).json()}async markNotificationRead(e,t,s){await this.client.post(`v1/workspaces/${t}/notifications/${s}/read`,{headers:{Authorization:`Bearer ${e}`}})}async markAllNotificationsRead(e,t){await this.client.post(`v1/workspaces/${t}/notifications/readAll`,{headers:{Authorization:`Bearer ${e}`}})}async getModels(e,t){return await this.client.get(`v1/workspaces/${t}/models`,{headers:{Authorization:`Bearer ${e}`}}).json()}async getConnectors(e,t){return await this.client.get(`v1/workspaces/${t}/availableConnectors`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:100,connectionStatus:"connected"}}).json()}async getTasks(e,t,s=20){return await this.client.get(`v1/workspaces/${t}/tasks`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:s}}).json()}async searchTasks(e,t,s,n){let i={q:s,limit:n?.limit??20};return n?.nextKey&&(i.nextKey=n.nextKey),await this.client.get(`v1/workspaces/${t}/tasks/search`,{headers:{Authorization:`Bearer ${e}`},searchParams:i}).json()}async getMessages(e,t,s,n=50){return await this.client.get(`v1/workspaces/${t}/tasks/${s}/messages`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:n}}).json()}async getAgent(e,t,s){return await this.client.get(`v1/workspaces/${t}/agents/${s}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async listAvailableSkills(e,t,s){return await this.client.get(`v1/workspaces/${t}/availableSkills`,{headers:{Authorization:`Bearer ${e}`},searchParams:{createdBy:s?.createdBy,nextKey:s?.nextKey,limit:s?.limit??20}}).json()}async uploadSkill(e,t,s){return await this.client.post(`v1/workspaces/${t}/skills`,{headers:{Authorization:`Bearer ${e}`},body:s}).json()}async deleteSkill(e,t,s){await this.client.delete(`v1/workspaces/${t}/skills/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async downloadSkillCurrent(e,t,s){return await this.client.get(`v1/workspaces/${t}/skills/${s}/download`,{headers:{Authorization:`Bearer ${e}`}}).json()}async task(e,t,s){try{let n=await this.client.post(`v1/workspaces/${t}/tasks`,{headers:{Authorization:`Bearer ${e}`},json:s,timeout:6e4,throwHttpErrors:!1});if(!n.ok){let a=await n.text();throw new Error(`Task API failed (${n.status}): ${a}`)}let i=await n.json();return i.noop||!i.streamId?new Response(`data: [DONE]
3
-
4
- `,{headers:{"Content-Type":"text/event-stream"}}):await this.taskStream(e,t,i.taskId)}catch(n){throw n instanceof ke?new TypeError("Request timed out. Please check your connection and try again.",{cause:n}):n}}async taskStream(e,t,s){let n=await this.client.get(`v1/workspaces/${t}/tasks/${s}/stream`,{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"},timeout:!1,throwHttpErrors:!1});if(!n.ok){let i=await n.text();throw new Error(`Task stream failed (${n.status}): ${i}`)}return n}async getBudget(e,t){return await this.client.get(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`}}).json()}async updateBudget(e,t,s){await this.client.put(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`},json:{budget:s}})}async getMonthlyUsages(e,t,s){return await this.client.get(`v1/workspaces/${t}/monthlyUsages`,{headers:{Authorization:`Bearer ${e}`},searchParams:{nextKey:s?.nextKey,limit:s?.limit??20}}).json()}async createTaskShare(e,t,s,n="public"){return await this.client.post(`v1/workspaces/${t}/tasks/${s}/shares`,{headers:{Authorization:`Bearer ${e}`},json:{visibility:n}}).json()}async getSharedTask(e,t){let s={};return t&&(s.Authorization=`Bearer ${t}`),await this.client.get(`v1/shares/${e}`,{headers:s}).json()}async getSharedMessages(e,t=50,s){let n={};return s&&(n.Authorization=`Bearer ${s}`),await this.client.get(`v1/shares/${e}/messages`,{headers:n,searchParams:{limit:t}}).json()}async deleteTask(e,t,s){await this.client.delete(`v1/workspaces/${t}/tasks/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async getModelProviders(e,t){return await this.client.get(`v1/workspaces/${t}/modelProviders`,{headers:{Authorization:`Bearer ${e}`}}).json()}async uploadFile(e,t,s,n){let i=new FormData,a=new Blob([s.buffer],{type:s.mimeType});return i.append("file",a,s.filename),i.append("modelProviderId",n),await this.client.post(`v1/workspaces/${t}/files`,{headers:{Authorization:`Bearer ${e}`},body:i,timeout:12e4}).json()}async getSchedules(e,t,s){let n={limit:s?.limit??20};return s?.nextKey&&(n.nextKey=s.nextKey),s?.search&&(n.search=s.search),await this.client.get(`v1/workspaces/${t}/schedules`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async getSchedule(e,t,s){return await this.client.get(`v1/workspaces/${t}/schedules/${s}`,{headers:{Authorization:`Bearer ${e}`}}).json()}async createSchedule(e,t,s){return await this.client.post(`v1/workspaces/${t}/schedules`,{headers:{Authorization:`Bearer ${e}`},json:s}).json()}async updateSchedule(e,t,s,n){await this.client.put(`v1/workspaces/${t}/schedules/${s}`,{headers:{Authorization:`Bearer ${e}`},json:n})}async deleteSchedule(e,t,s){await this.client.delete(`v1/workspaces/${t}/schedules/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async activateSchedule(e,t,s){await this.client.post(`v1/workspaces/${t}/schedules/${s}/activate`,{headers:{Authorization:`Bearer ${e}`}})}async deactivateSchedule(e,t,s){await this.client.post(`v1/workspaces/${t}/schedules/${s}/deactivate`,{headers:{Authorization:`Bearer ${e}`}})}async runScheduleNow(e,t,s){return await this.client.post(`v1/workspaces/${t}/schedules/${s}/run`,{headers:{Authorization:`Bearer ${e}`}}).json()}async getScheduleRuns(e,t,s,n){let i={limit:n?.limit??20};return n?.nextKey&&(i.nextKey=n.nextKey),await this.client.get(`v1/workspaces/${t}/schedules/${s}/runs`,{headers:{Authorization:`Bearer ${e}`},searchParams:i}).json()}static async getAuthenticatedClient(e){let t=await p.getAll(e);return t?{client:new r(void 0,e),accessToken:t.accessToken,workspaceId:t.workspaceId??null}:null}};function Pe(){return process.env.ENTRYDESK_SANDBOX==="true"}function _(){if(!Pe())return null;let r=process.env.ENTRYDESK_SANDBOX_ACCESS_TOKEN?.trim(),e=process.env.ENTRYDESK_SANDBOX_WORKSPACE_ID?.trim();if(!r||!e){let t=[];throw r||t.push("ENTRYDESK_SANDBOX_ACCESS_TOKEN"),e||t.push("ENTRYDESK_SANDBOX_WORKSPACE_ID"),new Error(`Sandbox mode enabled but missing credentials: ${t.join(", ")}`)}return{accessToken:r,workspaceId:e}}function L(){let r=process.env.ENTRYDESK_TOKEN?.trim();if(!r)return null;let e=process.env.ENTRYDESK_WORKSPACE_ID?.trim();if(!e)throw new Error("ENTRYDESK_TOKEN is set but ENTRYDESK_WORKSPACE_ID is missing. Both are required for PAT authentication.");return{accessToken:r,workspaceId:e}}function rt(){let r=_();if(r)return{authSource:"sandbox-env",label:"sandbox environment (ENTRYDESK_SANDBOX)",workspaceId:r.workspaceId};let e=L();return e?{authSource:"pat-env",label:"personal access token (ENTRYDESK_TOKEN)",workspaceId:e.workspaceId}:null}import{execFile as Se}from"child_process";import{setTimeout as Ae}from"timers/promises";import{decodeJwt as Re}from"jose";import Te,{HTTPError as Ee,isHTTPError as Ce}from"ky";function te(r){if(r===null||typeof r!="object")return{error:""};let e=r;return{code:typeof e.code=="string"?e.code:void 0,error:typeof e.error=="string"?e.error:""}}var I="entrydesk-cli",be="offline_access workspaces:read tasks:read tasks:write tasks:delete agents:read agents:write connectors:read connectors:write tools:read tools:execute skills:read skills:write meetings:read meetings:write workflows:read workflows:write notifications:read notifications:write publishes:read publishes:write calendar:read calendar:write schedules:read schedules:write user:read user:write";function $e(r){return new Promise((e,t)=>{let s=process.platform,n,i;switch(s){case"darwin":n="open",i=[r];break;case"win32":n="cmd",i=["/c","start","",r];break;default:n="xdg-open",i=[r];break}Se(n,i,a=>{a?t(new Error(`Failed to open browser. Please manually visit: ${r}`,{cause:a})):e()})})}async function dt(r){let e=B(),t=re(),s=K(),n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;s.ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",console.error("WARNING: SSL certificate validation is disabled globally for this process during the login flow. All connections in this process will skip TLS verification. Only use ENTRYDESK_IGNORE_SSL_ERRORS for local development."));try{let i=Te.create({baseUrl:e.replace(/\/?$/,"/"),timeout:3e4,hooks:{beforeError:[({error:c})=>(Ce(c)&&(c.request.headers.delete("authorization"),c.request.headers.delete("Authorization")),c)]}}),a;try{a=await i.post("v1/oauth/device/code",{json:{client_id:I,scope:be}}).json()}catch(c){let w=c instanceof Error?c:new Error("Failed to request device code");throw r?.onError?.(w),w}let{device_code:S,user_code:d,expires_in:ae,interval:ce}=a,X=new URL("/oauth/device",t);X.searchParams.set("user_code",d);let V=X.toString();r?.onDeviceCodeReceived?.(d,V),r?.onBrowserOpening?.();try{await $e(V)}catch(c){process.env.DEBUG&&console.error("[DEBUG] Failed to open browser:",c)}r?.onWaitingForAuthorization?.();let Z=Math.max(ce,5)*1e3,le=Date.now()+ae*1e3;for(;Date.now()<le;){await Ae(Z);try{let c=await i.post("v1/oauth/token",{json:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:S,client_id:I}}).json();r?.onAuthorized?.();let w={};try{w=Re(c.access_token)}catch{}return{accessToken:c.access_token,refreshToken:c.refresh_token??void 0,email:w.email||"",scopes:c.scope.split(" ").filter(D=>D.length>0)}}catch(c){if(c instanceof Ee){let{code:D,error:ge}=te(c.data),F=D||ge;if(!F)continue;switch(F){case"authorization_pending":continue;case"slow_down":Z+=5e3;continue;case"access_denied":throw new Error("Authorization denied by user",{cause:c});case"expired_token":throw new Error("Device code expired. Please try again.",{cause:c});default:throw new Error(`Authorization failed: ${F||"Unknown error"}`,{cause:c})}}let w=c instanceof Error?c:new Error("Unknown error during authorization");throw r?.onError?.(w),w}}throw new Error("Device code expired. Please try again.")}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}function Be(r){if(r instanceof xe){let e=r.response.status;return e===400||e===401}return!1}var f=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Ke(r){try{let e=r.split(".");if(e.length<2)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4,n=t.padEnd(t.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i)}catch{return null}}function _e(r,e=300){let s=Ke(r)?.exp;if(typeof s!="number")return!1;let n=Math.floor(Date.now()/1e3);return s-n<=e}async function se(r){let e=r.accessToken;if(!_e(e))return e;if(!r.refreshToken)throw await p.clear(),new f("session-expired","Session expired. Please run `entrydesk login` again.");let t=r.refreshToken;try{let n=await new x().refreshOAuthToken({refreshToken:t,clientId:I}),i=await p.getAll();return i?.accessToken&&i.refreshToken&&i.refreshToken!==t?i.accessToken:(await p.saveAll({...i??r,accessToken:n.access_token,refreshToken:n.refresh_token??i?.refreshToken??t}),n.access_token)}catch(s){if(!Be(s))throw new f("refresh-failed","Could not refresh your session (auth server unreachable). Please try again.");let n=await p.getAll();if(n?.accessToken&&n.refreshToken&&n.refreshToken!==t)return n.accessToken;throw await p.clear(),new f("session-expired","Session expired. Please run `entrydesk login` again.")}}async function wt(){let r=_();if(r)return r.accessToken;let e=await p.getAll();if(!e?.accessToken)throw new f("not-logged-in","Not logged in. Run `entrydesk login` first.");return se(e)}async function kt(){let r=_();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=L();if(e)return e;let t=await p.getAll();if(!t?.accessToken)throw new f("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!t.workspaceId)throw new f("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await se(t),workspaceId:t.workspaceId}}var h=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}exitCode;cause};function At(r){let e=!!process.env.DEBUG;if(r instanceof h&&(console.error(`Error: ${r.message}`),r.cause&&(console.error(`Cause: ${r.cause.message}`),e&&r.cause.stack&&console.error(r.cause.stack)),process.exit(r.exitCode)),r instanceof f&&(console.error(r.message),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Ue&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Ie){let t=r.response.status;console.error(t===401?"Not authorized (401). Your session may have expired \u2014 run `entrydesk login`.":t===403?"Forbidden (403). Your account or token lacks permission for this action. If your token predates a recently added feature, run `entrydesk login` to refresh its scopes; otherwise you may lack permission in this workspace.":`Request failed (${t}): ${r.response.statusText}`),e&&r.stack&&console.error(r.stack),process.exit(1)}r instanceof Error&&(console.error(`Unexpected error: ${r.message}`),e&&r.stack&&console.error(r.stack),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}var P="default",De=/^[A-Za-z0-9_-]+$/,W=null;function H(){return E.join(Me.homedir(),".entrydesk")}function ie(){return E.join(H(),"profiles")}function oe(){return E.join(H(),"profiles.json")}function U(r){return E.join(ie(),r)}function Y(r){if(!y.existsSync(r))y.mkdirSync(r,{mode:448,recursive:!0});else try{y.chmodSync(r,448)}catch{}}function Fe(){Y(H())}function G(){Y(ie())}function je(){let r=oe();try{if(!y.existsSync(r))return null;let e=y.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function T(r){Fe();let e=oe();y.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{y.chmodSync(e,384)}catch{}}function ze(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||P;return e.length===0&&e.push(P),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function $(r){G(),Y(U(r))}function v(){let r=je();if(!r){let t={currentProfile:P,profiles:[P]};return T(t),G(),$(P),t}let e=ze(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&T(e),G(),e}function A(r){if(!r)throw new h("Profile name is required.");if(!De.test(r))throw new h("Invalid profile name. Use letters, numbers, dash, or underscore.")}function b(r,e){if(!r.profiles.includes(e))throw new h(`Profile not found: ${e}`)}function ne(r,e){if(r.profiles.includes(e))throw new h(`Profile already exists: ${e}`)}var o={DEFAULT_PROFILE:P,setOverrideProfile(r){W=r},getOverrideProfile(){return W},getProfileDir(r){return U(r)},getProfileConfigFile(r){return E.join(o.getProfileDir(r),"config.json")},getProfileCredentialsFile(r){return E.join(o.getProfileDir(r),"credentials.json")},getProfileNames(){return[...v().profiles]},getProfileCount(){return o.getProfileNames().length},getCurrentProfileName(){return v().currentProfile},getEffectiveProfileName(r){let e=v(),t=r||W||e.currentProfile;return A(t),b(e,t),t},ensureProfileExists(r){let e=v();A(r),b(e,r)},createProfile(r){A(r);let e=v();ne(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};T(t),$(r)},deleteProfile(r){A(r);let e=v();if(b(e,r),e.profiles.length===1)throw new h("Cannot delete the last profile.");let t=e.profiles.filter(i=>i!==r),s=e.currentProfile;s===r&&(s=t.includes(P)?P:t[0]),T({currentProfile:s,profiles:t});try{y.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){A(r),A(e);let t=v();b(t,r),ne(t,e);let s=U(r),n=U(e);if(y.existsSync(s))try{y.renameSync(s,n)}catch(d){throw new h("Failed to rename profile directory.",1,d)}else $(e);let i=t.profiles.map(d=>d===r?e:d),a=t.currentProfile===r?e:t.currentProfile;return T({currentProfile:a,profiles:i}),{currentProfile:a}},setCurrentProfile(r){A(r);let e=v();b(e,r);let t={currentProfile:r,profiles:e.profiles};T(t),$(r)},ensureProfileDir:$};function Ne(r){let e=o.getEffectiveProfileName(r);return o.getProfileConfigFile(e)}function g(r){let e=Ne(r);try{if(!M.existsSync(e))return{};let t=M.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function m(r,e){let t=o.getEffectiveProfileName(e);o.ensureProfileDir(t);let s=o.getProfileConfigFile(t);M.writeFileSync(s,JSON.stringify(r,null,2),{mode:384});try{M.chmodSync(s,384)}catch{}}var J={getApiUrl(r){return g(r).apiUrl??null},setApiUrl(r,e){let t=g(e);t.apiUrl=r,m(t,e)},clearApiUrl(r){let e=g(r);delete e.apiUrl,m(e,r)},getHubUrl(r){return g(r).hubUrl??null},setHubUrl(r,e){let t=g(e);t.hubUrl=r,m(t,e)},getAll(r){return g(r)},setAll(r,e){m(r,e)},set(r,e,t){let s=g(t);s[r]=e,m(s,t)},get(r,e){return g(e)[r]},unset(r,e){let t=g(e);delete t[r],m(t,e)},getDefaultModel(r){return g(r).model?.default??null},setDefaultModel(r,e){let t=g(e);t.model={...t.model,default:r},m(t,e)},getDefaultConnectorIds(r){return g(r).connectors?.defaults??null},setDefaultConnectorIds(r,e){let t=g(e);t.connectors={...t.connectors,defaults:r},m(t,e)},getLocalTools(r){return g(r).localTools??null},setLocalTools(r,e){let t=g(e);t.localTools={...t.localTools,...r},m(t,e)}};var Oe="https://api.entrydesk.com",Le="https://app.entrydesk.com",We=3100,Ge=300*1e3;function q(r){return{apiUrl:J.getApiUrl(r)||process.env.ENTRYDESK_API_URL||Oe,hubUrl:J.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Le,mcp:{httpPort:We},auth:{loginTimeout:Ge,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function B(r){return q(r).apiUrl}function re(r){return q(r).hubUrl}function K(){return q().auth}export{o as a,J as b,q as c,B as d,re as e,K as f,p as g,x as h,rt as i,te as j,I as k,dt as l,f as m,_e as n,se as o,wt as p,kt as q,h as r,At as s};
@@ -1,208 +0,0 @@
1
- #!/usr/bin/env node
2
- import"./chunk-KURQCTT3.js";function e(){console.log(`
3
- EntryDesk CLI - Interact with EntryDesk from your terminal
4
-
5
- Usage: entrydesk <command> [options]
6
-
7
- Commands:
8
- login Authenticate with EntryDesk
9
- logout Sign out and clear credentials
10
- status Show current authentication status
11
- workspaces List or switch workspaces
12
- models List available models
13
- agents List available agents
14
- meeting List, view, or manage meetings and recordings
15
- workflow List, create, run, or manage workflows
16
- notifications List, count, or mark notifications read
17
- skills List or upload skills
18
- schedules List or manage scheduled tasks
19
- connectors List connected connectors
20
- tool List, get, or call MCP tools
21
- profile Manage profiles
22
- tasks List recent tasks or view messages
23
- task Send a message or start interactive task
24
- budget View or manage workspace budget
25
- usage View current month usage statistics
26
- mcp-server Start MCP server (stdio or HTTP)
27
- config Manage CLI configuration
28
- help Show this help message
29
- version Show version number
30
-
31
- Global Options:
32
- --json Output in JSON format (for scripting)
33
- -i Interactive mode (for task)
34
- --profile Use a specific profile for this command
35
-
36
- Login:
37
- entrydesk login # Open browser login (OAuth Device Flow)
38
-
39
- Task:
40
- entrydesk task -m "Hello" --model <model> # Send with model
41
- entrydesk task -m "Hello" -a <agent> # Send with agent
42
- entrydesk task -c 1 -m "Follow up" # Continue recent task
43
- entrydesk task -i # Interactive mode
44
- echo "Hello" | entrydesk task --model <m> # Pipe input from stdin
45
- entrydesk task -m "Hi" --model <m> --plain # Plain text output
46
- entrydesk task -m "Hi" --model <m> --output stream-json # Stream JSON
47
- entrydesk task -i --no-file-system # Disable local file operations
48
- entrydesk task -i --connectors id1,id2 # Use specific connectors
49
-
50
- MCP Server:
51
- entrydesk mcp-server # Start stdio server
52
- entrydesk mcp-server --http --port 3100 # Start HTTP server
53
-
54
- Tool Operations:
55
- entrydesk tool list # List all available tools
56
- entrydesk tool list --prefix sandbox # Filter by prefix
57
- entrydesk tool get <name> # Get tool details
58
- entrydesk tool call <name> --input {} # Execute a tool
59
-
60
- Workspaces:
61
- entrydesk workspaces # List all workspaces
62
- entrydesk workspaces switch <id> # Switch to a workspace
63
- entrydesk workspaces use <id> # Alias for switch
64
-
65
- Budget:
66
- entrydesk budget # Show current budget
67
- entrydesk budget get # Show current budget
68
- entrydesk budget set 100.00 # Set budget to $100.00
69
- entrydesk budget clear # Remove budget
70
-
71
- Usage:
72
- entrydesk usage # Show current month usage (top users by cost)
73
- entrydesk usage --limit 20 # Show top 20 users
74
- entrydesk usage --sort-by operations # Sort by operations instead of cost
75
- entrydesk usage --limit 10 --sort-by cost # Top 10 by cost
76
- entrydesk usage --json # Get usage as JSON
77
-
78
- Tasks:
79
- entrydesk tasks # List recent tasks
80
- entrydesk tasks --search "bug fix" # Search tasks (title + content)
81
- entrydesk tasks -q "\u5831\u8868" --limit 10 # Search, short flag + page size
82
- entrydesk tasks 1 # View task #1 messages
83
- entrydesk tasks <uuid> # View task by ID
84
- entrydesk tasks --share <shareId> # View shared task by share ID
85
- entrydesk tasks -s <shareId> # Short form for --share
86
- entrydesk tasks --share <id> --json # Get shared task as JSON
87
-
88
- Examples:
89
- $ entrydesk login
90
- $ entrydesk status
91
- $ entrydesk workspaces # List workspaces
92
- $ entrydesk workspaces switch <workspaceId> # Switch workspace
93
- $ entrydesk budget # View budget
94
- $ entrydesk budget set 100.00 # Set budget
95
- $ entrydesk budget clear # Clear budget
96
- $ entrydesk usage # View usage (all users, sorted by cost)
97
- $ entrydesk usage --limit 10 # Show top 10 users
98
- $ entrydesk usage --sort-by operations # Sort by operation count
99
- $ entrydesk models --json
100
- $ entrydesk agents --json
101
- $ entrydesk agents create --name "My Agent" --description "..." --system-prompt "..." --model-id <modelId>
102
- $ entrydesk agents update <agentId> --name "New Name" --description "..." --system-prompt "..." --model-id <modelId>
103
- $ entrydesk agents delete <agentId>
104
- $ entrydesk skills
105
- $ entrydesk skills upload ./my-skill.zip
106
- $ entrydesk skills upload ./my-skill-folder
107
- $ entrydesk task -m "Hello" --model gemini-2.5-flash-lite
108
- $ entrydesk tasks # List recent tasks
109
- $ entrydesk tasks 1 # View task #1 messages
110
- $ entrydesk task -c 1 -m "Tell me more" # Continue task #1
111
- $ entrydesk tasks 0 --output stream-json # Stream recent task as JSON
112
- $ entrydesk tasks --share <shareId> # View shared task
113
-
114
- Piping:
115
- $ echo "Explain this code" | entrydesk task --model gemini-2.5-flash-lite
116
- $ cat file.txt | entrydesk task -c 1 # Pipe file content
117
- $ entrydesk task -m "Hi" --model <m> > out.txt # Save to file
118
-
119
- Usage Examples:
120
- $ entrydesk usage # Show all users, sorted by cost
121
- $ entrydesk usage --limit 10 # Show top 10 users
122
- $ entrydesk usage --sort-by operations # Sort by operation count
123
-
124
- Configuration:
125
- entrydesk config # Show current config
126
- entrydesk config set <key> <value> # Set a config value
127
- entrydesk config unset <key> # Remove a config value
128
-
129
- Profiles:
130
- entrydesk profile # List profiles
131
- entrydesk profile create <name> # Create a profile
132
- entrydesk profile use <name> # Switch active profile
133
- entrydesk profile delete <name> # Delete a profile
134
- entrydesk profile rename <from> <to> # Rename a profile
135
- entrydesk profile clone <from> <to> # Clone config defaults (no credentials)
136
-
137
- Skills:
138
- entrydesk skills # List skills
139
- entrydesk skills list --me # List my skills
140
- entrydesk skills upload <file.zip> # Upload a skill zip
141
- entrydesk skills upload <folder> # Upload a skill folder
142
- entrydesk skills upload <file.zip> --force
143
- entrydesk skills delete <skillId>
144
-
145
- Agents:
146
- entrydesk agents # List agents
147
- entrydesk agents create --name "My Agent" --description "..." --system-prompt "..." --model-id <modelId>
148
- entrydesk agents update <agentId> --name "New Name" --description "..." --system-prompt "..." --model-id <modelId>
149
- entrydesk agents delete <agentId>
150
-
151
- Meetings:
152
- entrydesk meeting # List meetings
153
- entrydesk meeting list --filter mine # Only my meetings
154
- entrydesk meeting list --search "sprint" # Search meetings
155
- entrydesk meeting get <meetingId> # Meeting details + recordings
156
- entrydesk meeting create --title "Sprint Planning" --start 2026-06-20T09:00:00Z
157
- entrydesk meeting update <meetingId> --status completed
158
- entrydesk meeting delete <meetingId>
159
- entrydesk meeting summary <meetingId> # Print summary to stdout
160
- entrydesk meeting transcript <recordingId> # Print transcript (--raw for timestamps)
161
- entrydesk meeting previous <meetingId> # Previous meeting brief
162
- entrydesk meeting share <meetingId> # Show sharing (visibility + grants)
163
- entrydesk meeting share <meetingId> --visibility workspace
164
- entrydesk meeting share <meetingId> --add-user <userId> --role editor
165
- entrydesk meeting transcript <recordingId> | entrydesk task -m "List action items"
166
-
167
- Workflows:
168
- entrydesk workflow # List workflows
169
- entrydesk workflow list --search report
170
- entrydesk workflow get <workflowId> # Details (--show-source for script)
171
- entrydesk workflow create --name "Nightly" --file ./flow.js
172
- entrydesk workflow update <workflowId> --deactivate
173
- entrydesk workflow run <workflowId> --args '{"date":"2026-06-20"}' --wait
174
- entrydesk workflow runs <workflowId> # List runs
175
- entrydesk workflow run-get <workflowId> <runId>
176
- entrydesk workflow share <workflowId> --add-user <userId> --role editor
177
-
178
- Notifications:
179
- entrydesk notifications # List notifications
180
- entrydesk notifications --tab action # Only actionable ones
181
- entrydesk notifications unread # Unread count
182
- entrydesk notifications read <id> # Mark one read
183
- entrydesk notifications read-all # Mark all read
184
-
185
- Schedules:
186
- entrydesk schedules # List schedules
187
- entrydesk schedules get <id> # Show schedule details
188
- entrydesk schedules edit <id> --prompt "New prompt" # Update fields
189
- entrydesk schedules pause <id> # Pause / activate <id> to resume
190
- entrydesk schedules run <id> # Run now (prints taskId)
191
- entrydesk schedules runs <id> # Run history
192
- entrydesk schedules create \\
193
- --name "Daily Report" \\
194
- --agent-id <agentId> \\
195
- --prompt "Generate report" \\
196
- --starts-at "2025-01-01T09:00:00Z" \\
197
- --repeat-type days --every 1 --time 09:00 \\
198
- --utc-offset "+08:00"
199
- entrydesk schedules delete <id> # Delete a schedule
200
-
201
- Available keys: apiUrl, hubUrl
202
-
203
- Local Development:
204
- $ entrydesk config set apiUrl http://localhost:3200
205
- $ entrydesk config set hubUrl http://localhost:3000
206
-
207
- For more information, visit https://entrydesk.com/docs/cli
208
- `)}export{e as printHelp};
@@ -1,17 +0,0 @@
1
- #!/usr/bin/env node
2
- import{h as S,j as z,q as I,s as P}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";import A from"crypto";import g from"fs";import i from"fs/promises";import b from"os";import o from"path";import{Readable as j}from"stream";import{pipeline as E}from"stream/promises";import N from"adm-zip";import O from"archiver";import{isHTTPError as T}from"ky";function x(){console.log(`
3
- Usage: entrydesk skills [list|upload|delete|download] [options]
4
-
5
- Commands:
6
- list List available skills (default)
7
- upload <file.zip> Upload a skill zip file
8
- upload <folder> Upload a skill folder (auto-zipped)
9
- delete <skillId> Delete a skill you own
10
- download <skillId> Download and extract a skill to ./<skill-name>/
11
-
12
- Options:
13
- --me Only list skills created by me
14
- --force Overwrite an existing skill with the same name
15
- --json Output JSON (for list/upload)
16
- `)}function W(r,d){let n=o.relative(r,d);return n===""||!n.startsWith("..")&&!o.isAbsolute(n)}async function C(r){let d=await i.realpath(r),n=[process.cwd(),b.homedir()];if(!(await Promise.all(n.map(async a=>{try{return await i.realpath(a)}catch{return o.resolve(a)}}))).some(a=>W(a,d)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function F(r){let d=await i.mkdtemp(o.join(b.tmpdir(),"entrydesk-skill-")),n=o.join(d,`${o.basename(r)}.zip`);return await new Promise((f,m)=>{let a=g.createWriteStream(n),u=O("zip",{zlib:{level:9}});a.on("close",()=>f()),a.on("error",m),u.on("error",m),u.pipe(a),u.directory(r,!1),u.finalize()}),{zipPath:n,cleanupDir:d}}async function X(r){let d,n;try{let e=await I();d=e.accessToken,n=e.workspaceId}catch(e){P(e)}let f=r.action||"list",m=new S;if(f==="upload"){let e=r.configKey;e||(console.error("Missing file path."),x(),process.exit(1));let w=o.resolve(e),c;try{c=await i.stat(w)}catch{console.error(`File not found: ${w}`),process.exit(1)}let s=w,y=null;try{try{await C(w)}catch(l){let t=l instanceof Error?l.message:"Invalid upload path.";console.error(t),process.exit(1)}if(c.isDirectory()){let l=await F(w);s=l.zipPath,y=l.cleanupDir}else c.isFile()||(console.error(`Not a file or directory: ${w}`),process.exit(1));o.extname(s).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let v=await i.readFile(s),p=new FormData;p.append("file",new Blob([v],{type:"application/zip"}),o.basename(s)),r.force&&p.append("force","true");let k;try{k=await m.uploadSkill(d,n,p)}catch(l){if(T(l)&&l.response.status===409){let{code:t}=z(l.data);t==="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.")),process.exit(1)}throw l}if(r.json){console.log(JSON.stringify(k));return}console.log(`Uploaded skill: ${k.name}`),console.log(` ID: ${k.id}`),console.log(` Version ID: ${k.versionId}`),console.log(` Description: ${k.description}`);return}finally{y&&await i.rm(y,{recursive:!0,force:!0})}}if(f==="delete"){let e=r.configKey;e||(console.error("Missing skill ID."),x(),process.exit(1)),await m.deleteSkill(d,n,e),console.log(`Deleted skill: ${e}`);return}if(f==="download"){let e=r.configKey;e||(console.error("Missing skill ID."),x(),process.exit(1));let{url:w,name:c}=await m.downloadSkillCurrent(d,n,e);(c.includes("/")||c.includes(o.sep)||c==="."||c===".."||!c)&&(console.error(`Invalid skill name for output directory: ${c}`),process.exit(1));let s=o.resolve(c),y=await i.mkdtemp(o.join(b.tmpdir(),"entrydesk-skill-download-")),v=o.join(y,`${c}.zip`);try{let p=await fetch(w);if(!p.ok)throw new Error(`Failed to download skill zip: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("Response body is empty");let k=g.createWriteStream(v);await E(j.fromWeb(p.body),k);let l=await i.mkdtemp(o.join(o.dirname(s),".entrydesk-skill-extract-")),t=null;try{r.json||console.log("Extracting...");let D=new N(v),U=o.resolve(l)+o.sep;for(let h of D.getEntries()){if(h.isDirectory)continue;let $=o.resolve(l,h.entryName);if(!$.startsWith(U))throw new Error(`Zip entry contains path traversal: ${h.entryName}`);await i.mkdir(o.dirname($),{recursive:!0}),await i.writeFile($,h.getData())}g.existsSync(s)&&(t=o.join(o.dirname(s),`.entrydesk-backup-${A.randomUUID()}`),r.json||console.log(`Replacing existing directory: ${s}`),await i.rename(s,t));try{await i.rename(l,s),t&&g.existsSync(t)&&(await i.rm(t,{recursive:!0,force:!0}),t=null)}catch(h){throw t&&g.existsSync(t)&&(await i.rename(t,s),t=null),h}}catch(D){if(await i.rm(l,{recursive:!0,force:!0}),t&&g.existsSync(t))try{await i.rename(t,s)}catch{console.error(`Warning: Could not restore backup. Your original files are at: ${t}`)}throw D}if(r.json){console.log(JSON.stringify({skillId:e,skillName:c,outputDir:s}));return}console.log(`Downloaded skill "${c}" to ${s}`)}finally{await i.rm(y,{recursive:!0,force:!0})}return}f!=="list"&&(console.error(`Unknown skills command: ${f}`),x(),process.exit(1));let a=[],u;do{let e=await m.listAvailableSkills(d,n,{createdBy:r.createdBy,nextKey:u,limit:100});a.push(...e.skills),u=e.nextKey}while(u);if(r.json){console.log(JSON.stringify(a));return}if(a.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${a.length}):
17
- `);for(let e of a)console.log(` ${e.name} (${e.provider})`),console.log(` ${e.description.slice(0,120)}`),console.log(` ID: ${e.id}`),console.log(` Author: ${e.author.name}`),console.log("")}export{X as runSkills};
@@ -1,21 +0,0 @@
1
- #!/usr/bin/env node
2
- import{h as A,p as I,q as b,s as O}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";var h="\x1B[2m",a="\x1B[0m",p="\x1B[36m",w="\x1B[33m",R="\x1B[32m",v="stream-json";function f(t,n){let r=n===void 0?{event:t}:{event:t,data:n};process.stdout.write(`${JSON.stringify(r)}
3
- `)}function S(t){let n=new Date(t),e=new Date().getTime()-n.getTime(),o=Math.floor(e/(1e3*60*60*24));return o===0?n.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):o===1?"Yesterday":o<7?`${o} days ago`:n.toLocaleDateString("en-US",{month:"short",day:"numeric"})}var D="\x1B[1m";function j(t){return t.replace(/<mark>/g,D).replace(/<\/mark>/g,a).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&")}function T(t,n){if(n)return t;let r=t.split(`
4
- `);if(r.length<=15)return t;let e=r.slice(0,6),o=r.slice(-4),i=r.length-10;return[...e,`... (${i} lines omitted, use --full-output to see all) ...`,...o].join(`
5
- `)}function N(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(N);let n={};for(let[r,e]of Object.entries(t))typeof e=="string"&&e.length>200?n[r]=e.slice(0,150)+"... (truncated)":typeof e=="object"&&e!==null?n[r]=N(e):n[r]=e;return n}function E(t){if(!t||typeof t!="object")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}}function J(t,n){if(!t)return"(no result)";if(typeof t!="object")return T(String(t),n);let r=n?t:N(t);if("structuredContent"in r&&r.structuredContent){let e=r.structuredContent,o=[];if(e.stdout&&typeof e.stdout=="string"&&e.stdout.trim()&&o.push(e.stdout.trim()),e.stderr&&typeof e.stderr=="string"&&e.stderr.trim()&&o.push(`${w}[stderr]${a} ${e.stderr.trim()}`),e.urls&&Array.isArray(e.urls)){let i=e.urls;for(let s of i)s.path&&s.url&&o.push(`${s.path}: ${s.url}`)}return o.length===0&&o.push(JSON.stringify(e,null,2)),T(o.join(`
6
- `),n)}if("content"in r&&Array.isArray(r.content)){let o=r.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
7
- `);return T(o||JSON.stringify(t,null,2),n)}return T(JSON.stringify(t,null,2),n)}function M(t){if(typeof t.title=="string")return t.title;if(typeof t.toolName=="string")return t.toolName;let n=t.type;return n.startsWith("tool-")?n.slice(5).replace(/__/g," ").replace(/_/g," "):n}function L(t,n){let r=[];for(let e of t)if(e.type==="reasoning"&&e.text)r.push(`${h}${e.text}${a}`);else if(e.type==="text"&&e.text)r.push(e.text);else if(e.type==="tool-call"&&e.toolName){let o=[];if(o.push(`${p}\u250C\u2500 Tool Call: ${e.toolName}${a}`),e.args){o.push(`${w}\u2502 Arguments:${a}`);let i=E(e.args);for(let s of i.split(`
8
- `))o.push(`${h}\u2502 ${s}${a}`)}if(e.result!==void 0){o.push(`${R}\u2502 Result:${a}`);let i=J(e.result,n);for(let s of i.split(`
9
- `))o.push(`${h}\u2502 ${s}${a}`);o.push(`${p}\u2514\u2500 ${e.toolName} completed${a}`)}else e.state==="call"?o.push(`${p}\u2514\u2500 (awaiting result)${a}`):o.push(`${p}\u2514\u2500${a}`);r.push(o.join(`
10
- `))}else if(e.type.startsWith("tool-")&&e.type!=="tool-call"){let o=M(e),i=[];if(i.push(`${p}\u250C\u2500 Tool: ${o}${a}`),e.input){i.push(`${w}\u2502 Input:${a}`);let s=E(e.input);for(let c of s.split(`
11
- `))i.push(`${h}\u2502 ${c}${a}`)}if(e.output!==void 0&&e.state==="output-available"){i.push(`${R}\u2502 Output:${a}`);let s=J(e.output,n);for(let c of s.split(`
12
- `))i.push(`${h}\u2502 ${c}${a}`);i.push(`${p}\u2514\u2500 completed${a}`)}else e.state==="call"||e.state==="partial-call"?i.push(`${p}\u2514\u2500 (in progress)${a}`):i.push(`${p}\u2514\u2500${a}`);r.push(i.join(`
13
- `))}return r.join(`
14
-
15
- `).trim()}async function Y(t){let n=t.output===v;t.output&&!n&&(console.error(`Invalid --output value. Supported: ${v}`),process.exit(1));let r=new A;if(t.shareId){let s;try{s=await I()}catch{}try{let c=await r.getSharedTask(t.shareId,s),{messages:l}=await r.getSharedMessages(t.shareId,50,s);if(t.json){console.log(JSON.stringify({task:c,messages:l}));return}if(n){if(f("task",c),l.length===0)f("info","No messages in this shared task.");else for(let u of l.toReversed())f("message",u);f("done");return}if(console.log(`Shared Task: ${c.title||"Untitled"}`),console.log(`Visibility: ${c.visibility}`),c.agent&&console.log(`Agent: ${c.agent.name}`),console.log(`${l.length} messages
16
- `),l.length===0){console.log("No messages in this shared task.");return}let d=l.toReversed(),k=t.fullOutput??!1;for(let u of d){let y=L(u.parts,k);if(!y)continue;let x=u.role==="user"?"You":"Assistant";console.log(`[${x}] ${S(u.createdAt)}`),console.log(y),console.log("")}return}catch(c){if(c instanceof Error){let l=c.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared task requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared task not found. The share ID may be invalid or the task was deleted."):console.error(`Failed to fetch shared task: ${c.message}`)}else console.error("Failed to fetch shared task");process.exit(1)}}let e,o;try{let s=await b();e=s.accessToken,o=s.workspaceId}catch(s){O(s)}if(t.taskId){let s=t.taskId,c=!1,l=null,d=parseInt(t.taskId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(t.taskId)){let g=d===0?1:d,{tasks:$}=await r.getTasks(e,o,20);g>$.length&&(console.error(`Task number ${g} not found. You have ${$.length} recent tasks.`),process.exit(1));let m=$[g-1];s=m.id,c=!0,l=m,n||console.log(`Task: ${m.title||"Untitled"}
17
- `)}let{messages:u}=await r.getMessages(e,o,s,50);if(t.json){console.log(JSON.stringify(u));return}if(n){if(l&&f("task",l),u.length===0)f("info","No messages in this task.");else for(let g of u.toReversed())f("message",g);f("done");return}if(u.length===0){console.log("No messages in this task.");return}let y=u.toReversed(),x=t.fullOutput??!1;c||console.log(`Task: ${t.taskId.slice(0,8)}...`),console.log(`${u.length} messages
18
- `);for(let g of y){let $=L(g.parts,x);if(!$)continue;let m=g.role==="user"?"You":"Assistant";console.log(`[${m}] ${S(g.createdAt)}`),console.log($),console.log("")}return}if(t.search){let{results:s,nextKey:c}=await r.searchTasks(e,o,t.search,{limit:t.limit,nextKey:t.nextKey});if(n){for(let l of s)f("task",l);f("done");return}if(t.json){console.log(JSON.stringify({results:s,nextKey:c}));return}if(s.length===0){console.log(`No tasks match "${t.search}".`);return}console.log(`Search results for "${t.search}" (${s.length}):
19
- `),s.forEach((l,d)=>{let k=(d+1).toString().padStart(2," "),u=l.titleHighlight?j(l.titleHighlight):l.title||"Untitled";console.log(` ${k}. ${h}${S(l.createdAt)}${a} ${u}`),l.contentSnippet&&console.log(` ${j(l.contentSnippet)}`),console.log(` ${h}ID: ${l.id}${a}`)}),c&&console.log(`
20
- Next page: --next-key ${c}`);return}let{tasks:i}=await r.getTasks(e,o,20);if(n){for(let s of i)f("task",s);f("done");return}if(t.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No tasks found.");return}console.log(`Recent Tasks (${i.length}):
21
- `),i.forEach((s,c)=>{let l=(c+1).toString().padStart(2," ");console.log(` ${l}. ${S(s.createdAt).padEnd(12)} ${s.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk tasks 1` to view the most recent task"),console.log('Use `entrydesk task -c 1 -m "message"` to continue it')}export{j as renderHighlight,Y as runTasks};
@@ -1,18 +0,0 @@
1
- #!/usr/bin/env node
2
- import{h as d,q as f}from"./chunk-TFQLXDTE.js";import"./chunk-KURQCTT3.js";function U(){console.log(`
3
- Usage: entrydesk usage [options]
4
-
5
- Options:
6
- --limit <number> Limit number of users shown (default: all)
7
- --sort-by cost|operations Sort by cost or operations (default: cost)
8
- --json Output JSON
9
-
10
- Examples:
11
- entrydesk usage # Show all users, sorted by cost
12
- entrydesk usage --limit 10 # Show top 10 users
13
- entrydesk usage --sort-by operations # Sort by operation count
14
- entrydesk usage --json # JSON output
15
- `)}async function k(e){if(e.help){U();return}let l,a;try{let o=await f();l=o.accessToken,a=o.workspaceId}catch(o){let s=o instanceof Error?o.message:"Authentication failed";console.error(s),process.exit(1)}let h=new d,t=[],r,i=0,m=100;do{let o=await h.getMonthlyUsages(l,a,{nextKey:r,limit:100});if(t.push(...o.monthlyUsages),r=o.nextKey,i++,i>=m){console.error(`Warning: Showing first ${t.length} entries (pagination limit reached)`);break}}while(r);if(e.json){console.log(JSON.stringify(t));return}if(t.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
16
- `);let c=0,g=0;for(let o of t)c+=parseFloat(o.totalCost),g+=o.operationCount;console.log(`Total Cost: $${c.toFixed(2)}`),console.log(`Total Operations: ${g.toLocaleString()}`),console.log(`Users: ${t.length}
17
- `);let u=e.sortBy||"cost",p=[...t].toSorted((o,s)=>u==="cost"?parseFloat(s.totalCost)-parseFloat(o.totalCost):s.operationCount-o.operationCount),y=e.limit&&e.limit>0?e.limit:p.length,n=p.slice(0,y);console.log(`Usage by User (sorted by ${u}, showing ${n.length} of ${t.length}):
18
- `);for(let o of n){let s=parseFloat(o.totalCost);console.log(` ${o.user.name} (${o.user.email})`),console.log(` Cost: $${s.toFixed(2)}`),console.log(` Operations: ${o.operationCount.toLocaleString()}`),console.log("")}n.length<t.length&&console.log(`... and ${t.length-n.length} more users`)}export{k as runUsage};