@entrydesk/cli 1.8.2 → 1.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import F from"fs";import p from"fs";import xe from"os";import E from"path";import{HTTPError as Ee,TimeoutError as Re}from"ky";import pe,{TimeoutError as he}from"ky";import x from"crypto";import u from"fs";import ce from"path";var le="ENTRYDESK_FORCE_FILE_STORAGE",C="EntryDesk CLI",ge="__entrydesk_keychain_test__",de="profile:",ue=".credentials.key",Z={keychain:!1,permissions:!1,corruptFile:!1,windowsFile:!1};function k(r,e){Z[r]||(Z[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 fe(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 O(r){return o.getProfileCredentialsFile(r)}var M=class{getKeyFilePath(e){return ce.join(o.getProfileDir(e),ue)}loadEncryptionKey(e){let t=this.getKeyFilePath(e);try{if(!u.existsSync(t))return null;let s=u.readFileSync(t);return s.length!==32?null:(this.ensureSecureFilePermissions(t),s)}catch{return null}}createEncryptionKey(e){o.ensureProfileDir(e);let t=this.getKeyFilePath(e),s=x.randomBytes(32);return u.writeFileSync(t,s,{mode:384}),this.ensureSecureFilePermissions(t),s}getOrCreateEncryptionKey(e){let t=this.loadEncryptionKey(e);return t||this.createEncryptionKey(e)}encrypt(e,t){let s=x.randomBytes(16),n=x.createCipheriv("aes-256-gcm",t,s),i=n.update(e,"utf8","hex");i+=n.final("hex");let c=n.getAuthTag();return`${s.toString("hex")}:${c.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"),c=s[2],S=x.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});S.setAuthTag(i);let d=S.update(c,"hex","utf8");return d+=S.final("utf8"),d}tryDecrypt(e,t){try{return this.decrypt(e,t)}catch{return null}}tryParseCredentials(e){try{let t=JSON.parse(e);return Q(t)?t:null}catch{return null}}ensureSecureFilePermissions(e){if(process.platform!=="win32"){try{u.chmodSync(e,384)}catch{k("permissions","Warning: Failed to set secure permissions on credentials file.");return}try{(u.statSync(e).mode&511)!==384&&k("permissions","Warning: Credentials file permissions are too permissive.")}catch{k("permissions","Warning: Failed to verify credentials file permissions.")}}}async getCredentials(e){let t=O(e);try{if(!u.existsSync(t))return null;let s=u.readFileSync(t,"utf-8").trim();if(!s)return null;let n=this.loadEncryptionKey(e),i=n?this.tryDecrypt(s,n):null;if(i){let c=this.tryParseCredentials(i);if(c)return c}return k("corruptFile","Warning: Credentials file is unreadable. Please run `entrydesk login` again."),null}catch{return null}}async setCredentials(e,t){o.ensureProfileDir(e);let s=O(e),n=this.getOrCreateEncryptionKey(e),i=this.encrypt(JSON.stringify(t),n);u.writeFileSync(s,i,{mode:384}),this.ensureSecureFilePermissions(s)}async deleteCredentials(e){let t=O(e);try{u.existsSync(t)&&u.unlinkSync(t)}catch{}}},N=class{keytarModule=null;keytarLoadAttempted=!1;keychainAvailable=null;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar"),s=t&&typeof t=="object"&&"default"in t?t.default:t;this.keytarModule=fe(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${de}${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=`${ge}${x.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||k("corruptFile",`Warning: Keychain entry for profile "${e}" is unreadable.`),n}async setCredentials(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let s=await this.getKeytar();if(!s)throw new Error("Keytar module not available");let n=JSON.stringify(t);await s.setPassword(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 M;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[le]?.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()&&(k("keychain","Keychain unavailable. Falling back to file-based credentials."),process.platform==="win32"&&k("windowsFile","Warning: File-based credentials on Windows may be readable by other users."))}async ensureInitialized(){if(this.shouldForceFileStorage()){this.keychainAvailable=!1,this.keychainStorage=null;return}this.keychainAvailable===null&&(this.initPromise||(this.initPromise=this.initializeStorage()),await this.initPromise)}disableKeychain(){this.shouldForceFileStorage()||k("keychain","Keychain error encountered. Falling back to file-based credentials."),this.keychainAvailable=!1,this.keychainStorage=null}async getKeychainStorage(){return await this.ensureInitialized(),this.shouldForceFileStorage()?null:this.keychainAvailable?this.keychainStorage:null}async getCredentials(e){let t=await this.getKeychainStorage();if(!t)return this.fileStorage.getCredentials(e);try{let n=await t.getCredentials(e);if(n)return n}catch{return this.disableKeychain(),this.fileStorage.getCredentials(e)}let s=await this.fileStorage.getCredentials(e);if(s)try{await t.setCredentials(e,s),await this.fileStorage.deleteCredentials(e)}catch{}return s}async setCredentials(e,t){let s=await this.getKeychainStorage();if(!s){await this.fileStorage.setCredentials(e,t);return}try{await s.setCredentials(e,t),await this.fileStorage.deleteCredentials(e)}catch{this.disableKeychain(),await this.fileStorage.setCredentials(e,t)}}async deleteCredentials(e){let t=await this.getKeychainStorage();if(t)try{await t.deleteCredentials(e)}catch{this.disableKeychain()}await this.fileStorage.deleteCredentials(e)}},g=new j,y={async saveAccessToken(r,e){let t=o.getEffectiveProfileName(e),s=await g.getCredentials(t)||{};s.accessToken=r,await g.setCredentials(t,s)},async getAccessToken(r){let e=o.getEffectiveProfileName(r);return(await g.getCredentials(e))?.accessToken??null},async saveRefreshToken(r,e){let t=o.getEffectiveProfileName(e),s=await g.getCredentials(t)||{};s.refreshToken=r,await g.setCredentials(t,s)},async getRefreshToken(r){let e=o.getEffectiveProfileName(r);return(await g.getCredentials(e))?.refreshToken??null},async saveEmail(r,e){let t=o.getEffectiveProfileName(e),s=await g.getCredentials(t)||{};s.email=r,await g.setCredentials(t,s)},async getEmail(r){let e=o.getEffectiveProfileName(r);return(await g.getCredentials(e))?.email??null},async saveWorkspaceId(r,e){let t=o.getEffectiveProfileName(e),s=await g.getCredentials(t)||{};s.workspaceId=r,await g.setCredentials(t,s)},async getWorkspaceId(r){let e=o.getEffectiveProfileName(r);return(await g.getCredentials(e))?.workspaceId??null},async saveAll(r,e){let t=o.getEffectiveProfileName(e);await g.setCredentials(t,r)},async getAll(r){let e=o.getEffectiveProfileName(r);return g.getCredentials(e)},async clear(r){let e=o.getEffectiveProfileName(r);await g.deleteCredentials(e)},async isLoggedIn(r){let e=o.getEffectiveProfileName(r);return(await g.getCredentials(e))?.accessToken!=null}};var U=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||I(t),D().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=pe.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}async refreshOAuthToken(e){return this.client.post("v1/oauth/token",{json:{grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}}).json()}async revokeOAuthToken(e){await this.client.post("v1/oauth/revoke",{json:{token:e.token,token_type_hint:"refresh_token",client_id:e.clientId}})}async getWorkspaces(e){try{return process.env.DEBUG&&console.log(`[DEBUG] Calling getWorkspaces API: ${this.baseUrl}/v1/workspaces`),await this.client.get("v1/workspaces",{headers:{Authorization:`Bearer ${e}`}}).json()}catch(t){throw process.env.DEBUG&&(console.error("[DEBUG] getWorkspaces error:",t),t instanceof Error&&"cause"in t&&console.error("[DEBUG] Error cause:",t.cause)),t}}async getAgents(e,t){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 he?new TypeError("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,c=new Blob([s.buffer],{type:s.mimeType});return i.append("file",c,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 y.getAll(e);return t?{client:new r(void 0,e),accessToken:t.accessToken,workspaceId:t.workspaceId??null}:null}};import{execFile as ye}from"child_process";import{setTimeout as me}from"timers/promises";import{decodeJwt as we}from"jose";import ke,{HTTPError as ve}from"ky";var $="entrydesk-cli",Pe="offline_access workspaces:read chats:read chats:write chats:delete agents:read agents:write connectors:read connectors:write tools:read tools:execute skills:read skills:write meetings:read meetings:write publishes:read publishes:write calendar:read calendar:write schedules:read schedules:write user:read user:write";function Se(r){return new Promise((e,t)=>{let s=process.platform,n,i;switch(s){case"darwin":n="open",i=[r];break;case"win32":n="cmd",i=["/c","start","",r];break;default:n="xdg-open",i=[r];break}ye(n,i,c=>{c?t(new Error(`Failed to open browser. Please manually visit: ${r}`,{cause:c})):e()})})}async function Qe(r){let e=I(),t=ee(),s=D(),n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;s.ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",console.error("WARNING: SSL certificate validation is disabled globally for this process during the login flow. All connections in this process will skip TLS verification. Only use ENTRYDESK_IGNORE_SSL_ERRORS for local development."));try{let i=ke.create({prefixUrl:e,timeout:3e4,hooks:{beforeError:[a=>(a.request?.headers&&(a.request.headers.delete("authorization"),a.request.headers.delete("Authorization")),a)]}}),c;try{c=await i.post("v1/oauth/device/code",{json:{client_id:$,scope:Pe}}).json()}catch(a){let w=a instanceof Error?a:new Error("Failed to request device code");throw r?.onError?.(w),w}let{device_code:S,user_code:d,expires_in:ie,interval:oe}=c,V=new URL("/oauth/device",t);V.searchParams.set("user_code",d);let Y=V.toString();r?.onDeviceCodeReceived?.(d,Y),r?.onBrowserOpening?.();try{await Se(Y)}catch(a){process.env.DEBUG&&console.error("[DEBUG] Failed to open browser:",a)}r?.onWaitingForAuthorization?.();let q=Math.max(oe,5)*1e3,ae=Date.now()+ie*1e3;for(;Date.now()<ae;){await me(q);try{let a=await i.post("v1/oauth/token",{json:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:S,client_id:$}}).json();r?.onAuthorized?.();let w={};try{w=we(a.access_token)}catch{}return{accessToken:a.access_token,refreshToken:a.refresh_token??void 0,email:w.email||"",scopes:a.scope.split(" ").filter(R=>R.length>0)}}catch(a){if(a instanceof ve){let R;try{let X=await a.response.json();R=X.code||X.error}catch{continue}switch(R){case"authorization_pending":continue;case"slow_down":q+=5e3;continue;case"access_denied":throw new Error("Authorization denied by user",{cause:a});case"expired_token":throw new Error("Device code expired. Please try again.",{cause:a});default:throw new Error(`Authorization failed: ${R||"Unknown error"}`,{cause:a})}}let w=a instanceof Error?a:new Error("Unknown error during authorization");throw r?.onError?.(w),w}}throw new Error("Device code expired. Please try again.")}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}function Ae(){return process.env.ENTRYDESK_SANDBOX==="true"}function z(){if(!Ae())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 m=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Ce(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 be(r,e=300){let s=Ce(r)?.exp;if(typeof s!="number")return!1;let n=Math.floor(Date.now()/1e3);return s-n<=e}async function te(r){let e=r.accessToken;if(!be(e))return e;if(!r.refreshToken)throw await y.clear(),new m("session-expired","Session expired. Please run `entrydesk login` again.");try{let s=await new U().refreshOAuthToken({refreshToken:r.refreshToken,clientId:$});return await y.saveAccessToken(s.access_token),s.refresh_token&&await y.saveRefreshToken(s.refresh_token),s.access_token}catch{throw await y.clear(),new m("session-expired","Session expired. Please run `entrydesk login` again.")}}async function ot(){let r=z();if(r)return r.accessToken;let e=await y.getAll();if(!e?.accessToken)throw new m("not-logged-in","Not logged in. Run `entrydesk login` first.");return te(e)}async function at(){let r=z();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=await y.getAll();if(!e?.accessToken)throw new m("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!e.workspaceId)throw new m("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await te(e),workspaceId:e.workspaceId}}var f=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}};function dt(r){let e=!!process.env.DEBUG;r instanceof f&&(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 m&&(console.error(r.message),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Re&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Ee&&(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 P="default",Te=/^[A-Za-z0-9_-]+$/,L=null;function H(){return E.join(xe.homedir(),".entrydesk")}function se(){return E.join(H(),"profiles")}function ne(){return E.join(H(),"profiles.json")}function K(r){return E.join(se(),r)}function G(r){if(!p.existsSync(r))p.mkdirSync(r,{mode:448,recursive:!0});else try{p.chmodSync(r,448)}catch{}}function _e(){G(H())}function W(){G(se())}function Ue(){let r=ne();try{if(!p.existsSync(r))return null;let e=p.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function b(r){_e();let e=ne();p.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{p.chmodSync(e,384)}catch{}}function Ie(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||P;return e.length===0&&e.push(P),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function v(){let r=Ue();if(!r){let t={currentProfile:P,profiles:[P]};return b(t),W(),_(P),t}let e=Ie(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&b(e),W(),e}function A(r){if(!r)throw new f("Profile name is required.");if(!Te.test(r))throw new f("Invalid profile name. Use letters, numbers, dash, or underscore.")}function T(r,e){if(!r.profiles.includes(e))throw new f(`Profile not found: ${e}`)}function re(r,e){if(r.profiles.includes(e))throw new f(`Profile already exists: ${e}`)}function _(r){W(),G(K(r))}var o={DEFAULT_PROFILE:P,setOverrideProfile(r){L=r},getOverrideProfile(){return L},getProfileDir(r){return K(r)},getProfileConfigFile(r){return E.join(o.getProfileDir(r),"config.json")},getProfileCredentialsFile(r){return E.join(o.getProfileDir(r),"credentials.json")},getProfileNames(){return[...v().profiles]},getProfileCount(){return o.getProfileNames().length},getCurrentProfileName(){return v().currentProfile},getEffectiveProfileName(r){let e=v(),t=r||L||e.currentProfile;return A(t),T(e,t),t},ensureProfileExists(r){let e=v();A(r),T(e,r)},createProfile(r){A(r);let e=v();re(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};b(t),_(r)},deleteProfile(r){A(r);let e=v();if(T(e,r),e.profiles.length===1)throw new f("Cannot delete the last profile.");let t=e.profiles.filter(i=>i!==r),s=e.currentProfile;s===r&&(s=t.includes(P)?P:t[0]),b({currentProfile:s,profiles:t});try{p.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){A(r),A(e);let t=v();T(t,r),re(t,e);let s=K(r),n=K(e);if(p.existsSync(s))try{p.renameSync(s,n)}catch(d){throw new f("Failed to rename profile directory.",1,d)}else _(e);let i=t.profiles.map(d=>d===r?e:d),c=t.currentProfile===r?e:t.currentProfile;return b({currentProfile:c,profiles:i}),{currentProfile:c}},setCurrentProfile(r){A(r);let e=v();T(e,r);let t={currentProfile:r,profiles:e.profiles};b(t),_(r)},ensureProfileDir:_};function De(r){let e=o.getEffectiveProfileName(r);return o.getProfileConfigFile(e)}function l(r){let e=De(r);try{if(!F.existsSync(e))return{};let t=F.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function h(r,e){let t=o.getEffectiveProfileName(e);o.ensureProfileDir(t);let s=o.getProfileConfigFile(t);F.writeFileSync(s,JSON.stringify(r,null,2),{mode:384});try{F.chmodSync(s,384)}catch{}}var J={getApiUrl(r){return l(r).apiUrl??null},setApiUrl(r,e){let t=l(e);t.apiUrl=r,h(t,e)},clearApiUrl(r){let e=l(r);delete e.apiUrl,h(e,r)},getHubUrl(r){return l(r).hubUrl??null},setHubUrl(r,e){let t=l(e);t.hubUrl=r,h(t,e)},getAll(r){return l(r)},setAll(r,e){h(r,e)},set(r,e,t){let s=l(t);s[r]=e,h(s,t)},get(r,e){return l(e)[r]},unset(r,e){let t=l(e);delete t[r],h(t,e)},getDefaultModel(r){return l(r).model?.default??null},setDefaultModel(r,e){let t=l(e);t.model={...t.model,default:r},h(t,e)},getDefaultConnectorIds(r){return l(r).connectors?.defaults??null},setDefaultConnectorIds(r,e){let t=l(e);t.connectors={...t.connectors,defaults:r},h(t,e)},getCapabilities(r){return l(r).capabilities??null},setCapabilities(r,e){let t=l(e);t.capabilities={...t.capabilities,...r},h(t,e)},getLocalTools(r){return l(r).localTools??null},setLocalTools(r,e){let t=l(e);t.localTools={...t.localTools,...r},h(t,e)}};var $e="https://entrydesk-api.dcard.io",Ke="https://entrydesk.dcard.io",Fe=3100,Be=300*1e3;function B(r){return{apiUrl:J.getApiUrl(r)||process.env.ENTRYDESK_API_URL||$e,hubUrl:J.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Ke,mcp:{httpPort:Fe},auth:{loginTimeout:Be,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function I(r){return B(r).apiUrl}function ee(r){return B(r).hubUrl}function St(){return B().mcp}function D(){return B().auth}export{$ as a,Qe as b,y as c,m as d,be as e,te as f,ot as g,at as h,f as i,dt as j,o as k,J as l,B as m,I as n,ee as o,St as p,D as q,U as r};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{m as a,n as b,o as c,p as d,q as e}from"./chunk-5JR5ME2B.js";export{b as getApiUrl,e as getAuthConfig,a as getConfig,c as getHubUrl,d as getMcpConfig};
|