@entrydesk/cli 1.7.4 → 1.7.6
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.
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import R from"crypto";import f from"fs";import pe from"path";import u from"fs";import ce from"os";import S from"path";import{HTTPError as ae,TimeoutError as le}from"ky";import re,{TimeoutError as se}from"ky";import E from"fs";function X(r){let e=o.getEffectiveProfileName(r);return o.getProfileConfigFile(e)}function a(r){let e=X(r);try{if(!E.existsSync(e))return{};let t=E.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function d(r,e){let t=o.getEffectiveProfileName(e);o.ensureProfileDir(t);let s=o.getProfileConfigFile(t);E.writeFileSync(s,JSON.stringify(r,null,2),{mode:384});try{E.chmodSync(s,384)}catch{}}var I={getApiUrl(r){return a(r).apiUrl??null},setApiUrl(r,e){let t=a(e);t.apiUrl=r,d(t,e)},clearApiUrl(r){let e=a(r);delete e.apiUrl,d(e,r)},getHubUrl(r){return a(r).hubUrl??null},setHubUrl(r,e){let t=a(e);t.hubUrl=r,d(t,e)},getAll(r){return a(r)},setAll(r,e){d(r,e)},set(r,e,t){let s=a(t);s[r]=e,d(s,t)},get(r,e){return a(e)[r]},unset(r,e){let t=a(e);delete t[r],d(t,e)},getDefaultModel(r){return a(r).model?.default??null},setDefaultModel(r,e){let t=a(e);t.model={...t.model,default:r},d(t,e)},getDefaultConnectorIds(r){return a(r).connectors?.defaults??null},setDefaultConnectorIds(r,e){let t=a(e);t.connectors={...t.connectors,defaults:r},d(t,e)},getCapabilities(r){return a(r).capabilities??null},setCapabilities(r,e){let t=a(e);t.capabilities={...t.capabilities,...r},d(t,e)},getLocalTools(r){return a(r).localTools??null},setLocalTools(r,e){let t=a(e);t.localTools={...t.localTools,...r},d(t,e)}};var Z="https://entrydesk-api.dcard.io",Q="https://entrydesk.dcard.io",ee=3100,te=300*1e3;function T(r){return{apiUrl:I.getApiUrl(r)||process.env.ENTRYDESK_API_URL||Z,hubUrl:I.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Q,mcp:{httpPort:ee},auth:{loginTimeout:te,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function O(r){return T(r).apiUrl}function Ae(r){return T(r).hubUrl}function be(){return T().mcp}function z(){return T().auth}var W="ENTRYDESK_ALLOW_INSECURE_LOGIN",$=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||O(t),z().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=re.create({prefixUrl:this.baseUrl,timeout:3e4,retry:{limit:3,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504]},hooks:{beforeError:[n=>(n.request?.headers&&(n.request.headers.delete("authorization"),n.request.headers.delete("Authorization")),n)]}})}getBaseUrl(){return this.baseUrl}shouldAllowInsecureLogin(){return process.env[W]?.toLowerCase()==="true"}assertSecureLogin(){let e;try{e=new URL(this.baseUrl)}catch(t){let s=t instanceof Error?t:void 0;throw new c("Invalid API URL; cannot perform login.",1,s)}if(e.protocol!=="https:"&&!this.shouldAllowInsecureLogin())throw new c(`Login requires HTTPS. Set apiUrl to https:// or set ${W}=true for local development.`)}async login(e,t){return this.assertSecureLogin(),await this.client.post("v1/auth/credentials/token",{json:{email:e,password:t}}).json()}async refreshToken(e){return await this.client.post("v1/auth/token/refresh",{json:{refreshToken:e}}).json()}async revokeToken(e){await this.client.post("v1/auth/token/revoke",{json:{refreshToken:e}})}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){return await this.client.get(`v1/workspaces/${t}/availableAgents`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:100}}).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 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 getChats(e,t,s=20){return await this.client.get(`v1/workspaces/${t}/chats`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:s}}).json()}async getMessages(e,t,s,n=50){return await this.client.get(`v1/workspaces/${t}/chats/${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 listSkillVersions(e,t,s){return await this.client.get(`v1/workspaces/${t}/skills/${s}/versions`,{headers:{Authorization:`Bearer ${e}`}}).json()}async chat(e,t,s){try{let n=await this.client.post(`v1/workspaces/${t}/chats`,{headers:{Authorization:`Bearer ${e}`},json:s,timeout:6e4,throwHttpErrors:!1});if(!n.ok){let i=await n.text();throw new Error(`Chat API failed (${n.status}): ${i}`)}return n}catch(n){throw n instanceof se?new Error("Request timed out. Please check your connection and try again.",{cause:n}):n}}async getBudget(e,t){return await this.client.get(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`}}).json()}async updateBudget(e,t,s){return await this.client.put(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`},json:{budget:s}}).json()}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 createChatShare(e,t,s,n="public"){return await this.client.post(`v1/workspaces/${t}/chats/${s}/shares`,{headers:{Authorization:`Bearer ${e}`},json:{visibility:n}}).json()}async getSharedChat(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 deleteChat(e,t,s){await this.client.delete(`v1/workspaces/${t}/chats/${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,g=new Blob([s.buffer],{type:s.mimeType});return i.append("file",g,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}`}})}static async getAuthenticatedClient(e){let t=await h.getAll(e);return t?{client:new r(void 0,e),accessToken:t.accessToken,workspaceId:t.workspaceId??null}:null}};function ne(){return process.env.ENTRYDESK_SANDBOX==="true"}function U(){if(!ne())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}}var p=class extends Error{code;constructor(e,t){super(t),this.code=e}};function ie(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 oe(r,e=300){let t=ie(r);if(!t?.exp)return!1;let s=Math.floor(Date.now()/1e3);return t.exp-s<=e}async function G(r){let e=r.accessToken;if(!oe(e))return e;if(!r.refreshToken)throw await h.clear(),new p("session-expired","Session expired. Please run `entrydesk login` again.");try{let t=new $,{token:s}=await t.refreshToken(r.refreshToken);return await h.saveAccessToken(s),s}catch{throw await h.clear(),new p("session-expired","Session expired. Please run `entrydesk login` again.")}}async function De(){let r=U();if(r)return r.accessToken;let e=await h.getAll();if(!e?.accessToken)throw new p("not-logged-in","Not logged in. Run `entrydesk login` first.");return G(e)}async function _e(){let r=U();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=await h.getAll();if(!e?.accessToken)throw new p("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!e.workspaceId)throw new p("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await G(e),workspaceId:e.workspaceId}}var c=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}};function je(r){let e=!!process.env.DEBUG;r instanceof c&&(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 p&&(console.error(r.message),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof le&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof ae&&(console.error(`Request failed (${r.response.status}): ${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 m="default",ge=/^[A-Za-z0-9_-]+$/,F=null;function D(){return S.join(ce.homedir(),".entrydesk")}function Y(){return S.join(D(),"profiles")}function H(){return S.join(D(),"profiles.json")}function K(r){return S.join(Y(),r)}function _(r){if(!u.existsSync(r))u.mkdirSync(r,{mode:448,recursive:!0});else try{u.chmodSync(r,448)}catch{}}function de(){_(D())}function B(){_(Y())}function ue(){let r=H();try{if(!u.existsSync(r))return null;let e=u.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function P(r){de();let e=H();u.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{u.chmodSync(e,384)}catch{}}function fe(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||m;return e.length===0&&e.push(m),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function y(){let r=ue();if(!r){let t={currentProfile:m,profiles:[m]};return P(t),B(),x(m),t}let e=fe(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&P(e),B(),e}function v(r){if(!r)throw new c("Profile name is required.");if(!ge.test(r))throw new c("Invalid profile name. Use letters, numbers, dash, or underscore.")}function b(r,e){if(!r.profiles.includes(e))throw new c(`Profile not found: ${e}`)}function V(r,e){if(r.profiles.includes(e))throw new c(`Profile already exists: ${e}`)}function x(r){B(),_(K(r))}var o={DEFAULT_PROFILE:m,setOverrideProfile(r){F=r},getOverrideProfile(){return F},getProfileDir(r){return K(r)},getProfileConfigFile(r){return S.join(o.getProfileDir(r),"config.json")},getProfileCredentialsFile(r){return S.join(o.getProfileDir(r),"credentials.json")},getProfileNames(){return[...y().profiles]},getProfileCount(){return o.getProfileNames().length},getCurrentProfileName(){return y().currentProfile},getEffectiveProfileName(r){let e=y(),t=r||F||e.currentProfile;return v(t),b(e,t),t},ensureProfileExists(r){let e=y();v(r),b(e,r)},createProfile(r){v(r);let e=y();V(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};P(t),x(r)},deleteProfile(r){v(r);let e=y();if(b(e,r),e.profiles.length===1)throw new c("Cannot delete the last profile.");let t=e.profiles.filter(i=>i!==r),s=e.currentProfile;s===r&&(s=t.includes(m)?m:t[0]),P({currentProfile:s,profiles:t});try{u.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){v(r),v(e);let t=y();b(t,r),V(t,e);let s=K(r),n=K(e);if(u.existsSync(s))try{u.renameSync(s,n)}catch(k){throw new c("Failed to rename profile directory.",1,k)}else x(e);let i=t.profiles.map(k=>k===r?e:k),g=t.currentProfile===r?e:t.currentProfile;return P({currentProfile:g,profiles:i}),{currentProfile:g}},setCurrentProfile(r){v(r);let e=y();b(e,r);let t={currentProfile:r,profiles:e.profiles};P(t),x(r)},ensureProfileDir:x};var he="ENTRYDESK_FORCE_FILE_STORAGE",C="EntryDesk CLI",ye="__entrydesk_keychain_test__",me="profile:",we=".credentials.key",J={keychain:!1,permissions:!1,corruptFile:!1,windowsFile:!1};function w(r,e){J[r]||(J[r]=!0,console.error(e))}function q(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 ke(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 M(r){return o.getProfileCredentialsFile(r)}var L=class{getKeyFilePath(e){return pe.join(o.getProfileDir(e),we)}loadEncryptionKey(e){let t=this.getKeyFilePath(e);try{if(!f.existsSync(t))return null;let s=f.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=R.randomBytes(32);return f.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=R.randomBytes(16),n=R.createCipheriv("aes-256-gcm",t,s),i=n.update(e,"utf8","hex");i+=n.final("hex");let g=n.getAuthTag();return`${s.toString("hex")}:${g.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"),g=s[2],A=R.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});A.setAuthTag(i);let k=A.update(g,"hex","utf8");return k+=A.final("utf8"),k}tryDecrypt(e,t){try{return this.decrypt(e,t)}catch{return null}}tryParseCredentials(e){try{let t=JSON.parse(e);return q(t)?t:null}catch{return null}}ensureSecureFilePermissions(e){if(process.platform!=="win32"){try{f.chmodSync(e,384)}catch{w("permissions","Warning: Failed to set secure permissions on credentials file.");return}try{(f.statSync(e).mode&511)!==384&&w("permissions","Warning: Credentials file permissions are too permissive.")}catch{w("permissions","Warning: Failed to verify credentials file permissions.")}}}async getCredentials(e){let t=M(e);try{if(!f.existsSync(t))return null;let s=f.readFileSync(t,"utf-8").trim();if(!s)return null;let n=this.loadEncryptionKey(e),i=n?this.tryDecrypt(s,n):null;if(i){let g=this.tryParseCredentials(i);if(g)return g}return w("corruptFile","Warning: Credentials file is unreadable. Please run `entrydesk login` again."),null}catch{return null}}async setCredentials(e,t){o.ensureProfileDir(e);let s=M(e),n=this.getOrCreateEncryptionKey(e),i=this.encrypt(JSON.stringify(t),n);f.writeFileSync(s,i,{mode:384}),this.ensureSecureFilePermissions(s)}async deleteCredentials(e){let t=M(e);try{f.existsSync(t)&&f.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=ke(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${me}${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=`${ye}${R.randomBytes(8).toString("hex")}`,s="test";await e.setPassword(C,t,s);let n=await e.getPassword(C,t),i=await e.deletePassword(C,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(C,this.getAccount(e));if(!s)return null;let n=this.tryParseKeychainPayload(s);return n||w("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(C,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(C,this.getAccount(e))}tryParseKeychainPayload(e){try{let t=JSON.parse(e);return q(t)?t:null}catch{return null}}},j=class{keychainStorage=null;fileStorage=new L;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[he]?.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()&&(w("keychain","Keychain unavailable. Falling back to file-based credentials."),process.platform==="win32"&&w("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.initPromise=this.initializeStorage()),await this.initPromise)}disableKeychain(){this.shouldForceFileStorage()||w("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 j,h={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}};export{h as a,p as b,De as c,_e as d,c as e,je as f,o as g,I as h,T as i,O as j,Ae as k,be as l,z as m,$ as n};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{i as a,j as b,k as c,l as d,m as e}from"./chunk-
|
|
2
|
+
import{i as a,j as b,k as c,l as d,m as e}from"./chunk-7HCPZOK3.js";export{b as getApiUrl,e as getAuthConfig,a as getConfig,c as getHubUrl,d as getMcpConfig};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as $e,b as Qe,c as dt,d as pe,e as Dt,f as xe,g as H,h as ne,i as Me,n as B}from"./chunk-
|
|
2
|
+
import{a as $e,b as Qe,c as dt,d as pe,e as Dt,f as xe,g as H,h as ne,i as Me,n as B}from"./chunk-7HCPZOK3.js";import{render as Xi}from"ink";function Po(){console.log(`
|
|
3
3
|
Usage: entrydesk agents [list|create|update|delete] [options]
|
|
4
4
|
|
|
5
5
|
Commands:
|
|
@@ -21,7 +21,7 @@ Create/Update Options:
|
|
|
21
21
|
|
|
22
22
|
Flags:
|
|
23
23
|
--json Output JSON
|
|
24
|
-
`)}function Ks(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function rn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),
|
|
24
|
+
`)}function Ks(e){if(!e)return[];let t=new Map([["sandbox","sandbox"],["web","web_search"],["web-search","web_search"],["web_search","web_search"],["image","image_generation"],["image-gen","image_generation"],["image_generation","image_generation"],["chart","chart"]]);return e.map(o=>t.get(o)??o)}function rn(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),Po(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:Ks(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function an(e){try{if(e.help){Po();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="create"){let a=rn(e),l=await i.createAgent(o,s,a);if(e.json){console.log(JSON.stringify(l));return}console.log(`Created agent: ${l.name}`),console.log(` ID: ${l.id}`);return}if(n==="update"){let a=e.agentId;if(!a)throw new Error("Missing agentId for update command");let l=rn(e);await i.updateAgent(o,s,a,l),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await i.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),Po(),process.exit(1));let{agents:r}=await i.getAgents(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${r.length}):
|
|
25
25
|
`);for(let a of r)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){xe(t)}}function qs(){console.log(`
|
|
26
26
|
Usage: entrydesk budget [get|set|clear] [options]
|
|
27
27
|
|
|
@@ -32,7 +32,7 @@ Commands:
|
|
|
32
32
|
|
|
33
33
|
Flags:
|
|
34
34
|
--json Output JSON
|
|
35
|
-
`)}async function ln(e){try{if(e.help){qs();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new B;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){xe(t)}}import{render as Kr}from"ink";import{v4 as yo}from"uuid";import{exec as zs}from"child_process";import Ys from"fs";import et from"fs/promises";import cn from"os";import
|
|
35
|
+
`)}async function ln(e){try{if(e.help){qs();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",i=new B;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await i.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await i.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let r=await i.getBudget(o,s);if(e.json){console.log(JSON.stringify(r));return}if(r.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${r.budget}`)}catch(t){xe(t)}}import{render as Kr}from"ink";import{v4 as yo}from"uuid";import{exec as zs}from"child_process";import Ys from"fs";import et from"fs/promises";import cn from"os";import Ao from"path";import{promisify as Xs}from"util";import{glob as Zs}from"glob";var Qs=Xs(zs),er=`## Filesystem Tool Instructions
|
|
36
36
|
|
|
37
37
|
You have access to filesystem tools that allow you to interact with the user's local filesystem.
|
|
38
38
|
|
|
@@ -57,17 +57,17 @@ You have access to filesystem tools that allow you to interact with the user's l
|
|
|
57
57
|
- Execute Command has a default timeout of 30 seconds (max 5 minutes)
|
|
58
58
|
- The current working directory is: ${process.cwd()}
|
|
59
59
|
- The user's home directory is: ${cn.homedir()}
|
|
60
|
-
`,tr=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function un(){return{name:"filesystem",systemPrompt:er,tools:tr}}function Ke(e){return e.startsWith("~/")?
|
|
60
|
+
`,tr=[{name:"filesystem__read_file",description:"Read the contents of a file from the local filesystem.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to read."}},required:["path"]}},{name:"filesystem__read_multiple_files",description:"Read multiple files at once (max 10 files).",inputSchema:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of absolute file paths to read."}},required:["paths"]}},{name:"filesystem__write_file",description:"Create or overwrite a file with the given content.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the file to write."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]}},{name:"filesystem__create_directory",description:"Create a new directory (including parent directories if needed).",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to create."}},required:["path"]}},{name:"filesystem__list_directory",description:"List files and subdirectories in a directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path of the directory to list."}},required:["path"]}},{name:"filesystem__search_files",description:"Search for files matching a glob pattern.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts").'},cwd:{type:"string",description:"Base directory to search in (optional)."}},required:["pattern"]}},{name:"filesystem__get_file_info",description:"Get metadata about a file or directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute path to get info for."}},required:["path"]}},{name:"filesystem__move_file",description:"Move or rename a file or directory.",inputSchema:{type:"object",properties:{source:{type:"string",description:"The source path."},destination:{type:"string",description:"The destination path."}},required:["source","destination"]}},{name:"filesystem__execute_command",description:"Execute a shell command on the local machine.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to execute."},cwd:{type:"string",description:"Working directory for the command (optional)."},timeout:{type:"number",description:"Timeout in milliseconds (default: 30000, max: 300000)."}},required:["command"]}}];function un(){return{name:"filesystem",systemPrompt:er,tools:tr}}function Ke(e){return e.startsWith("~/")?Ao.join(cn.homedir(),e.slice(2)):e}function oo(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
|
|
61
61
|
|
|
62
|
-
... (truncated, ${e.length-t} more characters)`}async function dn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ke(t.path),s=await et.readFile(o,"utf-8");return{success:!0,result:oo(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Ke(n);try{let r=await et.readFile(i,"utf-8");s[n]=oo(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ke(t.path),s=t.content;return await et.mkdir(
|
|
62
|
+
... (truncated, ${e.length-t} more characters)`}async function dn(e,t){try{switch(e){case"filesystem__read_file":{let o=Ke(t.path),s=await et.readFile(o,"utf-8");return{success:!0,result:oo(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let i=Ke(n);try{let r=await et.readFile(i,"utf-8");s[n]=oo(r,5e4)}catch(r){s[n]={error:r instanceof Error?r.message:String(r)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Ke(t.path),s=t.content;return await et.mkdir(Ao.dirname(o),{recursive:!0}),await et.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Ke(t.path);return await et.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Ke(t.path);return{success:!0,result:(await et.readdir(o,{withFileTypes:!0})).map(i=>({name:i.name,type:i.isDirectory()?"directory":i.isFile()?"file":i.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Ke(t.cwd):process.cwd(),n=await Zs(o,{cwd:s,nodir:!0,maxDepth:10});return{success:!0,result:{files:n.slice(0,100),total:n.length,truncated:n.length>100}}}case"filesystem__get_file_info":{let o=Ke(t.path),s=await et.stat(o);return{success:!0,result:{path:o,type:s.isDirectory()?"directory":s.isFile()?"file":"other",size:s.size,created:s.birthtime.toISOString(),modified:s.mtime.toISOString(),accessed:s.atime.toISOString(),mode:s.mode.toString(8)}}}case"filesystem__move_file":{let o=Ke(t.source),s=Ke(t.destination);return await et.mkdir(Ao.dirname(s),{recursive:!0}),await et.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Ke(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!Ys.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:i,stderr:r}=await Qs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:oo(i,5e4),stderr:oo(r,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function No(e){return e.startsWith("filesystem__")}function fn(){return[un()]}function no(){return fn().flatMap(e=>e.tools)}function so(){return fn().map(e=>e.systemPrompt).filter(Boolean).join(`
|
|
63
63
|
|
|
64
|
-
`)}function tt(e){return
|
|
65
|
-
`){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Cn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ir=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=xn(()=>
|
|
66
|
-
`,...m.slice(a)].join("");Y(L,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&
|
|
64
|
+
`)}function tt(e){return No(e)}async function ro(e,t){return No(e)?dn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as Pe,Text as K,useInput as Ho}from"ink";import Vo from"ink-spinner";import{useCallback as Ko,useEffect as ho,useRef as ss,useState as Br}from"react";import{Box as io,Text as Ot}from"ink";import{jsx as ao,jsxs as Rt}from"react/jsx-runtime";function pn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function mn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:i,pageSize:r=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),C=Math.max(1,r),x=Math.floor(t/C)*C,b=Math.min(e.length,x+C),$=e.slice(x,b);return Rt(io,{flexDirection:"column",marginBottom:1,children:[ao(Ot,{bold:!0,color:"cyan",children:i}),ao(io,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:$.map((m,h)=>{let D=x+h===t,V=o?.has(m.id),Z=pn(m.name,d),ae=m.description?pn(m.description,Math.max(0,d-l)):"",Y=s?" ".repeat(l):"";return Rt(io,{paddingX:1,flexDirection:"column",children:[Rt(io,{children:[s&&ao(Ot,{color:V?"green":"gray",children:V?"[\u2713] ":"[ ] "}),ao(Ot,{backgroundColor:D?"cyan":void 0,color:D?"black":V?"green":"white",bold:!0,children:Z})]}),ae&&Rt(Ot,{dimColor:!0,children:[Y,"\xB7 ",ae]})]},m.id)})}),Rt(Ot,{dimColor:!0,children:[s?"\u2191\u2193 Navigate \xB7 Space Toggle \xB7 a All \xB7 n None \xB7 Enter Confirm \xB7 Esc Cancel":"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Cancel",e.length>C?` \xB7 Showing ${x+1}-${b} of ${e.length}`:""]})]})}import{Box as Eo,Text as Ut}from"ink";import{jsx as jt,jsxs as _o}from"react/jsx-runtime";function gn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:_o(Eo,{flexDirection:"column",marginBottom:1,children:[jt(Eo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let i=n===t,r=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return _o(Eo,{paddingX:1,children:[_o(Ut,{backgroundColor:i?"cyan":void 0,color:i?"black":"cyan",bold:i,children:["/",s.name]}),jt(Ut,{dimColor:!0,children:r}),jt(Ut,{children:" - "}),jt(Ut,{color:i?"white":"gray",children:s.description})]},s.name)})}),jt(Ut,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as or,Text as hn,useInput as nr,useStdout as sr}from"ink";import{useCallback as yn,useEffect as wn,useMemo as Lo,useRef as kn,useState as xn}from"react";import{jsx as Ro}from"react/jsx-runtime";function lo(e,t){return e<0?0:e>t?t:e}function Do(e){return Array.from(e)}function co(e){return/\s/.test(e)}function Oo(e,t){let o=t;for(;o>0&&co(e[o-1]??"");)o-=1;for(;o>0&&!co(e[o-1]??"");)o-=1;return o}function bn(e,t){let o=t;for(;o<e.length&&co(e[o]??"");)o+=1;for(;o<e.length&&!co(e[o]??"");)o+=1;return o}function rr(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((r,a)=>{if(r===`
|
|
65
|
+
`){t.push(s),s=[],n=a+1,o.push(n);return}s.push(r)}),t.push(s);let i=t.map(r=>r.length);return{lines:t,lineStarts:o,lineLengths:i}}function Cn(e,t,o){for(let n=0;n<t.length;n+=1){let i=t[n]??0,r=o[n]??0,a=i+r;if(e<=a)return{row:n,col:e-i}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ir=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:i=0,multiline:r=!1}){let[a,l]=xn(()=>Do(e).length),d=kn(null),[C,x]=xn(0),b=kn(null),{stdout:$}=sr(),m=Lo(()=>Do(e),[e]),{lines:h,lineStarts:T,lineLengths:D}=Lo(()=>rr(m),[m]),{row:V,col:Z}=Lo(()=>Cn(a,T,D),[a,T,D]),ae=Math.max(1,($?.columns??80)-i);wn(()=>{d.current!==e?(l(m.length),b.current=null):l(j=>lo(j,m.length)),d.current=e},[e,m.length]),wn(()=>{x(j=>{let P=j;Z<P?P=Z:Z>=P+ae&&(P=Z-ae+1);let E=D[V]??0,R=Z===E?E+1:E,W=Math.max(0,R-ae);return P>W&&(P=W),P<0&&(P=0),P})},[ae,Z,V,D]);let Y=yn((j,P)=>{d.current=j,t(j),l(P),b.current=null},[t]),Se=yn(async(j,P)=>{if(!n)return;let{row:E,col:R}=Cn(a,T,D),W=h[E]??[],_=D[E]??0,he=h.length>1;if(r&&(P.meta&&P.return||P.ctrl&&j==="j"||P.shift&&P.return)){let L=[...m.slice(0,a),`
|
|
66
|
+
`,...m.slice(a)].join("");Y(L,a+1);return}if(P.return){o(e);return}if(P.leftArrow){P.ctrl||P.meta?(R===0&&E>0?l(T[E]-1):l(T[E]+Oo(W,R)),b.current=null):(R===0&&E>0?l(T[E]-1):l(L=>lo(L-1,m.length)),b.current=null);return}if(P.rightArrow){P.ctrl||P.meta?(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),b.current=null):(R>=_&&E<h.length-1?l(T[E+1]):l(L=>lo(L+1,m.length)),b.current=null);return}if(r&&he&&P.upArrow){let L=b.current??R,p=Math.max(0,E-1),ie=Math.min(L,D[p]??0);l((T[p]??0)+ie),b.current=L;return}if(r&&he&&P.downArrow){let L=b.current??R,p=Math.min(h.length-1,E+1),ie=Math.min(L,D[p]??0);l((T[p]??0)+ie),b.current=L;return}if(P.ctrl){if(j==="a"){l(T[E]??0),b.current=null;return}if(j==="e"){l((T[E]??0)+_),b.current=null;return}if(j==="u"){if(R>0){let L=T[E]??0,p=[...m.slice(0,L),...m.slice(a)].join("");Y(p,L)}return}if(j==="k"){if(R<_){let L=(T[E]??0)+_,p=[...m.slice(0,a),...m.slice(L)].join("");Y(p,a)}return}if(j==="w"){if(R===0&&E>0){let p=[...m.slice(0,a-1),...m.slice(a)].join("");Y(p,a-1);return}let L=Oo(W,R);if(L!==R){let p=(T[E]??0)+L,ie=[...m.slice(0,p),...m.slice(a)].join("");Y(ie,p)}return}if(j==="d"){if(a<m.length){let L=[...m.slice(0,a),...m.slice(a+1)].join("");Y(L,a)}return}return}if(P.meta){j==="b"?(R===0&&E>0?l(T[E]-1):l(T[E]+Oo(W,R)),b.current=null):j==="f"&&(R>=_&&E<h.length-1?l(T[E+1]):l(T[E]+bn(W,R)),b.current=null);return}if(P.backspace||P.delete){if(a<=0)return;let L=[...m.slice(0,a-1),...m.slice(a)].join("");Y(L,a-1);return}if(!(P.tab||P.escape)&&j.length>0){let L=r?j.replace(/\r\n/g,`
|
|
67
67
|
`).replace(/\r/g,`
|
|
68
68
|
`):j.replace(/\r?\n/g,"");if(!L||(L=L.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!L))return;if((L.length>=ir||L.includes(`
|
|
69
|
-
`))&&s){let q=!1,A={text:L,preventDefault:()=>{q=!0}};if(await Promise.resolve(s(A)),q)return}let ie=
|
|
70
|
-
`);return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},In=
|
|
69
|
+
`))&&s){let q=!1,A={text:L,preventDefault:()=>{q=!0}};if(await Promise.resolve(s(A)),q)return}let ie=Do(L),ke=[...m.slice(0,a),...ie,...m.slice(a)].join("");Y(ke,a+ie.length)}},[m,a,n,D,T,h,r,s,o,Y,e]);return nr(Se,{isActive:n}),Ro(or,{flexDirection:"column",children:h.map((j,P)=>{let E=P===V,W=(E&&Z===j.length?[...j," "]:j).slice(C,C+ae),_=W.join("");if(!E)return Ro(hn,{children:_||" "},P);let he=lo(Z-C,Math.max(0,W.length-1)),L=W.slice(0,he).join(""),p=W[he]??" ",ie=W.slice(he+1).join(""),A=`${L}\x1B[7m${p}\x1B[27m${ie}`;return Ro(hn,{children:A},P)})})}import{Box as qe,Text as ft}from"ink";import Fo from"react";import{Text as Be}from"ink";import ar from"react";import{Fragment as ur,jsx as Je,jsxs as vn}from"react/jsx-runtime";var Uo=2,jo=1,Bo=2,lr=1,Sn=3,Tn=4,cr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Je(Be,{color:n,children:e});let i=[],r=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>r&&i.push(Je(Be,{color:n,children:e.slice(r,l.index)},`t-${r}`));let d=l[0],C=null,x=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Uo*2)C=Je(Be,{bold:!0,color:n,children:d.slice(Uo,-Uo)},x);else if(d.length>jo*2&&(d.startsWith("*")&&d.endsWith("*")||d.startsWith("_")&&d.endsWith("_"))&&!/\w/.test(e.substring(l.index-1,l.index))&&!/\w/.test(e.substring(a.lastIndex,a.lastIndex+1))&&!/\S[./\\]/.test(e.substring(l.index-2,l.index))&&!/[./\\]\S/.test(e.substring(a.lastIndex,a.lastIndex+2)))C=Je(Be,{italic:!0,color:n,children:d.slice(jo,-jo)},x);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Bo*2)C=Je(Be,{strikethrough:!0,color:n,children:d.slice(Bo,-Bo)},x);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>lr){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(C=Je(Be,{color:s,children:b[2]},x))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let $=b[1],m=b[2];C=vn(Be,{color:n,children:[$,vn(Be,{color:o,children:[" (",m,")"]})]},x)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Sn+Tn-1?C=Je(Be,{underline:!0,color:n,children:d.slice(Sn,-Tn)},x):d.match(/^https?:\/\//)&&(C=Je(Be,{color:o,children:d},x))}catch{C=null}i.push(C??Je(Be,{color:n,children:d},x)),r=a.lastIndex}return r<e.length&&i.push(Je(Be,{color:n,children:e.slice(r)},`t-${r}`)),Je(ur,{children:i.filter(d=>d!==null)})},Bt=ar.memo(cr);import{Fragment as yr,jsx as we,jsxs as Nn}from"react/jsx-runtime";var dr=1,An=1,fr=1,pr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,i=/^([ \t]*)([-*+]) +(.*)/,r=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],C=!1,x=!0,b=[],$="";function m(h){h&&(d.push(h),x=!1)}return o.forEach((h,T)=>{let D=`line-${T}`;if(C){let P=h.match(n);P&&P[1].startsWith($[0])&&P[1].length>=$.length?(m(we(In,{content:b},D)),C=!1,b=[],$=""):b.push(h);return}let V=h.match(n),Z=h.match(s),ae=h.match(i),Y=h.match(r),Se=h.match(a),j=h.match(l);if(V)C=!0,$=V[1];else if(Se)m(we(qe,{children:we(ft,{dimColor:!0,children:"---"})},D));else if(Z){let P=Z[1].length,E=Z[2],R=P<=2?"cyan":"blue";m(we(qe,{children:we(ft,{color:R,...(P===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:we(Bt,{text:E,defaultColor:R,linkColor:"cyan",codeColor:"yellow"})})},D))}else if(j){let P=j[1];m(we(qe,{paddingLeft:1,children:Nn(ft,{dimColor:!0,children:["> ",we(Bt,{text:P,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},D))}else if(ae){let P=ae[1],E=ae[2],R=ae[3];m(we(Pn,{itemText:R,type:"ul",marker:E,leadingWhitespace:P},D))}else if(Y){let P=Y[1],E=Y[2],R=Y[3];m(we(Pn,{itemText:R,type:"ol",marker:E,leadingWhitespace:P},D))}else h.trim().length===0?x||(d.push(we(qe,{height:dr},`spacer-${T}`)),x=!0):m(we(qe,{children:we(ft,{wrap:"wrap",children:we(Bt,{text:h,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},D))}),C&&m(we(In,{content:b},"line-eof")),we(yr,{children:d})},gr=({content:e})=>{let t=e.join(`
|
|
70
|
+
`);return we(qe,{paddingLeft:An,flexDirection:"column",children:we(ft,{color:"yellow",children:t})})},In=Fo.memo(gr),hr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,i=n.length,r=s.length;return Nn(qe,{paddingLeft:r+fr,flexDirection:"row",children:[we(qe,{width:i,children:we(ft,{children:n})}),we(qe,{flexGrow:pr,children:we(ft,{wrap:"wrap",children:we(Bt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Pn=Fo.memo(hr),Wo=Fo.memo(mr);import{execFile as wr}from"child_process";import kr from"fs";import St from"fs/promises";import En from"os";import fo from"path";import{promisify as xr}from"util";var uo=xr(wr);async function br(){let e=fo.join(En.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
|
|
71
71
|
set imageData to the clipboard as "PNGf"
|
|
72
72
|
set fileRef to open for access POSIX file "${e}" with write permission
|
|
73
73
|
set eof fileRef to 0
|
|
@@ -81,7 +81,7 @@ You have access to filesystem tools that allow you to interact with the user's l
|
|
|
81
81
|
$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
82
82
|
[System.Convert]::ToBase64String($ms.ToArray())
|
|
83
83
|
}
|
|
84
|
-
`,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await uo("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function _n(){let e=
|
|
84
|
+
`,{stdout:t}=await uo("powershell.exe",["-command",e]),o=t.trim();if(!o)return;let s=Buffer.from(o,"base64");return s.length===0?void 0:{buffer:s,mime:"image/png"}}catch{return}}async function $r(){try{let{stdout:e}=await uo("wl-paste",["-t","image/png"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}try{let{stdout:e}=await uo("xclip",["-selection","clipboard","-t","image/png","-o"],{encoding:"buffer",maxBuffer:52428800});if(e&&e.length>0)return{buffer:e,mime:"image/png"}}catch{}}async function _n(){let e=En.platform();if(e==="darwin")return br();if(e==="win32")return Cr();if(e==="linux")return $r()}var Sr=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".heic",".heif",".pdf",".txt",".md",".rtf",".csv",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".key",".pages",".numbers",".odt",".ods",".odp",".json",".xml",".yaml",".yml"]);function Ln(e){let t=fo.extname(e).toLowerCase();return Sr.has(t)}function Tr(e){let t=fo.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".txt":"text/plain",".md":"text/markdown",".pdf":"application/pdf",".csv":"text/csv",".rtf":"application/rtf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".key":"application/vnd.apple.keynote",".pages":"application/vnd.apple.pages",".numbers":"application/vnd.apple.numbers",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".json":"application/json",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml"}[t]||"application/octet-stream"}function po(e){let t=e.trim();return t.startsWith("file://")&&(t=decodeURIComponent(t.slice(7))),(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t=t.replace(/\\(.)/g,"$1"),t}async function Dn(e){let t=po(e);if(/^https?:\/\//.test(t))return!1;try{return await St.access(t),!0}catch{return!1}}async function On(e){let t=po(e);try{if(!(await St.stat(t)).isFile())return;let s=await St.readFile(t),n=Tr(t),i=fo.basename(t);return{buffer:s,mimeType:n,filename:i}}catch{return}}var Fe="\x1B[2m",re="\x1B[0m",Ie="\x1B[36m",Tt="\x1B[32m",Rn="\x1B[31m",gt="\x1B[38;2;59;91;204m",Mo="\x1B[38;2;126;200;248m",Jo="\x1B[38;2;244;196;78m";import{useState as ot}from"react";import{v4 as Un}from"uuid";function jn(e,t){let[o,s]=ot({status:"loading"}),[n,i]=ot([]),[r,a]=ot(""),[l,d]=ot(()=>e||Un()),[C,x]=ot(t),[b,$]=ot(!!e),[m,h]=ot(null),[T,D]=ot(""),[V,Z]=ot(!1),ae=Se=>{i(j=>[...j,{role:"system",content:Se}])};return{state:o,setState:s,messages:n,setMessages:i,input:r,setInput:a,chatId:l,setChatId:d,currentChatTitle:C,setCurrentChatTitle:x,hasPersistedChat:b,setHasPersistedChat:$,credentials:m,setCredentials:h,currentResponse:T,setCurrentResponse:D,fullOutput:V,setFullOutput:Z,addSystemMessage:ae,startNewChat:Se=>{let j=Un();d(j),x(void 0),$(!1),i([]),Se&&ae(Se)}}}import{useEffect as vr,useState as Bn}from"react";function Fn(e){let[t,o]=Bn(null),[s,n]=Bn(!0);return vr(()=>{let i=!1;async function r(){try{let a=await pe();if(i)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(i)return;if(a instanceof Qe){if(a.code==="not-logged-in"){e({status:"not-logged-in"}),n(!1);return}if(a.code==="no-workspace"){e({status:"no-workspace"}),n(!1);return}}let l=a instanceof Error?a.message:"Failed to authenticate";e({status:"error",message:l}),n(!1)}}return r(),()=>{i=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Ir,useState as Ft}from"react";function Wn(e){let[t,o]=Ft([]),[s,n]=Ft([]),[i,r]=Ft([]),[a,l]=Ft([]),[d,C]=Ft(!1);return Ir(()=>{if(!e)return;let x=!1;C(!0);async function b(){if(e)try{let $=new B,[m,h,T,D]=await Promise.all([$.getConnectors(e.accessToken,e.workspaceId),$.getModels(e.accessToken,e.workspaceId),$.getAgents(e.accessToken,e.workspaceId),$.getModelProviders(e.accessToken,e.workspaceId)]);if(x)return;o(m.connectors),n(h.models),r(T.agents),l(D.providers??[])}catch{}finally{x||C(!1)}}return b(),()=>{x=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:i,modelProviders:a,loading:d}}import vt from"fs";import Jn from"path";import{useCallback as Pr}from"react";import{v4 as Ar}from"uuid";function Mn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let i=n.stdout.trim();return t||i.length<=200?i:i.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
|
|
85
85
|
`);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function ht(e,t=!1){let o=[];for(let s of e)if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="reasoning"&&s.text)t?o.push(`${Fe}[Thinking]
|
|
86
86
|
${s.text}${re}`):o.push(`${Fe}[Thinking...]${re}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${Ie}\u250C\u2500 Tool: ${s.toolName}${re}`),s.args){let i=JSON.stringify(s.args,null,t?2:void 0),r=t||i.length<=100?i:i.slice(0,100)+"...";n.push(`${Fe}\u2502 Args: ${r}${re}`)}s.result!==void 0?(n.push(`${Tt}\u2502 Result: ${Mn(s.result,t)}${re}`),n.push(`${Ie}\u2514\u2500 completed${re}`)):n.push(`${Ie}\u2514\u2500${re}`),o.push(n.join(`
|
|
87
87
|
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),i=[];if(i.push(`${Ie}\u250C\u2500 Tool: ${n}${re}`),s.input){let r=JSON.stringify(s.input,null,t?2:void 0),a=t||r.length<=100?r:r.slice(0,100)+"...";i.push(`${Fe}\u2502 Input: ${a}${re}`)}s.output!==void 0&&s.state==="output-available"?(i.push(`${Tt}\u2502 Output: ${Mn(s.output,t)}${re}`),i.push(`${Ie}\u2514\u2500 completed${re}`)):s.state==="error"?i.push(`${Ie}\u2514\u2500 failed${re}`):i.push(`${Ie}\u2514\u2500${re}`),o.push(i.join(`
|
|
@@ -111,14 +111,14 @@ ${Rn}\u2502 Error: ${r}${re}`,o+=`
|
|
|
111
111
|
${Ie}\u2514\u2500 failed${re}
|
|
112
112
|
`,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var Wt=Jn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function le(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
|
|
113
113
|
DATA: ${JSON.stringify(t,null,2)}`),s+=`
|
|
114
|
-
`;try{vt.appendFileSync(Wt,s)}catch{}}function
|
|
115
|
-
`)}}catch{}}function go(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Gn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:
|
|
116
|
-
`);ke=
|
|
114
|
+
`;try{vt.appendFileSync(Wt,s)}catch{}}function Nr(){try{if(vt.existsSync(Wt)&&vt.unlinkSync(Wt),process.env.DEBUG){let e=Jn.dirname(Wt);vt.existsSync(e)||vt.mkdirSync(e,{recursive:!0}),vt.writeFileSync(Wt,`=== Debug session started at ${new Date().toISOString()} ===
|
|
115
|
+
`)}}catch{}}function go(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Gn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:i,webSearch:r,imageGeneration:a,chart:l,localTools:d,fullOutput:C,setMessages:x,setState:b,setCurrentResponse:$,setCredentials:m,setHasPersistedChat:h,getFileIds:T,clearFiles:D}){let V=d?no():void 0,Z=d?so():void 0;return{sendMessage:Pr(async(Y,Se,j)=>{Nr(),le("=== sendMessage called ===",{text:Y,localTools:d,clientToolsCount:V?.length});let P=Se||t?.accessToken,E=j||t?.workspaceId;if(!P||!E)try{let _=await pe();P=_.accessToken,E=_.workspaceId,m(_)}catch(_){if(_ instanceof Qe){if(_.code==="not-logged-in"){b({status:"not-logged-in"});return}if(_.code==="no-workspace"){b({status:"no-workspace"});return}}let he=_ instanceof Error?_.message:"Authentication failed";b({status:"error",message:he});return}else try{let _=await dt();_!==P&&(P=_,m({accessToken:_,workspaceId:E}))}catch(_){if(_ instanceof Qe&&_.code==="not-logged-in"){b({status:"not-logged-in"});return}let he=_ instanceof Error?_.message:"Authentication failed";b({status:"error",message:he});return}x(_=>[..._,{role:"user",content:Y}]),b({status:"sending"}),$("");let R=null,W=null;try{let _=new B,he=T?.()??[],L={id:e,message:{id:Ar(),createdAt:new Date,role:"user",parts:[{type:"text",text:Y}]}};he.length>0&&(L.fileIds=he),o?L.agentId=o:(s&&(L.model=s),L.connectorIds=n??[],L.enableSandbox=i,L.enableWebSearch=r,L.enableImageGeneration=a,L.enableChart=l),V&&(L.clientTools=V),Z&&(L.clientToolSystemPrompt=Z);let p=await _.chat(P,E,L);if(!p.ok){let F=await p.text();throw new Error(`API error ${p.status}: ${F}`)}if(!p.body)throw new Error("No response body from server");R=p.body.getReader();let ie=new TextDecoder,ke="",q="",A="",te="",ee="",me="",ce="",M=new mo,Q=[],z=[],fe=[],Te=()=>{let F=M.hasExecuting();F&&!W?W=setInterval(()=>{if(!M.hasExecuting()){W&&(clearInterval(W),W=null);return}$(q+M.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:se}=await R.read();if(F)break;ke+=ie.decode(se,{stream:!0});let O=ke.split(`
|
|
116
|
+
`);ke=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(le(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":te=w.id||"0",A="";break;case"reasoning-delta":w.delta&&(A+=w.delta,$(`${Fe}[Thinking...]${re}
|
|
117
117
|
${A}`)),w.providerMetadata?.anthropic?.signature&&(ee=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let v={type:"reasoning",id:te,text:A,state:"done"};ee&&(v.providerMetadata={anthropic:{signature:ee}}),z.push(v),le("Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$("");break;case"text-delta":w.delta&&(M.hasPending()&&(q=M.flushPending(q)),q+=w.delta,me+=w.delta,$(q));break;case"tool-input-start":{let v=M.handleToolInputStart(w);v&&$(q+v),Te();break}case"tool-input-delta":{let v=M.handleToolInputDelta(w);v&&$(q+v),Te();break}case"tool-call":case"tool-input-available":{if(le(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?tt(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let v=go(w.args??w.input);z.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:v}),le("Added tool to messageParts",{messagePartsCount:z.length})}if(d&&w.toolCallId&&w.toolName&&tt(w.toolName)){let v=go(w.args??w.input);Q.push({toolCallId:w.toolCallId,toolName:w.toolName,args:v}),le("Added to pendingClientTools",{pendingCount:Q.length,pendingClientTools:Q}),$(q+M.buildToolDisplay()+`
|
|
118
|
-
[Executing ${w.toolName} locally...]`)}else le("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?tt(w.toolName):!1});break}case"tool-output-start":{let v=M.handleToolOutputStart(w);v&&$(q+v),Te();break}case"tool-output-delta":{let v=M.handleToolOutputDelta(w);v&&$(q+v),Te();break}case"tool-output-end":{let v=M.handleToolOutputEnd(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let v=M.handleToolError(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"start":w.messageId&&(ce=w.messageId,le("Captured messageId from start event",{messageId:ce}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(me){let F=z.findIndex(
|
|
119
|
-
`);fe.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:oe,isError:f.isError})}}if(le("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let se={id:e,clientToolResults:F};o?se.agentId=o:(s&&(se.model=s),se.connectorIds=n??[],se.enableSandbox=i,se.enableWebSearch=r,se.enableImageGeneration=a,se.enableChart=l),V&&(se.clientTools=V),Z&&(se.clientToolSystemPrompt=Z),le("=== Sending continuation request ===",{chatId:e,hasAgentId:!!se.agentId,hasModel:!!se.model,clientToolResultsCount:F.length});let
|
|
118
|
+
[Executing ${w.toolName} locally...]`)}else le("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?tt(w.toolName):!1});break}case"tool-output-start":{let v=M.handleToolOutputStart(w);v&&$(q+v),Te();break}case"tool-output-delta":{let v=M.handleToolOutputDelta(w);v&&$(q+v),Te();break}case"tool-output-end":{let v=M.handleToolOutputEnd(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"tool-input-error":case"tool-output-error":{let v=M.handleToolError(w,q);v&&(q=v.fullResponse,$(q+v.toolDisplay)),Te();break}case"start":w.messageId&&(ce=w.messageId,le("Captured messageId from start event",{messageId:ce}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(me){let F=z.findIndex(O=>O.type!=="reasoning"),se=F===-1?z.length:F;z.splice(se,0,{type:"text",text:me}),le("Added accumulated text to messageParts",{textLength:me.length,insertIndex:se})}for(le("=== Initial stream ended ===",{pendingClientToolsCount:Q.length,pendingClientTools:Q,messagePartsCount:z.length,messageParts:z.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Q.length>0;){le("=== Starting pending tools execution loop ===",{pendingCount:Q.length});let F=[];for(let f of Q){le(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),M.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),M.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),$(q+M.buildToolDisplay()),Te();let w=await ro(f.toolName,f.args);le(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let v=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:v}],isError:!w.success}),w.success){M.handleToolOutputStart({toolCallId:f.toolCallId}),M.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let oe=M.handleToolOutputEnd({toolCallId:f.toolCallId},q);oe&&(q=oe.fullResponse)}else{let oe=M.handleToolError({toolCallId:f.toolCallId,errorText:w.error},q);oe&&(q=oe.fullResponse)}$(q+M.buildToolDisplay()),Te()}Q.length=0;for(let f of F){let w=z.find(v=>(v.type==="tool-input-available"||v.type==="tool-call")&&v.toolCallId===f.toolCallId);if(w){let v=[];for(let U of f.content)U.type==="text"?v.push(U.text):U.type==="image"?v.push("[Image]"):U.type==="audio"?v.push("[Audio]"):(U.type==="resource"||U.type==="resource_link")&&v.push("[Resource]");let oe=v.join(`
|
|
119
|
+
`);fe.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:oe,isError:f.isError})}}if(le("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),R)try{R.releaseLock()}catch{}let se={id:e,clientToolResults:F};o?se.agentId=o:(s&&(se.model=s),se.connectorIds=n??[],se.enableSandbox=i,se.enableWebSearch=r,se.enableImageGeneration=a,se.enableChart=l),V&&(se.clientTools=V),Z&&(se.clientToolSystemPrompt=Z),le("=== Sending continuation request ===",{chatId:e,hasAgentId:!!se.agentId,hasModel:!!se.model,clientToolResultsCount:F.length});let O=await _.chat(P,E,se);if(le("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(le("=== Processing continuation stream ==="),R=O.body.getReader(),z.length=0,me="",A="",te="",ee="";;){let{done:f,value:w}=await R.read();if(f){le("=== Continuation stream done ===");break}ke+=ie.decode(w,{stream:!0});let v=ke.split(`
|
|
120
120
|
`);ke=v.pop()||"";for(let oe of v)if(oe.trim()!=="data: [DONE]"&&oe.startsWith("data: "))try{let U=JSON.parse(oe.slice(6));switch(le(`Continuation SSE: ${U.type}`,U),U.type){case"reasoning-start":te=U.id||"0",A="";break;case"reasoning-delta":U.delta&&(A+=U.delta,$(`${Fe}[Thinking...]${re}
|
|
121
|
-
${A}`)),U.providerMetadata?.anthropic?.signature&&(ee=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Ce={type:"reasoning",id:te,text:A,state:"done"};ee&&(Ce.providerMetadata={anthropic:{signature:ee}}),z.push(Ce),le("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$(q);break;case"text-delta":U.delta&&(q+=U.delta,me+=U.delta,$(q));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Ce=go(U.args??U.input);z.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Ce})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Ce=go(U.args??U.input);Q.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Ce}),le("Continuation: Added to pendingClientTools",{pendingCount:Q.length})}break;case"finish":le("Continuation finish event",U);break}}catch{}}if(me){let f=z.findIndex(v=>v.type!=="reasoning"),w=f===-1?z.length:f;z.splice(w,0,{type:"text",text:me})}le("=== Continuation stream processing complete ===",{pendingClientToolsCount:Q.length,messagePartsCount:z.length,fullResponseLength:q.length})}if(d&&V&&V.length>0){let F=[];for(let
|
|
121
|
+
${A}`)),U.providerMetadata?.anthropic?.signature&&(ee=U.providerMetadata.anthropic.signature);break;case"reasoning-end":if(A){let Ce={type:"reasoning",id:te,text:A,state:"done"};ee&&(Ce.providerMetadata={anthropic:{signature:ee}}),z.push(Ce),le("Continuation: Added reasoning to messageParts",{reasoningLength:A.length,hasSignature:!!ee,messagePartsCount:z.length})}A="",ee="",$(q);break;case"text-delta":U.delta&&(q+=U.delta,me+=U.delta,$(q));break;case"tool-call":case"tool-input-available":if(U.toolCallId&&U.toolName){let Ce=go(U.args??U.input);z.push({type:U.type,toolCallId:U.toolCallId,toolName:U.toolName,args:Ce})}if(d&&U.toolCallId&&U.toolName&&tt(U.toolName)){let Ce=go(U.args??U.input);Q.push({toolCallId:U.toolCallId,toolName:U.toolName,args:Ce}),le("Continuation: Added to pendingClientTools",{pendingCount:Q.length})}break;case"finish":le("Continuation finish event",U);break}}catch{}}if(me){let f=z.findIndex(v=>v.type!=="reasoning"),w=f===-1?z.length:f;z.splice(w,0,{type:"text",text:me})}le("=== Continuation stream processing complete ===",{pendingClientToolsCount:Q.length,messagePartsCount:z.length,fullResponseLength:q.length})}if(d&&V&&V.length>0){let F=[];for(let O of fe)F.push({type:String(O.type),title:String(O.toolName).replace(/__/g," "),input:O.input,output:O.output,state:O.isError?"error":"output-available"});for(let O of z)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let se=ht(F,C);le("=== Using formatted parts for local tools ===",{executedToolsCount:fe.length,textPartsCount:z.filter(O=>O.type==="text").length,contentLength:se.length}),x(O=>[...O,{role:"assistant",content:se,parts:F}])}else{le("=== Fetching message from API ===",{fullResponseLength:q.length,fullResponsePreview:q.slice(0,200)});try{let{messages:F}=await _.getMessages(P,E,e,10);le("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let se=F.find(O=>O.role==="assistant");if(se){let O=se.parts,f=ht(O,C);le("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),x(w=>[...w,{role:"assistant",content:f,parts:O}])}else le("=== No assistant message found, using fallback ==="),x(O=>[...O,{role:"assistant",content:q}])}catch(F){le("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),x(se=>[...se,{role:"assistant",content:q}])}}le("=== Message handling complete ==="),$(""),b({status:"ready"}),h(!0),he.length>0&&D?.()}catch(_){le("=== ERROR ===",{message:_ instanceof Error?_.message:String(_),stack:_ instanceof Error?_.stack:void 0});let he=_ instanceof Error?_.message:"Failed to send message";b({status:"error",message:he})}finally{if(W&&(clearInterval(W),W=null),R)try{R.releaseLock()}catch{}}},[t,e,o,s,n,i,r,a,l,d,V,Z,C,x,b,$,m,h,T,D])}}import{useState as Mt}from"react";var Hn={sandbox:{id:"sandbox",apiKey:"sandbox",name:"Sandbox",description:"Code execution",type:"server"},webSearch:{id:"webSearch",apiKey:"web_search",name:"Web Search",description:"Search the web",type:"server"},imageGeneration:{id:"imageGeneration",apiKey:"image_generation",name:"Image Generation",description:"Generate images",type:"server"},chart:{id:"chart",apiKey:"chart",name:"Chart",description:"Create charts",type:"server"},fileSystem:{id:"fileSystem",apiKey:"file_system",name:"FileSystem",description:"Local file operations",type:"client"}},Vn=new Map(Object.values(Hn).map(e=>[e.apiKey,e.name]));function Kn(){return Object.values(Hn)}function qn(e,t,o,s,n){let[i,r]=Mt(e),[a,l]=Mt(t),[d,C]=Mt(o),[x,b]=Mt(s),[$,m]=Mt(n);return{sandbox:i,setSandbox:r,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:C,chart:x,setChart:b,fileSystem:$,setFileSystem:m,capabilityLabelMap:Vn}}import{useEffect as Er,useState as _r}from"react";function zn(e,t){let[o,s]=_r(null);return Er(()=>{let n=!1;async function i(){if(!e||!t){s(null);return}try{let a=await new B().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return i(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Go}from"react";function Yn(e,t,o){let[s,n]=Go(e),[i,r]=Go(t),[a,l]=Go(o);return{currentModel:s,setCurrentModel:n,currentAgentId:i,setCurrentAgentId:r,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Dr,useInput as Or}from"ink";import{useCallback as nt,useRef as Rr,useState as De}from"react";import{spawn as Lr}from"child_process";function Xn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let i=Lr(s,n,{stdio:"ignore",detached:!0});i.once("error",r=>{o(r)}),i.once("spawn",()=>{i.unref(),t()})})}var Zn=[{name:"help",aliases:["h","?"],description:"Show available commands"},{name:"clear",aliases:["cls","new"],description:"Start a new chat"},{name:"model",aliases:["m"],description:"Show/switch model",hasArgs:!0},{name:"agent",aliases:["a"],description:"Show/switch agent",hasArgs:!0},{name:"skills",aliases:["sk"],description:"List skills",hasArgs:!0},{name:"schedules",aliases:["sch"],description:"List schedules",hasArgs:!0},{name:"connectors",aliases:["conn"],description:"Select connectors"},{name:"capabilities",aliases:["cap"],description:"Select capabilities"},{name:"chats",aliases:["c"],description:"Switch to another chat"},{name:"workspace",aliases:["ws"],description:"List/switch workspace",hasArgs:!0},{name:"budget",aliases:["bg"],description:"View/set workspace budget",hasArgs:!0},{name:"usage",aliases:["u"],description:"View current month usage"},{name:"status",aliases:["s"],description:"Show session status"},{name:"profile",aliases:["p"],description:"Manage profiles",hasArgs:!0},{name:"open-in-browser",aliases:[],description:"Open current chat in browser"},{name:"share",aliases:[],description:"Get share link for current chat"},{name:"delete",aliases:["del"],description:"Delete current chat"},{name:"quit",aliases:["exit","q"],description:"Exit chat"}];function Qn(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Zn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Zn}function es(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),s=o[0]?.toLowerCase(),n=o.slice(1).join(" ");switch(s){case"help":case"h":case"?":return{type:"help"};case"clear":case"cls":case"new":return{type:"clear"};case"model":case"m":return{type:"model",value:n||void 0};case"agent":case"a":return{type:"agent",value:n||void 0};case"skills":case"sk":return{type:"skills",value:n||void 0};case"schedules":case"sch":return{type:"schedules",value:n||void 0};case"connectors":case"conn":return{type:"connectors"};case"capabilities":case"cap":return{type:"capabilities"};case"chats":case"c":return{type:"chats"};case"workspace":case"ws":return{type:"workspace",value:n||void 0};case"budget":case"bg":return{type:"budget",value:n||void 0};case"usage":case"u":return{type:"usage"};case"status":case"s":return{type:"status"};case"profile":case"p":return{type:"profile",value:n||void 0};case"open-in-browser":return{type:"open-in-browser"};case"share":return{type:"share"};case"delete":case"del":return{type:"delete"};case"quit":case"exit":case"q":return{type:"quit"};default:return{type:"unknown",input:t}}}var ts=`Available commands:
|
|
122
122
|
/help, /h, /? Show this help message
|
|
123
123
|
/clear, /cls, /new Start a new chat
|
|
124
124
|
/model [name], /m Show current model or switch to [name]
|
|
@@ -142,96 +142,96 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
|
|
|
142
142
|
|
|
143
143
|
Keyboard shortcuts:
|
|
144
144
|
Ctrl+O Toggle full output mode
|
|
145
|
-
Ctrl+C Exit`;function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:
|
|
146
|
-
Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return
|
|
145
|
+
Ctrl+C Exit`;function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:i,currentModel:r,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:C,setCurrentAgentDetails:x,activeConnectorIds:b,setActiveConnectorIds:$,sandbox:m,setSandbox:h,webSearch:T,setWebSearch:D,imageGeneration:V,setImageGeneration:Z,chart:ae,setChart:Y,fileSystem:Se,setFileSystem:j,availableModels:P,availableAgents:E,availableConnectors:R,messages:W,hasPersistedChat:_,setHasPersistedChat:he,setMessages:L,addSystemMessage:p,startNewChat:ie,sendMessage:ke,setFullOutput:q,credentials:A,setCredentials:te,setState:ee,defaultCapabilities:me,capabilityLabelMap:ce,hasUploadingFiles:M=!1}){let{exit:Q}=Dr(),[z,fe]=De([]),[Te,F]=De(0),[se,O]=De(!1),[f,w]=De(null),[v,oe]=De([]),[U,Ce]=De(0),[rt,it]=De(new Set),[Re,at]=De(new Set),[To,Xt]=De([]),[We,wt]=De([]),[Ye,Zt]=De([]),[lt,vo]=De([]),[Ve,Xe]=De(null),[Qt,kt]=De(""),mt=Rr(!1),[ct,xt]=De(!1),bt=nt(async()=>{if(!A)return[];let I=new B,y=[],c;do{let u=await I.listAvailableSkills(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.skills),c=u.nextKey}while(c);return wt(y),y},[A]),Ct=nt(async()=>{if(!A)return[];let I=new B,y=[],c;do{let u=await I.getSchedules(A.accessToken,A.workspaceId,{limit:100,nextKey:c});y.push(...u.schedules),c=u.nextKey}while(c);return Zt(y),y},[A]),_e=nt(async I=>{if(I==="model"){if(P.length===0){p("No models available.");return}let y=P.map(u=>({id:u.id,name:u.name,description:u.description}));oe(y);let c=r?y.findIndex(u=>u.id===r):-1;Ce(c>=0?c:0),w("model")}else if(I==="agent"){if(E.length===0){p("No agents available.");return}let y=E.map(u=>({id:u.id,name:u.name,description:u.description}));oe(y);let c=l?y.findIndex(u=>u.id===l):-1;Ce(c>=0?c:0),w("agent")}else if(I==="skills"){let y=We;if(y.length===0)try{y=await bt()}catch{p("Failed to load skills.");return}if(y.length===0){p("No skills available.");return}let c=y.map(u=>({id:u.id,name:u.name,description:u.description}));oe(c),Ce(0),w("skills")}else if(I==="schedules"){let y=Ye;if(y.length===0)try{y=await Ct()}catch{p("Failed to load schedules.");return}if(y.length===0){p("No schedules found.");return}let c=y.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));oe(c),Ce(0),w("schedules")}else if(I==="connectors"){if(R.length===0){p("No connectors available.");return}let y=R.map(c=>({id:c.id,name:c.name}));oe(y),Ce(0),it(new Set(b||[])),w("connectors")}else if(I==="capabilities"){let y=Kn().map(u=>({id:u.id,name:u.name,description:u.description}));oe(y),Ce(0);let c=new Set;m&&c.add("sandbox"),T&&c.add("webSearch"),V&&c.add("imageGeneration"),ae&&c.add("chart"),Se&&c.add("fileSystem"),at(c),w("capabilities")}else if(I==="chats"){if(!A){p("Not authenticated.");return}try{let y=new B,{chats:c}=await y.getChats(A.accessToken,A.workspaceId,20);if(c.length===0){p("No chats available.");return}Xt(c);let u=c.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));oe(u);let g=u.findIndex(S=>S.id===o);Ce(g>=0?g:0),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let y=H.getProfileNames(),c=H.getCurrentProfileName(),u=y.map(S=>({id:S,name:S,description:S===c?"(current)":void 0}));oe(u);let g=u.findIndex(S=>S.id===c);Ce(g>=0?g:0),w("profile")}O(!1),fe([])},[P,E,We,Ye,R,b,r,l,bt,Ct,m,T,V,ae,Se,A,o,p]),ye=nt(I=>{let y=ne.getAll(I);a(y.model?.default),d(void 0),x(null);let c=y.connectors?.defaults;$(c&&c.length>0?c:void 0);let u=y.capabilities;h(u?.sandbox??me.sandbox),D(u?.webSearch??me.webSearch),Z(u?.imageGeneration??me.imageGeneration),Y(u?.chart??me.chart);let g=y.localTools;j(g?.fileSystem??me.fileSystem)},[a,d,x,$,h,D,Z,Y,j,me]),Ze=nt(async()=>{try{let I=await pe();te({accessToken:I.accessToken,workspaceId:I.workspaceId}),ee({status:"ready"})}catch(I){if(te(null),I instanceof Qe){if(I.code==="not-logged-in"){ee({status:"not-logged-in"});return}if(I.code==="no-workspace"){ee({status:"no-workspace"});return}}let y=I instanceof Error?I.message:"Failed to authenticate";ee({status:"error",message:y})}},[te,ee]),$t=nt(async I=>{switch(I.type){case"help":return p(ts),!0;case"clear":return ie("Started a new chat."),!0;case"model":{if(I.value){let y=I.value.toLowerCase(),c=P.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id);else{let u=P.map(g=>g.name).join(", ");p(`Model "${I.value}" not found.
|
|
146
|
+
Available: ${u||"none"}`)}}else{let y=P.find(c=>c.id===r)?.name||r;p(r?`Current model: ${y}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return E.length===0?(p("No agents available."),!0):(_e("agent"),!0);let y=I.value.toLowerCase(),c=E.find(u=>u.id.toLowerCase()===y||u.name.toLowerCase().includes(y));if(c)c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=E.map(g=>g.name).join(", ");p(`Agent "${I.value}" not found.
|
|
147
147
|
Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return _e("skills"),!0;let y=I.value.toLowerCase();return(We.length?Promise.resolve(We):bt().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));p(g?`Skill: ${g.name}
|
|
148
148
|
${g.description}
|
|
149
149
|
Provider: ${g.provider}
|
|
150
150
|
Author: ${g.author.name}
|
|
151
|
-
ID: ${g.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return _e("schedules"),!0;let y=I.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));if(g){let S=
|
|
151
|
+
ID: ${g.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return _e("schedules"),!0;let y=I.value.toLowerCase();return(Ye.length?Promise.resolve(Ye):Ct().catch(()=>[])).then(u=>{let g=u.find(S=>S.id.toLowerCase()===y||S.name.toLowerCase().includes(y));if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
|
|
152
152
|
Agent: ${g.agent.name}
|
|
153
153
|
Status: ${g.isActive?"Active":"Paused"}
|
|
154
154
|
Repeat: ${S(g.config)}
|
|
155
155
|
Next Run: ${k}
|
|
156
|
-
ID: ${g.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(l){let c=
|
|
156
|
+
ID: ${g.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(l){let c=C?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(g=>` - ${g.name}`).join(`
|
|
157
157
|
`);p(`Agent connectors:
|
|
158
|
-
${u}`)}return!0}let y=R.filter(c=>
|
|
158
|
+
${u}`)}return!0}let y=R.filter(c=>b?.includes(c.id));if(y.length===0)p("No active connectors.");else{let c=y.map(u=>` - ${u.name}`).join(`
|
|
159
159
|
`);p(`Active connectors:
|
|
160
|
-
${c}`)}return!0}case"capabilities":{if(l){let u=(
|
|
160
|
+
${c}`)}return!0}case"capabilities":{if(l){let u=(C?.capabilities||[]).map(g=>ce.get(g)??g);return p(u.length>0?`Agent capabilities:
|
|
161
161
|
${u.map(g=>` - ${g}`).join(`
|
|
162
162
|
`)}`:"No agent capabilities."),!0}let y=[];return m&&y.push("Sandbox"),T&&y.push("Web Search"),V&&y.push("Image Generation"),ae&&y.push("Chart"),Se&&y.push("FileSystem"),p(y.length>0?`Active capabilities:
|
|
163
163
|
${y.map(c=>` - ${c}`).join(`
|
|
164
164
|
`)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!I.value){try{let{workspaces:u}=await y.getWorkspaces(A.accessToken);if(u.length===0)p("No workspaces found.");else{let g=u.map(S=>` ${S.id===A.workspaceId?"* ":" "}${S.name}
|
|
165
165
|
ID: ${S.id}`);p(`Workspaces:
|
|
166
166
|
${g.join(`
|
|
167
|
-
`)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=I.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),g=u.find(k=>k.id===c);if(!g)return p(`Workspace not found: ${c}`),!0;let{TokenStorage:S}=await import("./token-storage-
|
|
168
|
-
`))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=H.getCurrentProfileName(),c=r?P.find(k=>k.id===r)?.name||r:null,u=l?
|
|
167
|
+
`)}`)}}catch(u){p(`Failed to load workspaces: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}let c=I.value;try{let{workspaces:u}=await y.getWorkspaces(A.accessToken),g=u.find(k=>k.id===c);if(!g)return p(`Workspace not found: ${c}`),!0;let{TokenStorage:S}=await import("./token-storage-HJFI4DTN.js");await S.saveWorkspaceId(c),p(`Switched to workspace: ${g.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!A)return p("Not authenticated."),!0;let y=new B;if(!I.value){try{let g=await y.getBudget(A.accessToken,A.workspaceId);g.budget===null?p("No budget set for this workspace."):p(`Current budget: $${g.budget}`)}catch(g){p(`Failed to get budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let c=I.value.toLowerCase();if(c==="clear"||c==="null"){try{await y.updateBudget(A.accessToken,A.workspaceId,null),p("Budget cleared.")}catch(g){p(`Failed to clear budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await y.updateBudget(A.accessToken,A.workspaceId,c),p(`Budget set to: $${c}`)}catch(g){p(`Failed to set budget: ${g instanceof Error?g.message:"Unknown error"}`)}return!0}case"usage":{if(!A)return p("Not authenticated."),!0;let y=new B;try{let c=[],u,g=0,S=10;do{let ve=await y.getMonthlyUsages(A.accessToken,A.workspaceId,{nextKey:u,limit:20});if(c.push(...ve.monthlyUsages),u=ve.nextKey,g++,g>=S){p(`Warning: Showing first ${c.length} entries (pagination limit reached)`);break}}while(u);if(c.length===0)return p("No usage data found for this workspace."),!0;let k=0,N=0;for(let ve of c)k+=parseFloat(ve.totalCost),N+=ve.operationCount;let J=[...c].toSorted((ve,ut)=>parseFloat(ut.totalCost)-parseFloat(ve.totalCost)),G=10,ue=J.slice(0,G),Ue=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${N.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ue.length} Users by Cost:`,...ue.map(ve=>` ${ve.user.name}: $${parseFloat(ve.totalCost).toFixed(2)} (${ve.operationCount.toLocaleString()} ops)`)];c.length>G&&(Ue.push("",`... and ${c.length-G} more users`),Ue.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Ue.join(`
|
|
168
|
+
`))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let y=H.getCurrentProfileName(),c=r?P.find(k=>k.id===r)?.name||r:null,u=l?E.find(k=>k.id===l)?.name||l:null,g=b?R.filter(k=>b.includes(k.id)).map(k=>k.name):[],S=[];return m&&S.push("Sandbox"),T&&S.push("Web Search"),V&&S.push("Image Gen"),ae&&S.push("Chart"),Se&&S.push("FileSystem"),$e.getEmail().then(k=>{let N=[`Profile: ${y}${y!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",A?.workspaceId?`Workspace: ${A.workspaceId}`:null,_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(N.join(`
|
|
169
169
|
`))}).catch(()=>{let k=[`Profile: ${y}`,"Not logged in",_?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${g.length>0?g.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(k.join(`
|
|
170
|
-
`))}),!0}case"profile":{let y=I.value?I.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],g=y[2],S=H.getProfileNames(),k=H.getCurrentProfileName(),
|
|
171
|
-
`)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let G=J(u,!0),ue=ne.getAll(G),Ue=await $e.getAll(G),ve=!!Ue?.accessToken,ut=ue.capabilities?Object.entries(ue.capabilities).filter(([,
|
|
170
|
+
`))}),!0}case"profile":{let y=I.value?I.value.split(/\s+/).filter(Boolean):[];if(y.length===0)return _e("profile"),!0;let c=y[0]?.toLowerCase()||"list",u=y[1],g=y[2],S=H.getProfileNames(),k=H.getCurrentProfileName(),N=H.getOverrideProfile(),J=(G,ue=!1)=>{if(G)return G;if(ue&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let G=[`Profiles (${S.length}):`];for(let ue of S){let Ue=ue===k?" (current)":"";G.push(` ${ue}${Ue}`)}return p(G.join(`
|
|
171
|
+
`)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let G=J(u,!0),ue=ne.getAll(G),Ue=await $e.getAll(G),ve=!!Ue?.accessToken,ut=ue.capabilities?Object.entries(ue.capabilities).filter(([,Io])=>Io).map(([Io])=>Io):[],Hs=ue.connectors?.defaults&&ue.connectors.defaults.length>0?ue.connectors.defaults.join(", "):"unset",Vs=[`Profile: ${G}${G===k?" (current)":""}`,`API URL: ${ue.apiUrl??"default"}`,`Hub URL: ${ue.hubUrl??"default"}`,`Model: ${ue.model?.default??"unset"}`,`Connectors: ${Hs}`,`Capabilities: ${ut.length>0?ut.join(", "):"none"}`,ve?`Logged in as: ${Ue?.email??"unknown"}`:"Not logged in",ve&&Ue?.workspaceId?`Workspace ID: ${Ue.workspaceId}`:null].filter(Boolean);return p(Vs.join(`
|
|
172
172
|
`)),!0}if(c==="create"){let G=u||H.DEFAULT_PROFILE;return H.createProfile(G),p(`Profile created: ${G}`),!0}if(c==="use"||c==="switch"){let G=J(u,!0);return H.setOverrideProfile(G),H.setCurrentProfile(G),ye(G),await Ze(),ie(`Switched to profile: ${G} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let G=J(u,!0),ue=G===k,Ue=H.deleteProfile(G),ve=`Profile deleted: ${G}`;if(ue)H.setOverrideProfile(Ue.currentProfile),ye(Ue.currentProfile),await Ze(),ie(`${ve}
|
|
173
|
-
Switched to profile: ${Ue.currentProfile} (new chat)`);else if(
|
|
174
|
-
Switched to profile: ${ut} (new chat)`)}else p(ve);return!0}if(c==="rename"||c==="move"||c==="mv"){let G=J(u,!0);if(!g)throw new Error("New profile name is required.");let ue=H.renameProfile(G,g);return p(`Profile renamed: ${G} -> ${g}`),
|
|
173
|
+
Switched to profile: ${Ue.currentProfile} (new chat)`);else if(N===G){let ut=H.getCurrentProfileName();H.setOverrideProfile(ut),ye(ut),await Ze(),ie(`${ve}
|
|
174
|
+
Switched to profile: ${ut} (new chat)`)}else p(ve);return!0}if(c==="rename"||c==="move"||c==="mv"){let G=J(u,!0);if(!g)throw new Error("New profile name is required.");let ue=H.renameProfile(G,g);return p(`Profile renamed: ${G} -> ${g}`),N===G?(H.setOverrideProfile(g),ye(g)):ue.currentProfile===g&&ye(g),!0}if(c==="clone"||c==="copy"){let G=J(u,!0);if(!g)throw new Error("Target profile name is required.");let ue=ne.getAll(G);return H.createProfile(g),ne.setAll(ue,g),await $e.clear(g),p(`Profile cloned: ${G} -> ${g}`),!0}p(`Unknown profile command: ${c}`)}catch(G){let ue=G instanceof Error?G.message:"Unknown error";p(`Profile error: ${ue}`)}return!0}case"open-in-browser":{let y=Me().hubUrl.replace(/\/$/,""),u=_||W.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",g=l?`?agentId=${encodeURIComponent(l)}`:"",S=`${y}${u}${g}`;try{await Xn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
|
|
175
175
|
URL: ${S}`)}return!0}case"share":{if(!A)return p("Not authenticated."),!0;if(!(_||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new B().createChatShare(A.accessToken,A.workspaceId,o,"public"),S=`${Me().hubUrl.replace(/\/$/,"")}/share/${u.id}`;p(`Share link: ${S}`)}catch(c){p(`Failed to create share link: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"delete":return A?_?(xt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Q(),!0;case"unknown":return p(`Unknown command: ${I.input}
|
|
176
|
-
Type /help for available commands.`),!0;default:return!1}},[p,P,
|
|
176
|
+
Type /help for available commands.`),!0;default:return!1}},[p,P,E,R,We,Ye,r,l,b,m,T,V,ae,Se,o,n,Q,_e,ie,ce,C,_,W,bt,Ct,L,a,d,x,a,ye,Ze]),eo=nt(I=>{if(mt.current=!1,ct){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&xt(!1));return}if(t(I),kt(I),Ve!==null&&Xe(null),f&&(w(null),oe([])),I.startsWith("/")&&!I.includes(" ")){let y=Qn(I);fe(y),F(0),O(y.length>0)}else O(!1),fe([])},[f,Ve,ct,t]),Lt=nt((I,y=!1)=>{if(I>=0&&I<z.length){let c=z[I];O(!1),fe([]),c.name==="model"?(t("/model "),_e("model")):c.name==="agent"?(t("/agent "),_e("agent")):c.name==="skills"?(t("/skills "),_e("skills")):c.name==="schedules"?(t("/schedules "),_e("schedules")):c.name==="connectors"?(t("/connectors "),_e("connectors")):c.name==="capabilities"?(t("/capabilities "),_e("capabilities")):c.name==="chats"?(t("/chats "),_e("chats")):c.name==="profile"?(t("/profile "),_e("profile")):y?(t(""),$t({type:c.name})):t(`/${c.name}`)}},[z,_e,t,$t]),to=nt(async I=>{mt.current=!1;let y=I.trim();if(!y||ct)return;if(f==="model"&&v.length>0){let u=v[U];u&&(l?ie(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),x(null)),w(null),oe([]),t("");return}if(f==="agent"&&v.length>0){let u=v[U];u&&(u.id!==l?ie(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),oe([]),t("");return}if(f==="skills"&&v.length>0){let u=v[U];if(u){let g=We.find(S=>S.id===u.id);g&&p(`Skill: ${g.name}
|
|
177
177
|
${g.description}
|
|
178
178
|
Provider: ${g.provider}
|
|
179
179
|
Author: ${g.author.name}
|
|
180
|
-
ID: ${g.id}`)}w(null),oe([]),t("");return}if(f==="schedules"&&v.length>0){let u=v[U];if(u){let g=Ye.find(S=>S.id===u.id);if(g){let S=
|
|
180
|
+
ID: ${g.id}`)}w(null),oe([]),t("");return}if(f==="schedules"&&v.length>0){let u=v[U];if(u){let g=Ye.find(S=>S.id===u.id);if(g){let S=N=>{if(N.type==="no-repeat")return"No repeat";let{interval:J}=N;switch(J.unit){case"minutes":return`Every ${J.every} min`;case"hours":return`Every ${J.every} hr`;case"days":return`Every ${J.every} day at ${String(J.time.hour).padStart(2,"0")}:${String(J.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${J.every} week`;case"months":return`Every ${J.every} month`;default:return"Unknown"}},k=g.nextRunAt?new Date(g.nextRunAt).toLocaleString():"-";p(`Schedule: ${g.name}
|
|
181
181
|
Agent: ${g.agent.name}
|
|
182
182
|
Status: ${g.isActive?"Active":"Paused"}
|
|
183
183
|
Repeat: ${S(g.config)}
|
|
184
184
|
Next Run: ${k}
|
|
185
|
-
ID: ${g.id}`)}}w(null),oe([]),t("");return}if(f==="connectors"){let u=Array.from(rt);$(u.length>0?u:void 0),ne.setDefaultConnectorIds(u);let g=R.filter(S=>rt.has(S.id)).map(S=>S.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),oe([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),g=Re.has("webSearch"),S=Re.has("imageGeneration"),k=Re.has("chart"),
|
|
185
|
+
ID: ${g.id}`)}}w(null),oe([]),t("");return}if(f==="connectors"){let u=Array.from(rt);$(u.length>0?u:void 0),ne.setDefaultConnectorIds(u);let g=R.filter(S=>rt.has(S.id)).map(S=>S.name);p(g.length>0?`Active connectors: ${g.join(", ")}`:"All connectors disabled."),w(null),oe([]),t("");return}if(f==="capabilities"){let u=Re.has("sandbox"),g=Re.has("webSearch"),S=Re.has("imageGeneration"),k=Re.has("chart"),N=Re.has("fileSystem");h(u),D(g),Z(S),Y(k),j(N),ne.setCapabilities({sandbox:u,webSearch:g,imageGeneration:S,chart:k}),ne.setLocalTools({fileSystem:N});let J=[];u&&J.push("Sandbox"),g&&J.push("Web Search"),S&&J.push("Image Generation"),k&&J.push("Chart"),N&&J.push("FileSystem"),p(J.length>0?`Active capabilities: ${J.join(", ")}`:"All capabilities disabled."),w(null),oe([]),t("");return}if(f==="profile"&&v.length>0){let u=v[U];if(u){let g=H.getCurrentProfileName();u.id!==g?(H.setOverrideProfile(u.id),H.setCurrentProfile(u.id),ye(u.id),Ze(),ie(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),oe([]),t("");return}if(se&&z.length>0){Lt(Te,!0);return}Xe(null),kt(""),vo(u=>u.length>0&&u[u.length-1]===y?u:[...u,y]);let c=es(y);if(c){await $t(c),t(""),O(!1);return}if(M){p("Please wait for file uploads to complete.");return}t(""),O(!1),ke(y)},[ke,$t,se,z,Te,Lt,f,v,U,rt,Re,R,We,Ye,p,t,l,ie,a,d,x,$,h,D,Z,Y,j,M,ye,Ze,ct,A,_,o]);return Or((I,y)=>{if(y.ctrl&&I==="c"){if(e.length>0){eo(""),mt.current=!0,p("Press Ctrl+C again to exit.");return}if(mt.current){Q();return}Q();return}if(y.ctrl&&I==="o"){q(c=>!c);return}if(ct){if(y.escape||y.return||I==="n"||I==="N"){xt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){xt(!1),t(""),A&&_&&new B().deleteChat(A.accessToken,A.workspaceId,o).then(()=>{ie("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&v.length>0){if(y.upArrow){Ce(c=>c<=0?v.length-1:c-1);return}if(y.downArrow){Ce(c=>c>=v.length-1?0:c+1);return}if(y.escape){w(null),oe([]),t("");return}if(y.return){if(f==="model"){let c=v[U];c&&(l?ie(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),x(null),ne.setDefaultModel(c.id))}else if(f==="agent"){let c=v[U];c&&(c.id!==l?ie(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0))}else if(f==="skills"){let c=v[U];if(c){let u=We.find(g=>g.id===c.id);u&&p(`Skill: ${u.name}
|
|
186
186
|
${u.description}
|
|
187
187
|
Provider: ${u.provider}
|
|
188
188
|
Author: ${u.author.name}
|
|
189
|
-
ID: ${u.id}`)}}else if(f==="schedules"){let c=v[U];if(c){let u=Ye.find(g=>g.id===c.id);if(u){let g=k=>{if(k.type==="no-repeat")return"No repeat";let{interval:
|
|
189
|
+
ID: ${u.id}`)}}else if(f==="schedules"){let c=v[U];if(c){let u=Ye.find(g=>g.id===c.id);if(u){let g=k=>{if(k.type==="no-repeat")return"No repeat";let{interval:N}=k;switch(N.unit){case"minutes":return`Every ${N.every} min`;case"hours":return`Every ${N.every} hr`;case"days":return`Every ${N.every} day at ${String(N.time.hour).padStart(2,"0")}:${String(N.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${N.every} week`;case"months":return`Every ${N.every} month`;default:return"Unknown"}},S=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
|
|
190
190
|
Agent: ${u.agent.name}
|
|
191
191
|
Status: ${u.isActive?"Active":"Paused"}
|
|
192
192
|
Repeat: ${g(u.config)}
|
|
193
193
|
Next Run: ${S}
|
|
194
|
-
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);$(c.length>0?c:void 0),ne.setDefaultConnectorIds(c);let u=R.filter(g=>rt.has(g.id)).map(g=>g.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Re.has("sandbox"),u=Re.has("webSearch"),g=Re.has("imageGeneration"),S=Re.has("chart"),k=Re.has("fileSystem");h(c),
|
|
194
|
+
ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(rt);$(c.length>0?c:void 0),ne.setDefaultConnectorIds(c);let u=R.filter(g=>rt.has(g.id)).map(g=>g.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=Re.has("sandbox"),u=Re.has("webSearch"),g=Re.has("imageGeneration"),S=Re.has("chart"),k=Re.has("fileSystem");h(c),D(u),Z(g),Y(S),j(k),ne.setCapabilities({sandbox:c,webSearch:u,imageGeneration:g,chart:S}),ne.setLocalTools({fileSystem:k});let N=[];c&&N.push("Sandbox"),u&&N.push("Web Search"),g&&N.push("Image Generation"),S&&N.push("Chart"),k&&N.push("FileSystem"),p(N.length>0?`Active capabilities: ${N.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=v[U];if(c){let u=To.find(g=>g.id===c.id);u&&A&&(s(u.id),i(u.title||void 0),he(!0),new B().getMessages(A.accessToken,A.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(N=>N.role==="user"||N.role==="assistant").map(N=>({role:N.role,content:ht(N.parts,!1),parts:N.parts})).filter(N=>N.content).toReversed();L(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=v[U];if(c){let u=H.getCurrentProfileName();c.id!==u?(H.setOverrideProfile(c.id),H.setCurrentProfile(c.id),ye(c.id),Ze(),ie(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),oe([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let c=v[U];c&&(f==="connectors"?it:at)(g=>{let S=new Set(g);return S.has(c.id)?S.delete(c.id):S.add(c.id),S});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set(v.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?it:at)(new Set);return}return}if(se&&z.length>0){if(y.upArrow){F(c=>c<=0?z.length-1:c-1);return}if(y.downArrow){F(c=>c>=z.length-1?0:c+1);return}if(y.escape){O(!1),fe([]);return}if(y.tab){Lt(Te);return}}if(y.upArrow){if(e.includes(`
|
|
195
195
|
`)||lt.length===0)return;if(Ve===null){kt(e);let u=lt.length-1;Xe(u),t(lt[u]);return}let c=Math.max(0,Ve-1);Xe(c),t(lt[c]);return}if(y.downArrow){if(e.includes(`
|
|
196
|
-
`)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:z,suggestionIndex:Te,showSuggestions:se,argMode:f,argItems:v,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as Ur,useState as jr}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=jr([]),a=Ur(0),l=Jt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let T of o)if(T.models.some(V=>V.id===h))return T.id;return o[0]?.id}},[o]),d=Jt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let T=t?l(t):o[0]?.id;if(!T){n?.(h.filename,"No model provider available");return}let
|
|
196
|
+
`)||Ve===null)return;if(Ve>=lt.length-1){Xe(null),t(Qt);return}let c=Ve+1;Xe(c),t(lt[c])}}),{suggestions:z,suggestionIndex:Te,showSuggestions:se,argMode:f,argItems:v,argIndex:U,selectedConnectorIds:rt,selectedCapabilities:Re,deleteConfirmMode:ct,handleInputChange:eo,handleSubmit:to}}import{useCallback as Jt,useRef as Ur,useState as jr}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[i,r]=jr([]),a=Ur(0),l=Jt(h=>{if(!(!Array.isArray(o)||o.length===0)){for(let T of o)if(T.models.some(V=>V.id===h))return T.id;return o[0]?.id}},[o]),d=Jt(async h=>{if(!e){n?.(h.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(h.filename,"Model providers not loaded yet. Please wait and try again.");return}let T=t?l(t):o[0]?.id;if(!T){n?.(h.filename,"No model provider available");return}let D=`file-${++a.current}`;r(V=>[...V,{id:D,filename:h.filename,mimeType:h.mimeType,status:"uploading"}]);try{let Z=await new B().uploadFile(e.accessToken,e.workspaceId,h,T);r(ae=>ae.map(Y=>Y.id===D?{...Y,status:"uploaded",fileId:Z.id}:Y)),s?.(h.filename)}catch(V){let Z=V instanceof Error?V.message:"Upload failed";r(ae=>ae.map(Y=>Y.id===D?{...Y,status:"error",error:Z}:Y)),n?.(h.filename,Z)}},[e,t,l,o,s,n]),C=Jt(h=>{r(T=>T.filter(D=>D.id!==h))},[]),x=Jt(()=>{r([])},[]),b=Jt(()=>i.filter(h=>h.status==="uploaded"&&h.fileId).map(h=>h.fileId),[i]),$=i.some(h=>h.status==="uploading"),m=i.length>0;return{pendingFiles:i,addFile:d,removeFile:C,clearFiles:x,getUploadedFileIds:b,hasUploadingFiles:$,hasFiles:m}}import{jsx as X,jsxs as de}from"react/jsx-runtime";var Fr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Jo,Jo,Mo,Mo,gt,gt,gt,gt],rs=Fr.map((e,t)=>`${Wr[t]??gt}${e}${re}`).join(`
|
|
197
197
|
`),Mr=`${gt}EntryDesk${re}`,Jr=500;function Gr(e){let t="",o=0;for(;o<e.length;){if(e.charCodeAt(o)===27&&e[o+1]==="["){for(o+=2;o<e.length;){let s=e.charCodeAt(o);if(s>=64&&s<=126){o+=1;break}o+=1}continue}t+=e[o],o+=1}return t}function Hr(e){let t=Gr(e);return Math.max(...t.split(`
|
|
198
|
-
`).map(o=>o.length))}function Vr(e){let t=Hr(rs);return e>=t?rs:Mr}function is({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:
|
|
198
|
+
`).map(o=>o.length))}function Vr(e){let t=Hr(rs);return e>=t?rs:Mr}function is({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:i,enableSandbox:r=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:C=!0}){let x=process.stdout.columns??80,b=Vr(x),$=ss(null),m=jn(s,n),{state:h,setState:T,messages:D,setMessages:V,input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,hasPersistedChat:E,setHasPersistedChat:R,credentials:W,setCredentials:_,currentResponse:he,setCurrentResponse:L,fullOutput:p,setFullOutput:ie,addSystemMessage:ke,startNewChat:q}=m,{credentials:A}=Fn(T);ho(()=>{A&&!W&&_(A)},[A,W,_]);let{availableConnectors:te,availableModels:ee,availableAgents:me,modelProviders:ce,loading:M}=Wn(W),{currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,activeConnectorIds:F,setActiveConnectorIds:se}=Yn(t,e,i),O=ss(!1);ho(()=>{if(!O.current){if(O.current=!0,!t&&!e){let k=ne.getDefaultModel();k&&z(k)}if(!i&&!e){let k=ne.getDefaultConnectorIds();k&&se(k.length>0?k:void 0)}}},[t,e,i,z,se]);let{currentAgentDetails:f}=zn(fe,W),{sandbox:w,setSandbox:v,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,capabilityLabelMap:Xt}=qn(r,a,l,d,C),{pendingFiles:We,addFile:wt,removeFile:Ye,clearFiles:Zt,getUploadedFileIds:lt,hasUploadingFiles:vo,hasFiles:Ve}=ns({credentials:W,currentModel:Q,modelProviders:ce,onUploadSuccess:k=>{ke(`\u2713 Attached: ${k}`)},onUploadError:(k,N)=>{ke(`\u2717 Failed to upload ${k}: ${N}`)}}),{sendMessage:Xe}=Gn({chatId:Y,credentials:W,currentAgentId:fe,currentModel:Q,activeConnectorIds:F,sandbox:w,webSearch:oe,imageGeneration:Ce,chart:it,localTools:at,fullOutput:p,setMessages:V,setState:T,setCurrentResponse:L,setCredentials:_,setHasPersistedChat:R,getFileIds:lt,clearFiles:Zt}),Qt=Ko(k=>{q(k),L("")},[q]),[kt,mt]=Br(!1),ct=Ko(async k=>{let N=k.text.trim(),J=po(N);if(/^https?:\/\//.test(J))return;if(await Dn(N)&&Ln(J)){let ue=await On(N);ue&&(k.preventDefault(),await wt(ue))}},[wt]),xt=Ko(async()=>{if(!(kt||h.status!=="ready")){if(M||ce.length===0){ke("Please wait for resources to load before pasting images.");return}ke("Reading clipboard..."),mt(!0);try{let k=await _n();if(k){let N=`clipboard-${Date.now()}.png`;ke(`Uploading: ${N} (${Math.round(k.buffer.length/1024)}KB)`),await wt({buffer:k.buffer,filename:N,mimeType:k.mime})}else ke("No image found in clipboard. Copy an image first.")}catch(k){let N=k instanceof Error?k.message:"Failed to read clipboard";ke(`Clipboard error: ${N}`)}finally{mt(!1)}}},[wt,ke,kt,h.status,M,ce.length]),{suggestions:bt,suggestionIndex:Ct,showSuggestions:_e,argMode:ye,argItems:Ze,argIndex:$t,selectedConnectorIds:eo,selectedCapabilities:Lt,deleteConfirmMode:to,handleInputChange:I,handleSubmit:y}=os({input:Z,setInput:ae,chatId:Y,setChatId:Se,currentChatTitle:j,setCurrentChatTitle:P,currentModel:Q,setCurrentModel:z,currentAgentId:fe,setCurrentAgentId:Te,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:se,sandbox:w,setSandbox:v,webSearch:oe,setWebSearch:U,imageGeneration:Ce,setImageGeneration:rt,chart:it,setChart:Re,fileSystem:at,setFileSystem:To,availableModels:ee,availableAgents:me,availableConnectors:te,messages:D,hasPersistedChat:E,setHasPersistedChat:R,setMessages:V,addSystemMessage:ke,startNewChat:Qt,sendMessage:Xe,setFullOutput:ie,credentials:W,setCredentials:_,setState:T,defaultCapabilities:{sandbox:r,webSearch:a,imageGeneration:l,chart:d,fileSystem:C},capabilityLabelMap:Xt,hasUploadingFiles:vo});if(Ho((k,N)=>{(N.ctrl||N.meta)&&k==="v"&&xt()},{isActive:h.status==="ready"&&!ye}),Ho((k,N)=>{if(!N.escape)return;let J=Date.now(),G=$.current;$.current=J,!(!G||J-G>Jr)&&(ye||_e||($.current=null,Ve&&Zt(),Z.length>0&&I("")))},{isActive:h.status==="ready"}),Ho((k,N)=>{N.return&&(Qt("Started a new chat."),T({status:"ready"}))},{isActive:h.status==="error"}),ho(()=>{if(W&&!M&&h.status==="loading")if(!Q&&!fe){let k=ne.getDefaultModel(),N=k&&ee.some(G=>G.id===k),J=N?k:ee[0]?.id;J?(N||ne.setDefaultModel(J),z(J),T({status:"ready"})):me.length===0?T({status:"no-model"}):T({status:"ready"})}else T({status:"ready"})},[W,M,Q,fe,ee,me,h.status,z,T]),ho(()=>{o&&W&&h.status==="ready"&&Xe(o)},[W,o]),h.status==="loading")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),de(Pe,{children:[X(K,{color:"cyan",children:X(Vo,{type:"dots"})}),X(K,{children:" Initializing chat..."})]})]});if(h.status==="not-logged-in")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"Not logged in"}),X(K,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(h.status==="no-workspace")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"No workspace selected"}),X(K,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(h.status==="no-model")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),X(K,{color:"yellow",children:"No model or agent specified"}),s&&X(K,{dimColor:!0,children:"Could not determine the model used in this chat."}),X(K,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),X(K,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(h.status==="error")return de(Pe,{flexDirection:"column",children:[X(K,{children:b}),de(K,{color:"red",children:["Error: ",h.message]}),X(K,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=fe?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":F&&F.length>0?te.filter(k=>F.includes(k.id)).map(k=>k.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(fe)if(f?.capabilities)for(let k of f.capabilities)u.push(Xt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),oe&&u.push("Web"),Ce&&u.push("Image"),it&&u.push("Chart");at&&u.push("FileSystem");let g=H.getCurrentProfileName(),S=g!=="default";return de(Pe,{flexDirection:"column",children:[de(Pe,{marginBottom:1,flexDirection:"column",children:[X(K,{children:b}),de(Pe,{children:[X(K,{bold:!0,color:"cyan",children:j?`Continuing: ${j}`:"EntryDesk CLI"}),de(K,{dimColor:!0,children:[" v","1.7.6"]}),S&&de(K,{color:"magenta",children:[" [",g,"]"]}),X(K,{dimColor:!0,children:" (type /help for commands)"})]})]}),D.map((k,N)=>{let J=k.parts&&p?ht(k.parts,!0):k.content,G=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ue=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return de(Pe,{flexDirection:"column",marginBottom:1,children:[de(K,{bold:!0,color:G,children:[ue,":"]}),X(Wo,{text:J})]},N)}),he&&de(Pe,{flexDirection:"column",marginBottom:1,children:[X(K,{bold:!0,color:"blue",children:"Assistant:"}),X(Wo,{text:he})]}),h.status==="ready"&&X(gn,{suggestions:bt,activeIndex:Ct,visible:_e}),h.status==="ready"&&ye&&X(mn,{items:Ze,activeIndex:$t,pageSize:ye==="agent"||ye==="skills"||ye==="model"?5:10,selectedIds:ye==="connectors"?eo:ye==="capabilities"?Lt:void 0,multiSelect:ye==="connectors"||ye==="capabilities",visible:!0,title:ye==="model"?"Select model:":ye==="agent"?"Select agent:":ye==="skills"?"Select skill:":ye==="connectors"?"Select connectors:":ye==="capabilities"?"Select capabilities:":"Select chat:"}),h.status==="sending"&&!he?de(Pe,{children:[X(K,{color:"cyan",children:X(Vo,{type:"dots"})}),X(K,{children:" Thinking..."})]}):h.status==="ready"&&!ye?de(Pe,{flexDirection:"column",children:[to&&X(Pe,{marginBottom:1,children:X(K,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Ve&&!to&&de(Pe,{marginBottom:1,flexDirection:"row",gap:1,children:[X(K,{dimColor:!0,children:"Attachments:"}),We.map((k,N)=>de(K,{children:[k.status==="uploading"?de(K,{color:"yellow",children:[X(Vo,{type:"dots"})," ",k.filename]}):k.status==="error"?de(K,{color:"red",children:["\u2717 ",k.filename]}):de(K,{color:"green",children:["\u2713 ",k.filename]}),N<We.length-1&&X(K,{children:", "})]},k.id))]}),de(Pe,{children:[X(K,{color:"green",children:"> "}),X($n,{value:Z,onChange:I,onSubmit:y,onPaste:ct,leadingOffset:2,multiline:!0})]})]}):null,de(Pe,{marginTop:1,flexDirection:"column",children:[de(Pe,{gap:2,children:[de(K,{children:[X(K,{dimColor:!0,children:"Model: "}),X(K,{color:"magenta",children:fe?f?.model?.name||"loading...":ee.find(k=>k.id===Q)?.name||Q||"none"})]}),de(K,{children:[X(K,{dimColor:!0,children:"Connectors: "}),X(K,{color:"cyan",children:c})]}),de(K,{children:[X(K,{dimColor:!0,children:"Capabilities: "}),X(K,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),de(K,{dimColor:!0,children:["Esc Esc: Clear input & attachments | Ctrl+V: Paste image | Ctrl+O: Toggle full output ",p?"(ON)":"(OFF)"," | Ctrl+C: Exit"]})]})]})}import{jsx as Xr}from"react/jsx-runtime";async function qr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function zr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let i=n[s-1],r;if(!i.agentId){let{messages:a}=await e.getMessages(t,o,i.id,10);r=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:i,modelId:r}}var It="\x1B[2m",Oe="\x1B[0m",qo="\x1B[36m",us="\x1B[33m",wo="\x1B[32m",as="stream-json";function ls(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function ko(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
|
|
199
199
|
`)}function xo(e,t){if(t)return e;let o=e.split(`
|
|
200
200
|
`);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),i=o.length-10;return[...s,`${It}... (${i} lines omitted, use --full-output to see all) ...${Oe}`,...n].join(`
|
|
201
201
|
`)}function Yr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function cs(e,t){if(!e)return"(no result)";if(typeof e!="object")return xo(String(e),t);let o=e;if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${us}[stderr]${Oe} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),xo(n.join(`
|
|
202
202
|
`),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
|
|
203
|
-
`);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let te=await pe();t=te.accessToken,o=te.workspaceId}catch(te){xe(te)}let s=e.output===as;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${as}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=ne.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await qr());let a=new B;async function l(){if(!i)try{let{models:te}=await a.getModels(t,o),ee=te[0]?.id;if(!ee)return;ne.setDefaultModel(ee),i=ee}catch{}}let d,
|
|
203
|
+
`);return xo(n||JSON.stringify(e,null,2),t)}return xo(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let te=await pe();t=te.accessToken,o=te.workspaceId}catch(te){xe(te)}let s=e.output===as;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${as}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),i=ne.getDefaultModel(),r=e.message;!r&&!process.stdin.isTTY&&(r=await qr());let a=new B;async function l(){if(!i)try{let{models:te}=await a.getModels(t,o),ee=te[0]?.id;if(!ee)return;ne.setDefaultModel(ee),i=ee}catch{}}let d,C,x,b;if(e.continue){let te=await zr(a,t,o,e.continue);te||process.exit(1),d=te.chat.id,C=te.chat.title??void 0,x=te.chat.agentId??void 0,b=te.modelId;let ee=e.agentId||e.model||x||b||i;!ee&&!e.interactive&&(await l(),ee=e.agentId||e.model||x||b||i),!ee&&!e.interactive&&(n||console.log(`Continuing chat: ${te.chat.title||"Untitled"}`),console.error(`
|
|
204
204
|
Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${te.chat.title||"Untitled"}
|
|
205
|
-
`)}let $=e.agentId||x,m=e.model||
|
|
206
|
-
`);ce=F.pop()||"";for(let se of F){let
|
|
205
|
+
`)}let $=e.agentId||x,m=e.model||b||i||void 0;!$&&!m&&(await l(),m=e.model||b||i||void 0),ls(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),ls(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let h=ne.getCapabilities(),T=e.noSandbox?!1:e.sandbox?!0:h?.sandbox??!0,D=e.webSearch??h?.webSearch??!1,V=e.imageGen??h?.imageGeneration??!1,Z=e.chart??h?.chart??!1,ae=ne.getDefaultConnectorIds(),Y=e.connectors??ae??void 0,Se=ne.getLocalTools(),j=e.noFileSystem?!1:e.fileSystem?!0:Se?.fileSystem??!0;if(e.interactive){Kr(Xr(is,{agentId:$,model:m,message:e.message,chatId:d,chatTitle:C??void 0,connectorIds:Y,enableSandbox:T,enableWebSearch:D,enableImageGeneration:V,enableChart:Z,enableFileSystem:j}),{exitOnCtrlC:!1});return}let P=!e.continue&&!m&&!$;(!r||P)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let E=e.fullOutput??!1,R=d||yo(),W=j?no():void 0,_=j?so():void 0,he=[],L=yo(),p=(te,ee,me)=>{let ce={id:R};return te&&(ce.message={id:te.id,createdAt:new Date,role:"user",parts:[{type:"text",text:te.text}]}),$?ce.agentId=$:(m&&(ce.model=m),ce.connectorIds=Y??[],ce.enableSandbox=T,ce.enableWebSearch=D,ce.enableImageGeneration=V,ce.enableChart=Z),W&&(ce.clientTools=W),_&&(ce.clientToolSystemPrompt=_),ee&&ee.length>0&&(ce.clientToolResults=ee),me&&me.length>0&&(ce.previousMessages=me),ce},ie=async te=>{if(!te.body)throw new Error("No response body");let ee=te.body.getReader(),me=new TextDecoder,ce="",M=new Map,Q=[],z=[];for(;;){let{done:fe,value:Te}=await ee.read();if(fe)break;ce+=me.decode(Te,{stream:!0});let F=ce.split(`
|
|
206
|
+
`);ce=F.pop()||"";for(let se of F){let O=se.trimEnd();if(O==="data: [DONE]"){s&&ko("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&z.push(f),s){f.type==="text-delta"&&f.delta!==void 0?ko("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?ko("reasoning-delta",f.delta):ko(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),j&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&tt(f.toolName)){let w=f.args||f.input||{};Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${It}${f.delta}${Oe}`);break;case"reasoning-end":process.stdout.write(`
|
|
207
207
|
|
|
208
208
|
`);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){M.set(f.toolCallId,{toolName:f.toolName});let v=j&&tt(f.toolName)?`${wo}[LOCAL]${Oe} `:"";console.log(`
|
|
209
|
-
${
|
|
210
|
-
`))console.log(`${It}\u2502 ${oe}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),v=cs(f.result,
|
|
211
|
-
`))console.log(`${It}\u2502 ${oe}${Oe}`);console.log(`${
|
|
212
|
-
`),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${It}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Q,messageParts:z}},ke=p({id:yo(),text:r}),q=await a.chat(t,o,ke),A=await ie(q);for(he=A.messageParts;A.pendingClientTools.length>0;){let te=[];for(let M of A.pendingClientTools){!n&&!s&&console.log(`${wo}\u2502 Executing locally...${Oe}`);let Q=await ro(M.toolName,M.args),z=Q.success?JSON.stringify(Q.result):Q.error||"Unknown error";if(te.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:z}],isError:!Q.success}),!n&&!s){let fe=cs(Q.success?Q.result:{error:Q.error},
|
|
213
|
-
`))console.log(`${It}\u2502 ${Te}${Oe}`);console.log(`${
|
|
209
|
+
${qo}\u250C\u2500 ${v}Tool Call: ${f.toolName}${Oe}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},v=Yr(w);console.log(`${us}\u2502 Arguments:${Oe}`);for(let oe of v.split(`
|
|
210
|
+
`))console.log(`${It}\u2502 ${oe}${Oe}`);j&&tt(f.toolName)&&(M.set(f.toolCallId,{toolName:f.toolName,args:w}),Q.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=M.get(f.toolCallId),v=cs(f.result,E);console.log(`${wo}\u2502 Result:${Oe}`);for(let oe of v.split(`
|
|
211
|
+
`))console.log(`${It}\u2502 ${oe}${Oe}`);console.log(`${qo}\u2514\u2500 ${w?.toolName||"Tool"} completed${Oe}
|
|
212
|
+
`),M.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${It}Error: ${f.errorText}${Oe}`);break}}catch{}}}return{pendingClientTools:Q,messageParts:z}},ke=p({id:yo(),text:r}),q=await a.chat(t,o,ke),A=await ie(q);for(he=A.messageParts;A.pendingClientTools.length>0;){let te=[];for(let M of A.pendingClientTools){!n&&!s&&console.log(`${wo}\u2502 Executing locally...${Oe}`);let Q=await ro(M.toolName,M.args),z=Q.success?JSON.stringify(Q.result):Q.error||"Unknown error";if(te.push({toolCallId:M.toolCallId,toolName:M.toolName,content:[{type:"text",text:z}],isError:!Q.success}),!n&&!s){let fe=cs(Q.success?Q.result:{error:Q.error},E);console.log(`${wo}\u2502 Result:${Oe}`);for(let Te of fe.split(`
|
|
213
|
+
`))console.log(`${It}\u2502 ${Te}${Oe}`);console.log(`${qo}\u2514\u2500 ${M.toolName} completed${Oe}
|
|
214
214
|
`)}}let ee=he.map(M=>{if(M.type==="tool-call"){let Q=te.find(fe=>fe.toolCallId===M.toolCallId),z=Q?.content.filter(fe=>fe.type==="text").map(fe=>fe.text).join(`
|
|
215
|
-
`);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Q?.isError?"output-error":"output-available",output:z}}return M}),me=[{id:L,role:"assistant",parts:ee}];L=yo();let ce=p(void 0,te,me);q=await a.chat(t,o,ce),A=await ie(q),he=A.messageParts}s||console.log("")}var Gt="\x1B[2m",Ae="\x1B[0m",pt="\x1B[36m",
|
|
216
|
-
`)}function
|
|
215
|
+
`);return{type:"tool-invocation",toolCallId:M.toolCallId,toolName:M.toolName,args:M.args,state:Q?.isError?"output-error":"output-available",output:z}}return M}),me=[{id:L,role:"assistant",parts:ee}];L=yo();let ce=p(void 0,te,me);q=await a.chat(t,o,ce),A=await ie(q),he=A.messageParts}s||console.log("")}var Gt="\x1B[2m",Ae="\x1B[0m",pt="\x1B[36m",Yo="\x1B[33m",fs="\x1B[32m",ps="stream-json";function ze(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
|
|
216
|
+
`)}function zo(e){let t=new Date(e),s=new Date().getTime()-t.getTime(),n=Math.floor(s/(1e3*60*60*24));return n===0?t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?`${n} days ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function bo(e,t){if(t)return e;let o=e.split(`
|
|
217
217
|
`);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),i=o.length-10;return[...s,`... (${i} lines omitted, use --full-output to see all) ...`,...n].join(`
|
|
218
|
-
`)}function
|
|
218
|
+
`)}function Xo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(Xo);let t={};for(let[o,s]of Object.entries(e))typeof s=="string"&&s.length>200?t[o]=s.slice(0,150)+"... (truncated)":typeof s=="object"&&s!==null?t[o]=Xo(s):t[o]=s;return t}function ms(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function gs(e,t){if(!e)return"(no result)";if(typeof e!="object")return bo(String(e),t);let o=t?e:Xo(e);if("structuredContent"in o&&o.structuredContent){let s=o.structuredContent,n=[];if(s.stdout&&typeof s.stdout=="string"&&s.stdout.trim()&&n.push(s.stdout.trim()),s.stderr&&typeof s.stderr=="string"&&s.stderr.trim()&&n.push(`${Yo}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let i=s.urls;for(let r of i)r.path&&r.url&&n.push(`${r.path}: ${r.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),bo(n.join(`
|
|
219
219
|
`),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join(`
|
|
220
|
-
`);return bo(n||JSON.stringify(e,null,2),t)}return bo(JSON.stringify(e,null,2),t)}function Zr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function hs(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Gt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${pt}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${
|
|
220
|
+
`);return bo(n||JSON.stringify(e,null,2),t)}return bo(JSON.stringify(e,null,2),t)}function Zr(e){if(typeof e.title=="string")return e.title;if(typeof e.toolName=="string")return e.toolName;let t=e.type;return t.startsWith("tool-")?t.slice(5).replace(/__/g," ").replace(/_/g," "):t}function hs(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Gt}${s.text}${Ae}`);else if(s.type==="text"&&s.text)o.push(s.text);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${pt}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Yo}\u2502 Arguments:${Ae}`);let i=ms(s.args);for(let r of i.split(`
|
|
221
221
|
`))n.push(`${Gt}\u2502 ${r}${Ae}`)}if(s.result!==void 0){n.push(`${fs}\u2502 Result:${Ae}`);let i=gs(s.result,t);for(let r of i.split(`
|
|
222
222
|
`))n.push(`${Gt}\u2502 ${r}${Ae}`);n.push(`${pt}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${pt}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${pt}\u2514\u2500${Ae}`);o.push(n.join(`
|
|
223
|
-
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Zr(s),i=[];if(i.push(`${pt}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${
|
|
223
|
+
`))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Zr(s),i=[];if(i.push(`${pt}\u250C\u2500 Tool: ${n}${Ae}`),s.input){i.push(`${Yo}\u2502 Input:${Ae}`);let r=ms(s.input);for(let a of r.split(`
|
|
224
224
|
`))i.push(`${Gt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){i.push(`${fs}\u2502 Output:${Ae}`);let r=gs(s.output,t);for(let a of r.split(`
|
|
225
225
|
`))i.push(`${Gt}\u2502 ${a}${Ae}`);i.push(`${pt}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?i.push(`${pt}\u2514\u2500 (in progress)${Ae}`):i.push(`${pt}\u2514\u2500${Ae}`);o.push(i.join(`
|
|
226
226
|
`))}return o.join(`
|
|
227
227
|
|
|
228
228
|
`).trim()}async function ys(e){let t=e.output===ps;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ps}`),process.exit(1));let o=new B;if(e.shareId){let r;try{r=await dt()}catch{}try{let a=await o.getSharedChat(e.shareId,r),{messages:l}=await o.getSharedMessages(e.shareId,50,r);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(ze("chat",a),l.length===0)ze("info","No messages in this shared chat.");else for(let x of l.toReversed())ze("message",x);ze("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
|
|
229
|
-
`),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),
|
|
230
|
-
`)}let{messages:x}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(x));return}if(t){if(l&&ze("chat",l),x.length===0)ze("info","No messages in this chat.");else for(let m of x.toReversed())ze("message",m);ze("done");return}if(x.length===0){console.log("No messages in this chat.");return}let
|
|
231
|
-
`);for(let m of
|
|
232
|
-
`),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${
|
|
229
|
+
`),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),C=e.fullOutput??!1;for(let x of d){let b=hs(x.parts,C);if(!b)continue;let $=x.role==="user"?"You":"Assistant";console.log(`[${$}] ${zo(x.createdAt)}`),console.log(b),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let r=await pe();s=r.accessToken,n=r.workspaceId}catch(r){xe(r)}if(e.chatId){let r=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let m=d===0?1:d,{chats:h}=await o.getChats(s,n,20);m>h.length&&(console.error(`Chat number ${m} not found. You have ${h.length} recent chats.`),process.exit(1));let T=h[m-1];r=T.id,a=!0,l=T,t||console.log(`Chat: ${T.title||"Untitled"}
|
|
230
|
+
`)}let{messages:x}=await o.getMessages(s,n,r,50);if(e.json){console.log(JSON.stringify(x));return}if(t){if(l&&ze("chat",l),x.length===0)ze("info","No messages in this chat.");else for(let m of x.toReversed())ze("message",m);ze("done");return}if(x.length===0){console.log("No messages in this chat.");return}let b=x.toReversed(),$=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${x.length} messages
|
|
231
|
+
`);for(let m of b){let h=hs(m.parts,$);if(!h)continue;let T=m.role==="user"?"You":"Assistant";console.log(`[${T}] ${zo(m.createdAt)}`),console.log(h),console.log("")}return}let{chats:i}=await o.getChats(s,n,20);if(t){for(let r of i)ze("chat",r);ze("done");return}if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${i.length}):
|
|
232
|
+
`),i.forEach((r,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${zo(r.createdAt).padEnd(12)} ${r.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Qr,Text as Ne}from"ink";import{jsx as je,jsxs as Pt}from"react/jsx-runtime";var At=["apiUrl","hubUrl"];function Zo(e){return At.includes(e)}async function ws(e){let t=e.action||"list",o=e.configKey,s=e.value,n=H.getEffectiveProfileName();if(t==="list"){let i=ne.getAll(),r=Object.entries(i);if(e.json){console.log(JSON.stringify(i));return}if(console.log(`Profile: ${n}`),r.length===0){console.log("No configuration set."),console.log(`Available keys: ${At.join(", ")}`);return}console.log(`Configuration:
|
|
233
233
|
`);for(let[a,l]of r)console.log(` ${a}=${l}`);console.log(`
|
|
234
|
-
Available keys: ${At.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),
|
|
234
|
+
Available keys: ${At.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1));let i=ne.get(o);e.json?console.log(JSON.stringify({[o]:i??null})):console.log(i||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),ne.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),Zo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${At.join(", ")}`),process.exit(1)),ne.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ks(){let e=Me();return Pt(Qr,{flexDirection:"column",children:[je(Ne,{bold:!0,children:"entrydesk config"}),je(Ne,{children:" "}),je(Ne,{children:"Manage CLI configuration"}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Usage:"}),je(Ne,{children:" entrydesk config List all configuration"}),Pt(Ne,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Pt(Ne,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Available keys:"}),Pt(Ne,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Pt(Ne,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),je(Ne,{children:" "}),je(Ne,{bold:!0,children:"Examples:"}),je(Ne,{children:" entrydesk config set apiUrl http://localhost:3200"}),je(Ne,{children:" entrydesk config get apiUrl"}),je(Ne,{children:" entrydesk config unset apiUrl"})]})}async function xs(e){try{let t,o;try{let i=await pe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{connectors:n}=await s.getConnectors(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No connectors found in this workspace.");return}console.log(`Connected Connectors (${n.length}):
|
|
235
235
|
`);for(let i of n){let r=i.connected?"connected":"disconnected";console.log(` ${i.name} (${r})`),console.log(` Provider: ${i.provider}`),console.log(` ID: ${i.id}`),console.log("")}}catch(t){xe(t)}}function Co(){console.log(`
|
|
236
236
|
EntryDesk CLI - Interact with EntryDesk from your terminal
|
|
237
237
|
|
|
@@ -400,9 +400,9 @@ Local Development:
|
|
|
400
400
|
$ entrydesk config set hubUrl http://localhost:3000
|
|
401
401
|
|
|
402
402
|
For more information, visit https://entrydesk.com/docs/cli
|
|
403
|
-
`)}import{render as li}from"ink";import{randomUUID as ei}from"crypto";import{chromium as ti}from"playwright";function oi(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function ni(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid hub URL. Please check ENTRYDESK_HUB_URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Hub URL must use http or https.");if(t.username||t.password)throw new Error("Hub URL must not include credentials.");if(!t.hostname)throw new Error("Hub URL must include a hostname.");if(t.protocol==="http:"&&!oi(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function si(e){try{let t=e.split(".");if(t.length<2)return null;let o=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-o.length%4)%4,n=o.padEnd(o.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i).exp??null}catch{return null}}async function
|
|
403
|
+
`)}import{render as li}from"ink";import{randomUUID as ei}from"crypto";import{chromium as ti}from"playwright";function oi(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"}function ni(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid hub URL. Please check ENTRYDESK_HUB_URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Hub URL must use http or https.");if(t.username||t.password)throw new Error("Hub URL must not include credentials.");if(!t.hostname)throw new Error("Hub URL must include a hostname.");if(t.protocol==="http:"&&!oi(t.hostname))throw new Error("Hub URL must use https unless running on localhost.");return t}function si(e){try{let t=e.split(".");if(t.length<2)return null;let o=t[1].replace(/-/g,"+").replace(/_/g,"/"),s=(4-o.length%4)%4,n=o.padEnd(o.length+s,"="),i=Buffer.from(n,"base64").toString("utf8");return JSON.parse(i).exp??null}catch{return null}}async function Qo(e){let{hubUrl:t,auth:o}=Me(),s=ni(t),n=new URL("/login",s),i=ei();n.searchParams.set("cli","true"),n.searchParams.set("state",i);let r;try{r=await ti.launch({headless:!1,args:["--disable-blink-features=AutomationControlled"]})}catch(a){throw a instanceof Error&&a.message.includes("Executable")?new Error(`Chromium browser is not installed. Please run:
|
|
404
404
|
npm install -g playwright
|
|
405
|
-
npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",m=>{console.log(`[Browser Console] ${m.type()}: ${m.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(m=>{let h=new URL(m);if(h.host!==d)return!1;let T=h.pathname;if(T==="/login"||T.startsWith("/auth/"))return!1;let
|
|
405
|
+
npx playwright install chromium --with-deps`,{cause:a}):a}try{let l=await(await r.newContext({viewport:{width:1280,height:800},ignoreHTTPSErrors:o.ignoreSslErrors})).newPage();process.env.DEBUG&&l.on("console",m=>{console.log(`[Browser Console] ${m.type()}: ${m.text()}`)}),e?.onBrowserOpen?.(),await l.goto(n.toString(),{waitUntil:"networkidle"}),e?.onWaitingForLogin?.();let d=s.host;await l.waitForURL(m=>{let h=new URL(m);if(h.host!==d)return!1;let T=h.pathname;if(T==="/login"||T.startsWith("/auth/"))return!1;let D=h.searchParams.get("state");return!(D&&D!==i)},{timeout:o.loginTimeout});let C=new URL("/api/auth/session",s).toString();process.env.DEBUG&&(console.log(`[DEBUG] Fetching session from: ${C}`),console.log(`[DEBUG] Current page URL: ${l.url()}`),console.log(`[DEBUG] SSL ignore enabled: ${o.ignoreSslErrors}`));let x=await l.evaluate(async m=>{try{let h=await fetch(m);if(!h.ok)throw new Error(`Failed to fetch session: ${h.status} ${h.statusText}`);return h.json()}catch(h){throw console.error("[Browser Context] Fetch error:",h),h}},C);if(!x?.accessToken)throw new Error("Failed to get access token from session");let b=si(x.accessToken);if(b&&b*1e3<=Date.now())throw new Error("Access token is expired. Please log in again.");let $=x.user?.email||"";return e?.onLoginSuccess?.($||"unknown"),{accessToken:x.accessToken,email:$,workspaceId:x.currentWorkspaceId}}catch(a){let l;throw a instanceof Error?(l=a,l.message.includes("fetch failed")&&(l=new Error(`Network request failed. This might be due to SSL certificate issues. Current SSL ignore setting: ${o.ignoreSslErrors}. Original error: ${l.message}`))):l=new Error("Browser authentication failed."),e?.onError?.(l),l}finally{await r.close()}}import{Box as Ee,Text as Le,useApp as ri,useInput as ii}from"ink";import ai from"ink-spinner";import bs from"ink-text-input";import{useState as Ht}from"react";import{jsx as ge,jsxs as Ge}from"react/jsx-runtime";function Cs(){let{exit:e}=ri(),[t,o]=Ht("email"),[s,n]=Ht(""),[i,r]=Ht(""),[a,l]=Ht(null),[d,C]=Ht(null);return ii(($,m)=>{m.escape&&e()}),Ge(Ee,{flexDirection:"column",padding:1,children:[ge(Ee,{marginBottom:1,children:ge(Le,{bold:!0,color:"cyan",children:"EntryDesk Login"})}),t==="email"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(bs,{value:s,onChange:n,onSubmit:$=>{if(!$.includes("@")){l("Please enter a valid email address");return}n($),l(null),o("password")},placeholder:"user@example.com"})]}),a&&ge(Ee,{marginTop:1,children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to continue, Esc to cancel"})})]}),t==="password"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{children:"Email: "}),ge(Le,{color:"green",children:s})]}),Ge(Ee,{children:[ge(Le,{children:"Password: "}),ge(bs,{value:i,onChange:r,onSubmit:async $=>{r($),o("loading"),l(null);try{let m=new B,{token:h,refreshToken:T}=await m.login(s,$),{workspaces:D}=await m.getWorkspaces(h),V=D[0];await $e.saveAll({accessToken:h,refreshToken:T,email:s,workspaceId:V?.id}),C(V?.name??null),o("success"),setTimeout(()=>{e()},1500)}catch(m){o("error"),m instanceof Error?m.message.includes("403")||m.message.includes("Invalid")?l("Invalid email or password"):l(m.message):l("Login failed. Please try again.")}},mask:"*",placeholder:"Enter password"})]}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Press Enter to login, Esc to cancel"})})]}),t==="loading"&&Ge(Ee,{children:[ge(Le,{color:"cyan",children:ge(ai,{type:"dots"})}),ge(Le,{children:" Logging in..."})]}),t==="success"&&Ge(Ee,{flexDirection:"column",children:[Ge(Ee,{children:[ge(Le,{color:"green",children:"\u2713"}),ge(Le,{children:" Logged in as "}),ge(Le,{bold:!0,children:s})]}),d&&ge(Ee,{children:Ge(Le,{dimColor:!0,children:["Workspace: ",d]})})]}),t==="error"&&Ge(Ee,{flexDirection:"column",children:[ge(Ee,{children:ge(Le,{color:"red",children:"\u2717 Login failed"})}),a&&ge(Ee,{children:ge(Le,{color:"red",children:a})}),ge(Ee,{marginTop:1,children:ge(Le,{dimColor:!0,children:"Run `entrydesk login` to try again"})})]})]})}import{jsx as ci}from"react/jsx-runtime";async function $s(e){if(!!(e.email||e.password)){(!e.email||!e.password)&&(console.error("Usage: entrydesk login --email <email> --password <password>"),console.error(" entrydesk login"),console.error(" entrydesk login --google"),console.error(" entrydesk login -i (interactive mode)"),process.exit(1));let a=new B,{token:l,refreshToken:d}=await a.login(e.email,e.password),{workspaces:C}=await a.getWorkspaces(l),x=C[0];await $e.saveAll({accessToken:l,refreshToken:d,email:e.email,workspaceId:x?.id}),e.json?console.log(JSON.stringify({email:e.email,workspaceId:x?.id,workspaceName:x?.name})):(console.log(`Logged in as ${e.email}`),x&&console.log(`Workspace: ${x.name}`));return}if(e.google){console.log("Opening browser for Google OAuth...");let a=await Qo(),l=new B,{workspaces:d}=await l.getWorkspaces(a.accessToken),C=d[0],x=a.workspaceId||C?.id;await $e.saveAll({accessToken:a.accessToken,refreshToken:"",email:a.email,workspaceId:x}),e.json?console.log(JSON.stringify({email:a.email,workspaceId:x,workspaceName:C?.name})):(console.log(`Logged in as ${a.email}`),C&&console.log(`Workspace: ${C.name}`));return}if(e.interactive){li(ci(Cs,{}));return}if(console.log("Opening browser for login..."),process.env.DEBUG){let{getApiUrl:a,getHubUrl:l}=await import("./config-QNEVFNPV.js");console.log(`[DEBUG] Hub URL: ${l()}`),console.log(`[DEBUG] API URL: ${a()}`)}let o=await Qo(),s=new B,{workspaces:n}=await s.getWorkspaces(o.accessToken),i=n[0],r=o.workspaceId||i?.id;await $e.saveAll({accessToken:o.accessToken,refreshToken:"",email:o.email,workspaceId:r}),e.json?console.log(JSON.stringify({email:o.email,workspaceId:r,workspaceName:i?.name})):(console.log(`Logged in as ${o.email}`),i&&console.log(`Workspace: ${i.name}`))}async function Ss(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{await new B().revokeToken(t.refreshToken)}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){xe(t)}}import ui from"http";import{Client as di}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as fi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as pi}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as mi}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as gi}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as hi,ListToolsRequestSchema as yi}from"@modelcontextprotocol/sdk/types.js";async function wi(e,t,o){let s=new di({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),i=new fi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(i),s}function Ts(e){let t=new pi({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(yi,async()=>({tools:(await e.listTools()).tools})),t.setRequestHandler(hi,async o=>{let{name:s,arguments:n}=o.params,i=await e.callTool({name:s,arguments:n});return{content:i.content,isError:i.isError}}),t}async function ki(e,t){let o=ui.createServer(async(s,n)=>{if(s.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),n.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),n.writeHead(204),n.end();return}if(s.url!=="/mcp"){n.writeHead(404,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Not found"}));return}let i=Ts(e),r=new gi({sessionIdGenerator:void 0});if(n.setHeader("Access-Control-Allow-Origin","*"),n.on("close",()=>{r.close(),i.close()}),await i.connect(r),s.method==="POST"){let a="";s.on("data",l=>{a+=l.toString()}),s.on("end",async()=>{try{let l=JSON.parse(a);await r.handleRequest(s,n,l)}catch{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Invalid JSON"}))}})}else await r.handleRequest(s,n)});o.listen(t,()=>{console.error(`EntryDesk MCP server running at http://localhost:${t}/mcp`),console.error("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{console.error(`
|
|
406
406
|
Shutting down...`),o.close(),await e.close(),process.exit(0)}),process.on("SIGTERM",async()=>{o.close(),await e.close(),process.exit(0)})}async function xi(e){let t=Ts(e),o=new mi;o.onclose=async()=>{await e.close()},await t.connect(o)}async function vs(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{console.error("[entrydesk-mcp] Starting MCP server...");let t,o;try{let r=await pe();t=r.accessToken,o=r.workspaceId}catch(r){let a=r instanceof Error?r.message:"Authentication failed";console.error(a),process.exit(1)}let{apiUrl:s,mcp:n}=Me();console.error(`[entrydesk-mcp] Connecting to ${s}...`),console.error(`[entrydesk-mcp] Workspace: ${o}`);let i=await wi(s,t,o);if(console.error("[entrydesk-mcp] Connected to EntryDesk API"),e.mode==="http"){let r=e.port||n.httpPort;await ki(i,r)}else console.error("[entrydesk-mcp] Starting stdio server..."),await xi(i),console.error("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function Is(e){try{let t,o;try{let i=await pe();t=i.accessToken,o=i.workspaceId}catch(i){let r=i instanceof Error?i.message:"Authentication failed";console.error(r),process.exit(1)}let s=new B,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
|
|
407
407
|
`);for(let i of n)console.log(` ${i.name}`),i.description&&console.log(` ${i.description.slice(0,80)}`),console.log(` ID: ${i.id}`),console.log("")}catch(t){xe(t)}}function bi(){console.log(`
|
|
408
408
|
Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
|
|
@@ -462,30 +462,32 @@ Schedule:
|
|
|
462
462
|
Next Run: ${e.nextRunAt?qt(e.nextRunAt,e.utcOffset):"-"}
|
|
463
463
|
Created: ${qt(e.createdAt,e.utcOffset)}
|
|
464
464
|
Updated: ${qt(e.updatedAt,e.utcOffset)}
|
|
465
|
-
`)}function Si(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function
|
|
466
|
-
`);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${As(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?qt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){xe(t)}}import Ti from"fs";import
|
|
467
|
-
Usage: entrydesk skills [list|upload|delete] [options]
|
|
465
|
+
`)}function Si(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,i]=s.split(":"),r={hour:parseInt(n,10),minute:parseInt(i,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:r.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:r}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:r}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:r}};default:return{type:"no-repeat"}}}async function Ns(e){try{if(e.help){Kt();return}let t=await pe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",i=new B;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1));let d=await i.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}$i(d);return}if(n==="create"){(!e.name||!e.prompt||!e.agentId||!e.startsAt)&&(console.error("Missing required fields for schedule creation."),console.error("Required: --name, --prompt, --agent-id, --starts-at"),Kt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:Si(e),utcOffset:e.utcOffset||"+00:00"},d=await i.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?qt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Kt(),process.exit(1)),await i.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Kt(),process.exit(1));let r=[],a;do{let l=await i.getSchedules(o,s,{nextKey:a,limit:100});r.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${r.length}):
|
|
466
|
+
`);for(let l of r){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${As(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?qt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){xe(t)}}import Ti from"fs";import Nt from"fs/promises";import Es from"os";import st from"path";import vi from"archiver";function $o(){console.log(`
|
|
467
|
+
Usage: entrydesk skills [list|upload|delete|versions] [options]
|
|
468
468
|
|
|
469
469
|
Commands:
|
|
470
|
-
list
|
|
471
|
-
upload <file.zip>
|
|
472
|
-
upload <folder>
|
|
473
|
-
delete <skillId>
|
|
470
|
+
list List available skills (default)
|
|
471
|
+
upload <file.zip> Upload a skill zip file
|
|
472
|
+
upload <folder> Upload a skill folder (auto-zipped)
|
|
473
|
+
delete <skillId> Delete a skill you own
|
|
474
|
+
versions <skill-name> List all versions of a skill
|
|
474
475
|
|
|
475
476
|
Options:
|
|
476
|
-
--me
|
|
477
|
-
--force
|
|
478
|
-
--json
|
|
479
|
-
`)}function Ii(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Pi(e){let t=await
|
|
480
|
-
`)
|
|
477
|
+
--me Only list skills created by me
|
|
478
|
+
--force Overwrite an existing skill with the same name
|
|
479
|
+
--json Output JSON (for list/upload/versions)
|
|
480
|
+
`)}function Ii(e,t){let o=st.relative(e,t);return o===""||!o.startsWith("..")&&!st.isAbsolute(o)}async function Pi(e){let t=await Nt.realpath(e),o=[process.cwd(),Es.homedir()];if(!(await Promise.all(o.map(async i=>{try{return await Nt.realpath(i)}catch{return st.resolve(i)}}))).some(i=>Ii(i,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function Ai(e){let t=await Nt.mkdtemp(st.join(Es.tmpdir(),"entrydesk-skill-")),o=st.join(t,`${st.basename(e)}.zip`);return await new Promise((s,n)=>{let i=Ti.createWriteStream(o),r=vi("zip",{zlib:{level:9}});i.on("close",()=>s()),i.on("error",n),r.on("error",n),r.pipe(i),r.directory(e,!1),r.finalize()}),{zipPath:o,cleanupDir:t}}async function _s(e){let t,o;try{let a=await pe();t=a.accessToken,o=a.workspaceId}catch(a){xe(a)}let s=e.action||"list",n=new B;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),$o(),process.exit(1));let l=st.resolve(a),d;try{d=await Nt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let C=l,x=null;try{try{await Pi(l)}catch(h){let T=h instanceof Error?h.message:"Invalid upload path.";console.error(T),process.exit(1)}if(d.isDirectory()){let h=await Ai(l);C=h.zipPath,x=h.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));st.extname(C).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await Nt.readFile(C),$=new FormData;$.append("file",new Blob([b],{type:"application/zip"}),st.basename(C)),e.force&&$.append("force","true");let m;try{m=await n.uploadSkill(t,o,$)}catch(h){if(h instanceof Error&&h.name==="HTTPError"){let T=h;if(T.response&&T.response.status===409){try{(await T.response.json()).code==="skill_name_conflict"?console.error("Upload failed: A skill with this name is owned by another user."):(console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill."))}catch{console.error("Upload failed: A skill with this name already exists."),console.error("Use --force to overwrite the existing skill.")}process.exit(1)}}throw h}if(e.json){console.log(JSON.stringify(m));return}console.log(`Uploaded skill: ${m.name}`),console.log(` ID: ${m.id}`),console.log(` Version ID: ${m.versionId}`),console.log(` Description: ${m.description}`);return}finally{x&&await Nt.rm(x,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),$o(),process.exit(1)),await n.deleteSkill(t,o,a),console.log(`Deleted skill: ${a}`);return}if(s==="versions"){let a=e.configKey;a||(console.error("Missing skill name."),$o(),process.exit(1));let l=[],d;do{let b=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});l.push(...b.skills),d=b.nextKey}while(d);let C=l.find(b=>b.name===a);C||(console.error(`Skill not found: ${a}`),process.exit(1));let x=await n.listSkillVersions(t,o,C.id);if(e.json){console.log(JSON.stringify(x));return}if(console.log(`Versions for skill "${x.skillName}":
|
|
481
|
+
`),x.versions.length===0){console.log(" No versions found.");return}for(let b of x.versions){let $=new Date(b.createdAt);console.log(` ${$.toLocaleString()}`),console.log(` ID: ${b.id}`),console.log(` Description: ${b.description.slice(0,80)}`),console.log(` Created by: ${b.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),$o(),process.exit(1));let i=[],r;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:r,limit:100});i.push(...a.skills),r=a.nextKey}while(r);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${i.length}):
|
|
482
|
+
`);for(let a of i)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Ls(e){try{let t=H.getEffectiveProfileName(),o=await $e.getAll(),s={model:ne.getDefaultModel(),connectors:ne.getDefaultConnectorIds(),capabilities:ne.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let i=new B,r=await dt(),{workspaces:a}=await i.getWorkspaces(r);n=a.find(d=>d.id===o.workspaceId)?.name}catch(i){if(i instanceof Qe){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}}e.json?console.log(JSON.stringify({loggedIn:!0,profile:t,email:o.email,workspaceId:o.workspaceId,workspaceName:n,defaults:s})):(console.log(`Profile: ${t}`),console.log(`Logged in as ${o.email}`),n&&console.log(`Workspace: ${n}`),o.workspaceId&&console.log(`Workspace ID: ${o.workspaceId}`))}catch(t){xe(t)}}import Wi from"fs";import{Client as Ni}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Ei}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function _i(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await pe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Me().apiUrl);let n=new Ni({name:"entrydesk-cli",version:"1.0.0"}),i=new URL(`${t}/v1/workspaces/${s}/mcp`),r=new Ei(i,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(r),n}async function So(){return _i()}import tn from"fs/promises";import Li from"os";import zt from"path";var en=!process.env.NO_COLOR&&process.stdout.isTTY!==!1,Et={green:en?"\x1B[32m":"",yellow:en?"\x1B[33m":"",reset:en?"\x1B[0m":""},Di=10*1024,Ds=8*1024,Os=2*1024,Oi=100,Ri=100;function Ui(){return zt.join(Li.homedir(),".entrydesk","tool-results")}function ji(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Oi);return!t||t==="."||t===".."?"unnamed_tool":t}function Bi(e){try{return JSON.stringify(e,(t,o)=>typeof o=="bigint"?`${o}n`:typeof o=="function"?"[Function]":typeof o=="symbol"?o.toString():o,2)}catch{return String(e)}}function Fi(e){let t=new Date,o=[t.getFullYear(),String(t.getMonth()+1).padStart(2,"0"),String(t.getDate()).padStart(2,"0")].join("-")+"_"+[String(t.getHours()).padStart(2,"0"),String(t.getMinutes()).padStart(2,"0"),String(t.getSeconds()).padStart(2,"0")].join("-"),s=ji(e);return`${o}_${s}.json`}async function Rs(e,t){try{return await tn.writeFile(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="EEXIST")return!1;throw o}}async function Us(e,t){try{let o=Ui();await tn.mkdir(o,{recursive:!0});let s=Fi(e),n=zt.extname(s),i=s.slice(0,-n.length),r=Bi(t),a=zt.join(o,s);if(await Rs(a,r))return a;for(let C=1;C<=Ri;C++){let x=zt.join(o,`${i}-${C}${n}`);if(await Rs(x,r))return x}let l=Math.random().toString(36).slice(2,10),d=zt.join(o,`${i}-${l}${n}`);return await tn.writeFile(d,r,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${Et.yellow}Warning: Could not save result to file: ${s}${Et.reset}`),null}}function js(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Di)return e;let s=e.slice(0,Ds),n=e.slice(-Os),r=((o-Ds-Os)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${r}KB of ${a}KB) ...`;return t&&(l+=`
|
|
481
483
|
Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
|
|
482
484
|
|
|
483
485
|
${l}
|
|
484
486
|
|
|
485
|
-
${n}`}function Bs(e){console.log(`${
|
|
487
|
+
${n}`}function Bs(e){console.log(`${Et.green}Tool execution result saved to: ${e}${Et.reset}`),console.log()}function Fs(){console.log(`${Et.green}Tool execution result:${Et.reset}`)}function Mi(e){return e.split("__")[0]??e}function yt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function _t(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?yt("AUTH_MISSING",s,t):yt(o,s,t)}async function Ji(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(r),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},i=C=>{s||(s=!0,n(),e(C))},r=setTimeout(()=>{o||i(null)},100),a=C=>{o=!0,clearTimeout(r),t.push(C)},l=()=>{t.length===0?i(null):i(Buffer.concat(t).toString("utf-8").trim())},d=()=>{i(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Yt=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Gi(e,t){if(e)return e;if(t)try{return Wi.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Yt(`Failed to read input file: ${n}`)}let o=await Ji();if(o)return o;throw new Yt("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Hi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
|
|
486
488
|
`)}function Vi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&(t.push("Description:"),t.push(` ${e.description}`)),t.push("Input Schema:"),t.push(JSON.stringify(e.inputSchema,null,2)),t.join(`
|
|
487
|
-
`)}async function Ki(e,t){let o=await
|
|
488
|
-
`);for(let r of n)console.log(Hi(r)),console.log()}}catch(s){_t(s,e)}finally{await o.close().catch(()=>{})}}async function qi(e,t){let o=await
|
|
489
|
+
`)}async function Ki(e,t){let o=await So().catch(s=>{_t(s,e)});try{let n=(await o.listTools()).tools;if(t){let i=t.toLowerCase();n=n.filter(r=>Mi(r.name).toLowerCase().startsWith(i))}if(e)console.log(JSON.stringify(n,null,2));else{let i=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${i}:
|
|
490
|
+
`);for(let r of n)console.log(Hi(r)),console.log()}}catch(s){_t(s,e)}finally{await o.close().catch(()=>{})}}async function qi(e,t){let o=await So().catch(s=>{_t(s,t)});try{let n=(await o.listTools()).tools.find(i=>i.name===e);n||yt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Vi(n))}catch(s){_t(s,t)}finally{await o.close().catch(()=>{})}}async function zi(e,t,o){let s;try{s=JSON.parse(t)}catch(r){let a=r instanceof Error?`Invalid JSON input: ${r.message}`:"Invalid JSON input";yt("INVALID_INPUT",a,o)}let n=await So().catch(r=>{_t(r,o,"TOOL_CALL_FAILED")}),i=!1;try{let r=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(r,null,2));else{let a=await Us(e,r);a&&Bs(a),Fs();let l=r.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(r.structuredContent){let d=JSON.stringify(r.structuredContent,null,2),C=js(d,a);console.log(C)}}r.isError&&(i=!0)}catch(r){_t(r,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}i&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ki(t,e.prefix);break;case"get":e.name||yt("INVALID_INPUT","Tool name is required",t),await qi(e.name,t);break;case"call":{e.name||yt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Gi(e.input,e.inputFile)}catch(s){throw s instanceof Yt&&yt("INVALID_INPUT",s.message,t),s}await zi(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
|
|
489
491
|
|
|
490
492
|
Actions:
|
|
491
493
|
list List all available tools
|
|
@@ -525,8 +527,8 @@ Examples:
|
|
|
525
527
|
entrydesk usage --json # JSON output
|
|
526
528
|
`)}async function Ms(e){if(e.help){Yi();return}let t,o;try{let m=await pe();t=m.accessToken,o=m.workspaceId}catch(m){let h=m instanceof Error?m.message:"Authentication failed";console.error(h),process.exit(1)}let s=new B,n=[],i,r=0,a=100;do{let m=await s.getMonthlyUsages(t,o,{nextKey:i,limit:100});if(n.push(...m.monthlyUsages),i=m.nextKey,r++,r>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(i);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
|
|
527
529
|
`);let l=0,d=0;for(let m of n)l+=parseFloat(m.totalCost),d+=m.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
|
|
528
|
-
`);let
|
|
529
|
-
`);for(let m of $){let h=parseFloat(m.totalCost);console.log(` ${m.user.name} (${m.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${m.operationCount.toLocaleString()}`),console.log("")}$.length<n.length&&console.log(`... and ${n.length-$.length} more users`)}function on(){console.log("entrydesk 1.7.
|
|
530
|
+
`);let C=e.sortBy||"cost",x=[...n].toSorted((m,h)=>C==="cost"?parseFloat(h.totalCost)-parseFloat(m.totalCost):h.operationCount-m.operationCount),b=e.limit&&e.limit>0?e.limit:x.length,$=x.slice(0,b);console.log(`Usage by User (sorted by ${C}, showing ${$.length} of ${n.length}):
|
|
531
|
+
`);for(let m of $){let h=parseFloat(m.totalCost);console.log(` ${m.user.name} (${m.user.email})`),console.log(` Cost: $${h.toFixed(2)}`),console.log(` Operations: ${m.operationCount.toLocaleString()}`),console.log("")}$.length<n.length&&console.log(`... and ${n.length-$.length} more users`)}function on(){console.log("entrydesk 1.7.6")}function nn(){console.log(`
|
|
530
532
|
Usage: entrydesk workspaces [list|switch|use] [options]
|
|
531
533
|
|
|
532
534
|
Commands:
|
|
@@ -536,6 +538,6 @@ Commands:
|
|
|
536
538
|
|
|
537
539
|
Flags:
|
|
538
540
|
--json Output JSON
|
|
539
|
-
`)}async function Js(e){if(e.help){nn();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await dt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",i=new B;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),nn(),process.exit(1));let{workspaces:l}=await i.getWorkspaces(t),d=l.find(
|
|
540
|
-
Available workspaces:`);for(let
|
|
541
|
-
`);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Gs(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":r==="--google"||r==="-g"?n.google=!0:r==="-i"||r==="--interactive"?n.interactive=!0:r==="--email"?n.email=e[++i]:r==="--password"&&(n.password=e[++i]);break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(l=>l.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as ea}from"react/jsx-runtime";var He=process.argv.slice(2);(He[0]==="--help"||He[0]==="-h")&&(Co(),process.exit(0));(He[0]==="--version"||He[0]==="-v")&&(on(),process.exit(0));var sn=!He[0]||He[0].startsWith("-"),Zi=sn?"chat":He[0],be=Gs(He,Zi,sn);sn&&be.command==="chat"&&(be.interactive=!0);async function Qi(){try{if(be.command!=="profile"){let e=be.profile||H.getCurrentProfileName();H.ensureProfileExists(e),H.setOverrideProfile(e)}switch(be.command){case"login":await $s(be);break;case"logout":await Ss(be);break;case"status":await Ls(be);break;case"workspaces":await Js(be);break;case"agents":await an(be);break;case"models":await Is(be);break;case"connectors":await xs(be);break;case"skills":await _s(be);break;case"schedules":await
|
|
541
|
+
`)}async function Js(e){if(e.help){nn();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await dt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",i=new B;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),nn(),process.exit(1));let{workspaces:l}=await i.getWorkspaces(t),d=l.find(C=>C.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
|
|
542
|
+
Available workspaces:`);for(let C of l)console.error(` ${C.name}: ${C.id}`);process.exit(1)}if(await $e.saveWorkspaceId(a),e.json){console.log(JSON.stringify({workspaceId:a,workspaceName:d.name}));return}console.log(`Switched to workspace: ${d.name}`),console.log(` ID: ${a}`);return}n!=="list"&&(console.error(`Unknown workspaces command: ${n}`),nn(),process.exit(1));let{workspaces:r}=await i.getWorkspaces(t);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${r.length}):
|
|
543
|
+
`);for(let a of r){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Gs(e,t,o=!1){let s={},n={};for(let i=o?0:1;i<e.length;i++){let r=e[i];if(r==="--json")s.json=!0;else if(r==="--help"||r==="-h")s.help=!0;else if(r==="--profile")s.profile=e[++i];else switch(t){case"login":r==="--google"||r==="-g"?n.google=!0:r==="-i"||r==="--interactive"?n.interactive=!0:r==="--email"?n.email=e[++i]:r==="--password"&&(n.password=e[++i]);break;case"chat":if(r==="-m"||r==="--message")n.message=e[++i];else if(r==="-a"||r==="--agent")n.agentId=e[++i];else if(r==="--model")n.model=e[++i];else if(r==="--connectors"){let a=e[++i];n.connectors=a?.split(",").map(l=>l.trim())}else r==="-i"||r==="--interactive"?n.interactive=!0:r==="--full-output"?n.fullOutput=!0:r==="-c"||r==="--continue"?n.continue=parseInt(e[++i],10):r==="--plain"?n.plain=!0:r==="--output"?n.output=e[++i]:r==="--sandbox"?n.sandbox=!0:r==="--no-sandbox"?n.noSandbox=!0:r==="--web-search"?n.webSearch=!0:r==="--image-gen"?n.imageGen=!0:r==="--chart"?n.chart=!0:r==="--file-system"?n.fileSystem=!0:r==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(r==="--name")n.name=e[++i];else if(r==="--description")n.description=e[++i];else if(r==="--system-prompt")n.systemPrompt=e[++i];else if(r==="--model-id")n.modelId=e[++i];else if(r==="--connector-ids"){let a=e[++i];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--capabilities"){let a=e[++i];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--conversation-starters"){let a=e[++i];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(r==="--tools"){let a=e[++i];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else r==="--icon-id"?n.iconId=e[++i]:r.startsWith("-")||(n.action?n.agentId=r:n.action=r);break;case"skills":r==="--force"?n.force=!0:r==="--me"||r==="--mine"?n.createdBy="me":r.startsWith("-")||(n.action?n.configKey=r:n.action=r);break;case"schedules":if(r==="--name")n.name=e[++i];else if(r==="--prompt")n.prompt=e[++i];else if(r==="--agent-id")n.agentId=e[++i];else if(r==="--starts-at")n.startsAt=e[++i];else if(r==="--utc-offset")n.utcOffset=e[++i];else if(r==="--repeat-type")n.repeatType=e[++i];else if(r==="--every")n.every=parseInt(e[++i],10);else if(r==="--time")n.time=e[++i];else if(r==="--days-of-week"){let a=e[++i];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(r==="--days-of-month"){let a=e[++i];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else r==="--last-day-of-month"?n.lastDayOfMonth=!0:r.startsWith("-")||(n.action?n.scheduleId=r:n.action=r);break;case"config":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")?n.configKey=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"profile":!n.action&&!r.startsWith("-")?n.action=r:!n.name&&!r.startsWith("-")?n.name=r:!n.value&&!r.startsWith("-")&&(n.value=r);break;case"chats":r==="--share"||r==="-s"?n.shareId=e[++i]:r==="--full-output"?n.fullOutput=!0:r==="--output"?n.output=e[++i]:!n.chatId&&!r.startsWith("-")&&(n.chatId=r);break;case"budget":!n.action&&!r.startsWith("-")?n.action=r:!n.configKey&&!r.startsWith("-")&&(n.configKey=r);break;case"usage":if(r==="--limit")n.limit=parseInt(e[++i],10);else if(r==="--sort-by"){let a=e[++i];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":r==="--http"?n.http=!0:(r==="-p"||r==="--port")&&(n.port=parseInt(e[++i],10));break;case"tool":r==="-i"||r==="--input"?n.input=e[++i]:r==="-f"||r==="--input-file"?n.inputFile=e[++i]:r==="-p"||r==="--prefix"?n.prefix=e[++i]:r.startsWith("-")||(n.action?n.name||(n.name=r):n.action=r);break;case"workspaces":!n.action&&!r.startsWith("-")&&(n.action=r);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as ea}from"react/jsx-runtime";var He=process.argv.slice(2);(He[0]==="--help"||He[0]==="-h")&&(Co(),process.exit(0));(He[0]==="--version"||He[0]==="-v")&&(on(),process.exit(0));var sn=!He[0]||He[0].startsWith("-"),Zi=sn?"chat":He[0],be=Gs(He,Zi,sn);sn&&be.command==="chat"&&(be.interactive=!0);async function Qi(){try{if(be.command!=="profile"){let e=be.profile||H.getCurrentProfileName();H.ensureProfileExists(e),H.setOverrideProfile(e)}switch(be.command){case"login":await $s(be);break;case"logout":await Ss(be);break;case"status":await Ls(be);break;case"workspaces":await Js(be);break;case"agents":await an(be);break;case"models":await Is(be);break;case"connectors":await xs(be);break;case"skills":await _s(be);break;case"schedules":await Ns(be);break;case"chats":await ys(be);break;case"budget":await ln(be);break;case"usage":await Ms(be);break;case"config":be.action==="help"||He[1]==="--help"?Xi(ea(ks,{})):await ws(be);break;case"profile":await Ps(be);break;case"chat":He[1]==="--help"||He[1]==="-h"?Co():await ds(be);break;case"mcp-server":await vs({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ws(be);break;case"version":on();break;default:Co();break}}catch(e){xe(e)}}Qi();
|
package/package.json
CHANGED
package/dist/chunk-G36L33PZ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import E from"crypto";import f from"fs";import pe from"path";import u from"fs";import ce from"os";import S from"path";import{HTTPError as ae,TimeoutError as le}from"ky";import re,{TimeoutError as se}from"ky";import R from"fs";function X(r){let e=o.getEffectiveProfileName(r);return o.getProfileConfigFile(e)}function a(r){let e=X(r);try{if(!R.existsSync(e))return{};let t=R.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function d(r,e){let t=o.getEffectiveProfileName(e);o.ensureProfileDir(t);let s=o.getProfileConfigFile(t);R.writeFileSync(s,JSON.stringify(r,null,2),{mode:384});try{R.chmodSync(s,384)}catch{}}var U={getApiUrl(r){return a(r).apiUrl??null},setApiUrl(r,e){let t=a(e);t.apiUrl=r,d(t,e)},clearApiUrl(r){let e=a(r);delete e.apiUrl,d(e,r)},getHubUrl(r){return a(r).hubUrl??null},setHubUrl(r,e){let t=a(e);t.hubUrl=r,d(t,e)},getAll(r){return a(r)},setAll(r,e){d(r,e)},set(r,e,t){let s=a(t);s[r]=e,d(s,t)},get(r,e){return a(e)[r]},unset(r,e){let t=a(e);delete t[r],d(t,e)},getDefaultModel(r){return a(r).model?.default??null},setDefaultModel(r,e){let t=a(e);t.model={...t.model,default:r},d(t,e)},getDefaultConnectorIds(r){return a(r).connectors?.defaults??null},setDefaultConnectorIds(r,e){let t=a(e);t.connectors={...t.connectors,defaults:r},d(t,e)},getCapabilities(r){return a(r).capabilities??null},setCapabilities(r,e){let t=a(e);t.capabilities={...t.capabilities,...r},d(t,e)},getLocalTools(r){return a(r).localTools??null},setLocalTools(r,e){let t=a(e);t.localTools={...t.localTools,...r},d(t,e)}};var Z="https://entrydesk-api.dcard.io",Q="https://entrydesk.dcard.io",ee=3100,te=300*1e3;function T(r){return{apiUrl:U.getApiUrl(r)||process.env.ENTRYDESK_API_URL||Z,hubUrl:U.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Q,mcp:{httpPort:ee},auth:{loginTimeout:te,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function O(r){return T(r).apiUrl}function Ae(r){return T(r).hubUrl}function be(){return T().mcp}function z(){return T().auth}var W="ENTRYDESK_ALLOW_INSECURE_LOGIN",K=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||O(t),z().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=re.create({prefixUrl:this.baseUrl,timeout:3e4,retry:{limit:3,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504]},hooks:{beforeError:[n=>(n.request?.headers&&(n.request.headers.delete("authorization"),n.request.headers.delete("Authorization")),n)]}})}getBaseUrl(){return this.baseUrl}shouldAllowInsecureLogin(){return process.env[W]?.toLowerCase()==="true"}assertSecureLogin(){let e;try{e=new URL(this.baseUrl)}catch(t){let s=t instanceof Error?t:void 0;throw new c("Invalid API URL; cannot perform login.",1,s)}if(e.protocol!=="https:"&&!this.shouldAllowInsecureLogin())throw new c(`Login requires HTTPS. Set apiUrl to https:// or set ${W}=true for local development.`)}async login(e,t){return this.assertSecureLogin(),await this.client.post("v1/auth/credentials/token",{json:{email:e,password:t}}).json()}async refreshToken(e){return await this.client.post("v1/auth/token/refresh",{json:{refreshToken:e}}).json()}async revokeToken(e){await this.client.post("v1/auth/token/revoke",{json:{refreshToken:e}})}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){return await this.client.get(`v1/workspaces/${t}/availableAgents`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:100}}).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 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 getChats(e,t,s=20){return await this.client.get(`v1/workspaces/${t}/chats`,{headers:{Authorization:`Bearer ${e}`},searchParams:{limit:s}}).json()}async getMessages(e,t,s,n=50){return await this.client.get(`v1/workspaces/${t}/chats/${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 chat(e,t,s){try{let n=await this.client.post(`v1/workspaces/${t}/chats`,{headers:{Authorization:`Bearer ${e}`},json:s,timeout:6e4,throwHttpErrors:!1});if(!n.ok){let i=await n.text();throw new Error(`Chat API failed (${n.status}): ${i}`)}return n}catch(n){throw n instanceof se?new Error("Request timed out. Please check your connection and try again.",{cause:n}):n}}async getBudget(e,t){return await this.client.get(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`}}).json()}async updateBudget(e,t,s){return await this.client.put(`v1/workspaces/${t}/budget`,{headers:{Authorization:`Bearer ${e}`},json:{budget:s}}).json()}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 createChatShare(e,t,s,n="public"){return await this.client.post(`v1/workspaces/${t}/chats/${s}/shares`,{headers:{Authorization:`Bearer ${e}`},json:{visibility:n}}).json()}async getSharedChat(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 deleteChat(e,t,s){await this.client.delete(`v1/workspaces/${t}/chats/${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,g=new Blob([s.buffer],{type:s.mimeType});return i.append("file",g,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}`}})}static async getAuthenticatedClient(e){let t=await h.getAll(e);return t?{client:new r(void 0,e),accessToken:t.accessToken,workspaceId:t.workspaceId??null}:null}};function ne(){return process.env.ENTRYDESK_SANDBOX==="true"}function I(){if(!ne())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}}var p=class extends Error{code;constructor(e,t){super(t),this.code=e}};function ie(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 oe(r,e=300){let t=ie(r);if(!t?.exp)return!1;let s=Math.floor(Date.now()/1e3);return t.exp-s<=e}async function G(r){let e=r.accessToken;if(!oe(e))return e;if(!r.refreshToken)throw await h.clear(),new p("session-expired","Session expired. Please run `entrydesk login` again.");try{let t=new K,{token:s}=await t.refreshToken(r.refreshToken);return await h.saveAccessToken(s),s}catch{throw await h.clear(),new p("session-expired","Session expired. Please run `entrydesk login` again.")}}async function De(){let r=I();if(r)return r.accessToken;let e=await h.getAll();if(!e?.accessToken)throw new p("not-logged-in","Not logged in. Run `entrydesk login` first.");return G(e)}async function _e(){let r=I();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=await h.getAll();if(!e?.accessToken)throw new p("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!e.workspaceId)throw new p("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await G(e),workspaceId:e.workspaceId}}var c=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}};function je(r){let e=!!process.env.DEBUG;r instanceof c&&(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 p&&(console.error(r.message),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof le&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof ae&&(console.error(`Request failed (${r.response.status}): ${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 m="default",ge=/^[A-Za-z0-9_-]+$/,F=null;function D(){return S.join(ce.homedir(),".entrydesk")}function H(){return S.join(D(),"profiles")}function J(){return S.join(D(),"profiles.json")}function $(r){return S.join(H(),r)}function _(r){if(!u.existsSync(r))u.mkdirSync(r,{mode:448,recursive:!0});else try{u.chmodSync(r,448)}catch{}}function de(){_(D())}function B(){_(H())}function ue(){let r=J();try{if(!u.existsSync(r))return null;let e=u.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function P(r){de();let e=J();u.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{u.chmodSync(e,384)}catch{}}function fe(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||m;return e.length===0&&e.push(m),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function y(){let r=ue();if(!r){let t={currentProfile:m,profiles:[m]};return P(t),B(),x(m),t}let e=fe(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&P(e),B(),e}function k(r){if(!r)throw new c("Profile name is required.");if(!ge.test(r))throw new c("Invalid profile name. Use letters, numbers, dash, or underscore.")}function b(r,e){if(!r.profiles.includes(e))throw new c(`Profile not found: ${e}`)}function Y(r,e){if(r.profiles.includes(e))throw new c(`Profile already exists: ${e}`)}function x(r){B(),_($(r))}var o={DEFAULT_PROFILE:m,setOverrideProfile(r){F=r},getOverrideProfile(){return F},getProfileDir(r){return $(r)},getProfileConfigFile(r){return S.join(o.getProfileDir(r),"config.json")},getProfileCredentialsFile(r){return S.join(o.getProfileDir(r),"credentials.json")},getProfileNames(){return[...y().profiles]},getProfileCount(){return o.getProfileNames().length},getCurrentProfileName(){return y().currentProfile},getEffectiveProfileName(r){let e=y(),t=r||F||e.currentProfile;return k(t),b(e,t),t},ensureProfileExists(r){let e=y();k(r),b(e,r)},createProfile(r){k(r);let e=y();Y(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};P(t),x(r)},deleteProfile(r){k(r);let e=y();if(b(e,r),e.profiles.length===1)throw new c("Cannot delete the last profile.");let t=e.profiles.filter(i=>i!==r),s=e.currentProfile;s===r&&(s=t.includes(m)?m:t[0]),P({currentProfile:s,profiles:t});try{u.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){k(r),k(e);let t=y();b(t,r),Y(t,e);let s=$(r),n=$(e);if(u.existsSync(s))try{u.renameSync(s,n)}catch(v){throw new c("Failed to rename profile directory.",1,v)}else x(e);let i=t.profiles.map(v=>v===r?e:v),g=t.currentProfile===r?e:t.currentProfile;return P({currentProfile:g,profiles:i}),{currentProfile:g}},setCurrentProfile(r){k(r);let e=y();b(e,r);let t={currentProfile:r,profiles:e.profiles};P(t),x(r)},ensureProfileDir:x};var he="ENTRYDESK_FORCE_FILE_STORAGE",C="EntryDesk CLI",ye="__entrydesk_keychain_test__",me="profile:",we=".credentials.key",q={keychain:!1,permissions:!1,corruptFile:!1,windowsFile:!1};function w(r,e){q[r]||(q[r]=!0,console.error(e))}function V(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 ve(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 M(r){return o.getProfileCredentialsFile(r)}var L=class{getKeyFilePath(e){return pe.join(o.getProfileDir(e),we)}loadEncryptionKey(e){let t=this.getKeyFilePath(e);try{if(!f.existsSync(t))return null;let s=f.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=E.randomBytes(32);return f.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=E.randomBytes(16),n=E.createCipheriv("aes-256-gcm",t,s),i=n.update(e,"utf8","hex");i+=n.final("hex");let g=n.getAuthTag();return`${s.toString("hex")}:${g.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"),g=s[2],A=E.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});A.setAuthTag(i);let v=A.update(g,"hex","utf8");return v+=A.final("utf8"),v}tryDecrypt(e,t){try{return this.decrypt(e,t)}catch{return null}}tryParseCredentials(e){try{let t=JSON.parse(e);return V(t)?t:null}catch{return null}}ensureSecureFilePermissions(e){if(process.platform!=="win32"){try{f.chmodSync(e,384)}catch{w("permissions","Warning: Failed to set secure permissions on credentials file.");return}try{(f.statSync(e).mode&511)!==384&&w("permissions","Warning: Credentials file permissions are too permissive.")}catch{w("permissions","Warning: Failed to verify credentials file permissions.")}}}async getCredentials(e){let t=M(e);try{if(!f.existsSync(t))return null;let s=f.readFileSync(t,"utf-8").trim();if(!s)return null;let n=this.loadEncryptionKey(e),i=n?this.tryDecrypt(s,n):null;if(i){let g=this.tryParseCredentials(i);if(g)return g}return w("corruptFile","Warning: Credentials file is unreadable. Please run `entrydesk login` again."),null}catch{return null}}async setCredentials(e,t){o.ensureProfileDir(e);let s=M(e),n=this.getOrCreateEncryptionKey(e),i=this.encrypt(JSON.stringify(t),n);f.writeFileSync(s,i,{mode:384}),this.ensureSecureFilePermissions(s)}async deleteCredentials(e){let t=M(e);try{f.existsSync(t)&&f.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=ve(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${me}${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=`${ye}${E.randomBytes(8).toString("hex")}`,s="test";await e.setPassword(C,t,s);let n=await e.getPassword(C,t),i=await e.deletePassword(C,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(C,this.getAccount(e));if(!s)return null;let n=this.tryParseKeychainPayload(s);return n||w("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(C,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(C,this.getAccount(e))}tryParseKeychainPayload(e){try{let t=JSON.parse(e);return V(t)?t:null}catch{return null}}},j=class{keychainStorage=null;fileStorage=new L;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[he]?.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()&&(w("keychain","Keychain unavailable. Falling back to file-based credentials."),process.platform==="win32"&&w("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.initPromise=this.initializeStorage()),await this.initPromise)}disableKeychain(){this.shouldForceFileStorage()||w("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 j,h={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}};export{h as a,p as b,De as c,_e as d,c as e,je as f,o as g,U as h,T as i,O as j,Ae as k,be as l,z as m,K as n};
|