@entrydesk/cli 1.9.2 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import F from"fs";import p from"fs";import Te from"os";import E from"path";import{HTTPError as Re,TimeoutError as xe}from"ky";import he,{TimeoutError as ye}from"ky";import x from"crypto";import u from"fs";import le from"path";var ge="ENTRYDESK_FORCE_FILE_STORAGE",A="EntryDesk CLI",de="__entrydesk_keychain_test__",ue="profile:",fe=".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 pe(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 N=class{getKeyFilePath(e){return le.join(o.getProfileDir(e),fe)}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],P=x.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});P.setAuthTag(i);let d=P.update(c,"hex","utf8");return d+=P.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{}}},M=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=pe(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${ue}${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=`${de}${x.randomBytes(8).toString("hex")}`,s="test";await e.setPassword(A,t,s);let n=await e.getPassword(A,t),i=await e.deletePassword(A,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(A,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(A,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(A,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 N;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[ge]?.toLowerCase()==="true"}async initializeStorage(){if(this.shouldForceFileStorage()){this.keychainAvailable=!1,this.keychainStorage=null;return}try{let e=new M,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 K=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||I(t),U().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=he.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,s){let n={limit:s?.limit??100};return s?.nextKey&&(n.nextKey=s.nextKey),s?.search&&(n.search=s.search),await this.client.get(`v1/workspaces/${t}/availableAgents`,{headers:{Authorization:`Bearer ${e}`},searchParams:n}).json()}async createAgent(e,t,s){return await this.client.post(`v1/workspaces/${t}/agents`,{headers:{Authorization:`Bearer ${e}`},json:s}).json()}async updateAgent(e,t,s,n){await this.client.put(`v1/workspaces/${t}/agents/${s}`,{headers:{Authorization:`Bearer ${e}`},json:n})}async deleteAgent(e,t,s){await this.client.delete(`v1/workspaces/${t}/agents/${s}`,{headers:{Authorization:`Bearer ${e}`}})}async 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 ye?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}};function me(){return process.env.ENTRYDESK_SANDBOX==="true"}function z(){if(!me())return null;let r=process.env.ENTRYDESK_SANDBOX_ACCESS_TOKEN?.trim(),e=process.env.ENTRYDESK_SANDBOX_WORKSPACE_ID?.trim();if(!r||!e){let t=[];throw r||t.push("ENTRYDESK_SANDBOX_ACCESS_TOKEN"),e||t.push("ENTRYDESK_SANDBOX_WORKSPACE_ID"),new Error(`Sandbox mode enabled but missing credentials: ${t.join(", ")}`)}return{accessToken:r,workspaceId:e}}function ee(){let r=process.env.ENTRYDESK_TOKEN?.trim();if(!r)return null;let e=process.env.ENTRYDESK_WORKSPACE_ID?.trim();if(!e)throw new Error("ENTRYDESK_TOKEN is set but ENTRYDESK_WORKSPACE_ID is missing. Both are required for PAT authentication.");return{accessToken:r,workspaceId:e}}import{execFile as we}from"child_process";import{setTimeout as ke}from"timers/promises";import{decodeJwt as ve}from"jose";import Se,{HTTPError as Pe}from"ky";var D="entrydesk-cli",Ce="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 Ae(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}we(n,i,c=>{c?t(new Error(`Failed to open browser. Please manually visit: ${r}`,{cause:c})):e()})})}async function tt(r){let e=I(),t=te(),s=U(),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=Se.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:D,scope:Ce}}).json()}catch(a){let w=a instanceof Error?a:new Error("Failed to request device code");throw r?.onError?.(w),w}let{device_code:P,user_code:d,expires_in:oe,interval:ae}=c,J=new URL("/oauth/device",t);J.searchParams.set("user_code",d);let V=J.toString();r?.onDeviceCodeReceived?.(d,V),r?.onBrowserOpening?.();try{await Ae(V)}catch(a){process.env.DEBUG&&console.error("[DEBUG] Failed to open browser:",a)}r?.onWaitingForAuthorization?.();let q=Math.max(ae,5)*1e3,ce=Date.now()+oe*1e3;for(;Date.now()<ce;){await ke(q);try{let a=await i.post("v1/oauth/token",{json:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:P,client_id:D}}).json();r?.onAuthorized?.();let w={};try{w=ve(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 Pe){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}}var m=class extends Error{code;constructor(e,t){super(t),this.code=e}};function be(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 Ee(r,e=300){let s=be(r)?.exp;if(typeof s!="number")return!1;let n=Math.floor(Date.now()/1e3);return s-n<=e}async function re(r){let e=r.accessToken;if(!Ee(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 K().refreshOAuthToken({refreshToken:r.refreshToken,clientId:D});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 at(){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 re(e)}async function ct(){let r=z();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=ee();if(e)return e;let t=await y.getAll();if(!t?.accessToken)throw new m("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!t.workspaceId)throw new m("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await re(t),workspaceId:t.workspaceId}}var f=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}};function ut(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 xe&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Re&&(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 S="default",_e=/^[A-Za-z0-9_-]+$/,L=null;function H(){return E.join(Te.homedir(),".entrydesk")}function ne(){return E.join(H(),"profiles")}function ie(){return E.join(H(),"profiles.json")}function $(r){return E.join(ne(),r)}function G(r){if(!p.existsSync(r))p.mkdirSync(r,{mode:448,recursive:!0});else try{p.chmodSync(r,448)}catch{}}function Ke(){G(H())}function W(){G(ne())}function Ie(){let r=ie();try{if(!p.existsSync(r))return null;let e=p.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function b(r){Ke();let e=ie();p.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{p.chmodSync(e,384)}catch{}}function Ue(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||S;return e.length===0&&e.push(S),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function v(){let r=Ie();if(!r){let t={currentProfile:S,profiles:[S]};return b(t),W(),_(S),t}let e=Ue(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&b(e),W(),e}function C(r){if(!r)throw new f("Profile name is required.");if(!_e.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 se(r,e){if(r.profiles.includes(e))throw new f(`Profile already exists: ${e}`)}function _(r){W(),G($(r))}var o={DEFAULT_PROFILE:S,setOverrideProfile(r){L=r},getOverrideProfile(){return L},getProfileDir(r){return $(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 C(t),T(e,t),t},ensureProfileExists(r){let e=v();C(r),T(e,r)},createProfile(r){C(r);let e=v();se(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};b(t),_(r)},deleteProfile(r){C(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(S)?S:t[0]),b({currentProfile:s,profiles:t});try{p.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){C(r),C(e);let t=v();T(t,r),se(t,e);let s=$(r),n=$(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){C(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 Y={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",Fe="https://entrydesk.dcard.io",Be=3100,Oe=300*1e3;function B(r){return{apiUrl:Y.getApiUrl(r)||process.env.ENTRYDESK_API_URL||$e,hubUrl:Y.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Fe,mcp:{httpPort:Be},auth:{loginTimeout:Oe,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function I(r){return B(r).apiUrl}function te(r){return B(r).hubUrl}function Ct(){return B().mcp}function U(){return B().auth}export{D as a,tt as b,y as c,m as d,Ee as e,re as f,at as g,ct as h,f as i,ut as j,o as k,Y as l,B as m,I as n,te as o,Ct as p,U as q,K as r};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{m as a,n as b,o as c,p as d,q as e}from"./chunk-3IRLOP3O.js";export{b as getApiUrl,e as getAuthConfig,a as getConfig,c as getHubUrl,d as getMcpConfig};
2
+ import{m as a,n as b,o as c,p as d,q as e}from"./chunk-TXYEAHOW.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 tn,b as on,c as $e,d as qe,e as nn,f as sn,g as lt,h as fe,i as Et,j as ke,k as J,l as oe,m as Ye,r as G}from"./chunk-3IRLOP3O.js";import{render as Wi}from"ink";function So(){console.log(`
2
+ import{a as tn,b as on,c as $e,d as qe,e as nn,f as sn,g as lt,h as fe,i as Et,j as ke,k as J,l as oe,m as Ye,r as G}from"./chunk-TXYEAHOW.js";import{render as Wi}from"ink";function So(){console.log(`
3
3
  Usage: entrydesk agents [list|create|update|delete] [options]
4
4
 
5
5
  Commands:
@@ -19,10 +19,15 @@ Create/Update Options:
19
19
  --tools prefix__tool1,prefix__tool2
20
20
  --icon-id <iconId>
21
21
 
22
+ List Options:
23
+ --limit <number> Max agents per page; also page size for --all (default: 100)
24
+ --next-key <cursor> Fetch next page using cursor
25
+ --all Fetch all agents (auto-paginate)
26
+
22
27
  Flags:
23
28
  --json Output JSON
24
- `)}function rn(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 Hs(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),So(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:rn(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function an(e){try{if(e.help){So();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new G;if(n==="create"){let a=Hs(e),l=await r.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=await r.getAgent(o,s,a),d={name:e.name??l.name,description:e.description??l.description,systemPrompt:e.systemPrompt??l.systemPrompt??"",modelId:e.modelId??l.model?.id??"",connectorIds:e.connectorIds??l.connectors?.map(x=>x.id)??[],capabilities:e.capabilities?rn(e.capabilities):l.capabilities??[],conversationStarters:e.conversationStarters??l.conversationStarters??[],tools:e.tools??l.tools??[],iconId:e.iconId??l.iconId};await r.updateAgent(o,s,a,d),console.log(`Updated agent: ${a}`);return}if(n==="delete"){let a=e.agentId;if(!a)throw new Error("Missing agentId for delete command");await r.deleteAgent(o,s,a),console.log(`Deleted agent: ${a}`);return}n!=="list"&&(console.error(`Unknown agents command: ${n}`),So(),process.exit(1));let{agents:i}=await r.getAgents(o,s);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No agents found in this workspace.");return}console.log(`Available Agents (${i.length}):
25
- `);for(let a of i)console.log(` ${a.name} (${a.visibility})`),a.description&&console.log(` ${a.description.slice(0,80)}`),console.log(` ID: ${a.id}`),console.log("")}catch(t){ke(t)}}function Ks(){console.log(`
29
+ `)}function an(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){console.log(`Available Agents (${e.length}):
30
+ `);for(let t of e){if(console.log(` ${t.name} (${t.visibility})`),t.description){let o=t.description.length>80?`${t.description.slice(0,80)}...`:t.description;console.log(` ${o}`)}console.log(` ID: ${t.id}`),console.log("")}}function Ks(e){return(!e.name||!e.description||!e.systemPrompt||!e.modelId)&&(console.error("Missing required fields for agent create/update."),So(),process.exit(1)),{name:e.name,description:e.description,systemPrompt:e.systemPrompt,modelId:e.modelId,connectorIds:e.connectorIds??[],capabilities:an(e.capabilities),conversationStarters:e.conversationStarters??[],tools:e.tools,iconId:e.iconId}}async function ln(e){try{if(e.help){So();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new G;if(n==="create"){let l=Ks(e),d=await r.createAgent(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created agent: ${d.name}`),console.log(` ID: ${d.id}`);return}if(n==="update"){let l=e.agentId;if(!l)throw new Error("Missing agentId for update command");let d=await r.getAgent(o,s,l),b={name:e.name??d.name,description:e.description??d.description,systemPrompt:e.systemPrompt??d.systemPrompt??"",modelId:e.modelId??d.model?.id??"",connectorIds:e.connectorIds??d.connectors?.map(C=>C.id)??[],capabilities:e.capabilities?an(e.capabilities):d.capabilities??[],conversationStarters:e.conversationStarters??d.conversationStarters??[],tools:e.tools??d.tools??[],iconId:e.iconId??d.iconId};await r.updateAgent(o,s,l,b),console.log(`Updated agent: ${l}`);return}if(n==="delete"){let l=e.agentId;if(!l)throw new Error("Missing agentId for delete command");await r.deleteAgent(o,s,l),console.log(`Deleted agent: ${l}`);return}if(n!=="list"&&(console.error(`Unknown agents command: ${n}`),So(),process.exit(1)),e.all&&e.nextKey&&(console.error("Cannot use --all and --next-key together."),process.exit(1)),e.all){let d=[],b;for(let C=0;;C++){C>=100&&(console.error("Reached maximum page limit (100). Use --limit and --next-key for manual pagination."),process.exit(1));let x=await r.getAgents(o,s,{limit:e.limit??100,nextKey:b});if(d.push(...x.agents),b=x.nextKey,!b)break}if(e.json){console.log(JSON.stringify({agents:d}));return}if(d.length===0){console.log("No agents found in this workspace.");return}rn(d);return}let{agents:i,nextKey:a}=await r.getAgents(o,s,{limit:e.limit,nextKey:e.nextKey});if(e.json){console.log(JSON.stringify({agents:i,nextKey:a}));return}if(i.length===0){console.log("No agents found in this workspace.");return}rn(i),a&&console.log(`Next page: --next-key ${a}`)}catch(t){ke(t)}}function zs(){console.log(`
26
31
  Usage: entrydesk budget [get|set|clear] [options]
27
32
 
28
33
  Commands:
@@ -32,7 +37,7 @@ Commands:
32
37
 
33
38
  Flags:
34
39
  --json Output JSON
35
- `)}async function ln(e){try{if(e.help){Ks();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",r=new G;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await r.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await r.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let i=await r.getBudget(o,s);if(e.json){console.log(JSON.stringify(i));return}if(i.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${i.budget}`)}catch(t){ke(t)}}import{render as Hr}from"ink";import{v4 as po}from"uuid";import{exec as zs}from"child_process";import qs from"fs";import Xe from"fs/promises";import cn from"os";import To from"path";import{promisify as Ys}from"util";import{glob as Xs}from"glob";var Zs=Ys(zs),Qs=`## Filesystem Tool Instructions
40
+ `)}async function cn(e){try{if(e.help){zs();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"get",r=new G;if(n==="set"){let a=e.configKey;if(!a)throw new Error("Missing budget amount for set command");let l=parseFloat(a);if(isNaN(l)||l<0)throw new Error("Budget must be a positive number");let d=await r.updateBudget(o,s,a);if(e.json){console.log(JSON.stringify(d));return}console.log(`Budget updated: $${a}`);return}if(n==="clear"){let a=await r.updateBudget(o,s,null);if(e.json){console.log(JSON.stringify(a));return}console.log("Budget cleared.");return}if(n!=="get")throw new Error(`Unknown budget command: ${n}`);let i=await r.getBudget(o,s);if(e.json){console.log(JSON.stringify(i));return}if(i.budget===null){console.log("No budget set for this workspace.");return}console.log(`Current workspace budget: $${i.budget}`)}catch(t){ke(t)}}import{render as Kr}from"ink";import{v4 as po}from"uuid";import{exec as qs}from"child_process";import Ys from"fs";import Xe from"fs/promises";import un from"os";import To from"path";import{promisify as Xs}from"util";import{glob as Zs}from"glob";var Qs=Xs(qs),er=`## Filesystem Tool Instructions
36
41
 
37
42
  You have access to filesystem tools that allow you to interact with the user's local filesystem.
38
43
 
@@ -56,24 +61,24 @@ You have access to filesystem tools that allow you to interact with the user's l
56
61
  - Search results are limited to prevent overwhelming responses
57
62
  - Execute Command has a default timeout of 30 seconds (max 5 minutes)
58
63
  - The current working directory is: ${process.cwd()}
59
- - The user's home directory is: ${cn.homedir()}
60
- `,er=[{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:Qs,tools:er}}function Je(e){return e.startsWith("~/")?To.join(cn.homedir(),e.slice(2)):e}function Zt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
64
+ - The user's home directory is: ${un.homedir()}
65
+ `,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 dn(){return{name:"filesystem",systemPrompt:er,tools:tr}}function Je(e){return e.startsWith("~/")?To.join(un.homedir(),e.slice(2)):e}function Zt(e,t=1e5){return e.length<=t?e:e.slice(0,t)+`
61
66
 
62
- ... (truncated, ${e.length-t} more characters)`}async function dn(e,t){try{switch(e){case"filesystem__read_file":{let o=Je(t.path),s=await Xe.readFile(o,"utf-8");return{success:!0,result:Zt(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let r=Je(n);try{let i=await Xe.readFile(r,"utf-8");s[n]=Zt(i,5e4)}catch(i){s[n]={error:i instanceof Error?i.message:String(i)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Je(t.path),s=t.content;return await Xe.mkdir(To.dirname(o),{recursive:!0}),await Xe.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Je(t.path);return await Xe.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Je(t.path);return{success:!0,result:(await Xe.readdir(o,{withFileTypes:!0})).map(r=>({name:r.name,type:r.isDirectory()?"directory":r.isFile()?"file":r.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Je(t.cwd):process.cwd(),n=await Xs(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=Je(t.path),s=await Xe.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=Je(t.source),s=Je(t.destination);return await Xe.mkdir(To.dirname(s),{recursive:!0}),await Xe.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Je(t.cwd):process.cwd(),n=Math.min(t.timeout||3e4,3e5);if(!qs.existsSync(s))return{success:!1,error:`Working directory does not exist: ${s}`};let{stdout:r,stderr:i}=await Zs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Zt(r,5e4),stderr:Zt(i,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function Io(e){return e.startsWith("filesystem__")}function fn(){return[un()]}function Qt(){return fn().flatMap(e=>e.tools)}function eo(){return fn().map(e=>e.systemPrompt).filter(Boolean).join(`
67
+ ... (truncated, ${e.length-t} more characters)`}async function fn(e,t){try{switch(e){case"filesystem__read_file":{let o=Je(t.path),s=await Xe.readFile(o,"utf-8");return{success:!0,result:Zt(s)}}case"filesystem__read_multiple_files":{let o=t.paths.slice(0,10),s={};for(let n of o){let r=Je(n);try{let i=await Xe.readFile(r,"utf-8");s[n]=Zt(i,5e4)}catch(i){s[n]={error:i instanceof Error?i.message:String(i)}}}return{success:!0,result:s}}case"filesystem__write_file":{let o=Je(t.path),s=t.content;return await Xe.mkdir(To.dirname(o),{recursive:!0}),await Xe.writeFile(o,s,"utf-8"),{success:!0,result:{written:o}}}case"filesystem__create_directory":{let o=Je(t.path);return await Xe.mkdir(o,{recursive:!0}),{success:!0,result:{created:o}}}case"filesystem__list_directory":{let o=Je(t.path);return{success:!0,result:(await Xe.readdir(o,{withFileTypes:!0})).map(r=>({name:r.name,type:r.isDirectory()?"directory":r.isFile()?"file":r.isSymbolicLink()?"symlink":"other"}))}}case"filesystem__search_files":{let o=t.pattern,s=t.cwd?Je(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=Je(t.path),s=await Xe.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=Je(t.source),s=Je(t.destination);return await Xe.mkdir(To.dirname(s),{recursive:!0}),await Xe.rename(o,s),{success:!0,result:{moved:{from:o,to:s}}}}case"filesystem__execute_command":{let o=t.command,s=t.cwd?Je(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:r,stderr:i}=await Qs(o,{cwd:s,timeout:n,maxBuffer:10*1024*1024});return{success:!0,result:{stdout:Zt(r,5e4),stderr:Zt(i,5e4)}}}default:return{success:!1,error:`Unknown tool: ${e}`}}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}function Io(e){return e.startsWith("filesystem__")}function pn(){return[dn()]}function Qt(){return pn().flatMap(e=>e.tools)}function eo(){return pn().map(e=>e.systemPrompt).filter(Boolean).join(`
63
68
 
64
- `)}function Ze(e){return Io(e)}async function to(e,t){return Io(e)?dn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as ve,Text as V,useInput as Mo}from"ink";import Jo from"ink-spinner";import{useCallback as Go,useEffect as fo,useRef as ss,useState as jr}from"react";import{Box as oo,Text as _t}from"ink";import{jsx as no,jsxs as Dt}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:r,pageSize:i=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),x=Math.max(1,i),C=Math.floor(t/x)*x,b=Math.min(e.length,C+x),T=e.slice(C,b);return Dt(oo,{flexDirection:"column",marginBottom:1,children:[no(_t,{bold:!0,color:"cyan",children:r}),no(oo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:T.map((h,y)=>{let j=C+y===t,z=o?.has(h.id),X=pn(h.name,d),ie=h.description?pn(h.description,Math.max(0,d-l)):"",q=s?" ".repeat(l):"";return Dt(oo,{paddingX:1,flexDirection:"column",children:[Dt(oo,{children:[s&&no(_t,{color:z?"green":"gray",children:z?"[\u2713] ":"[ ] "}),no(_t,{backgroundColor:j?"cyan":void 0,color:j?"black":z?"green":"white",bold:!0,children:X})]}),ie&&Dt(_t,{dimColor:!0,children:[q,"\xB7 ",ie]})]},h.id)})}),Dt(_t,{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>x?` \xB7 Showing ${C+1}-${b} of ${e.length}`:""]})]})}import{Box as vo,Text as Ot}from"ink";import{jsx as Lt,jsxs as Ao}from"react/jsx-runtime";function gn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:Ao(vo,{flexDirection:"column",marginBottom:1,children:[Lt(vo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let r=n===t,i=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Ao(vo,{paddingX:1,children:[Ao(Ot,{backgroundColor:r?"cyan":void 0,color:r?"black":"cyan",bold:r,children:["/",s.name]}),Lt(Ot,{dimColor:!0,children:i}),Lt(Ot,{children:" - "}),Lt(Ot,{color:r?"white":"gray",children:s.description})]},s.name)})}),Lt(Ot,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as tr,Text as hn,useInput as or,useStdout as nr}from"ink";import{useCallback as yn,useEffect as wn,useMemo as Po,useRef as kn,useState as bn}from"react";import{jsx as _o}from"react/jsx-runtime";function so(e,t){return e<0?0:e>t?t:e}function No(e){return Array.from(e)}function ro(e){return/\s/.test(e)}function Eo(e,t){let o=t;for(;o>0&&ro(e[o-1]??"");)o-=1;for(;o>0&&!ro(e[o-1]??"");)o-=1;return o}function xn(e,t){let o=t;for(;o<e.length&&ro(e[o]??"");)o+=1;for(;o<e.length&&!ro(e[o]??"");)o+=1;return o}function sr(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((i,a)=>{if(i===`
65
- `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(i)}),t.push(s);let r=t.map(i=>i.length);return{lines:t,lineStarts:o,lineLengths:r}}function Cn(e,t,o){for(let n=0;n<t.length;n+=1){let r=t[n]??0,i=o[n]??0,a=r+i;if(e<=a)return{row:n,col:e-r}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var rr=2;function $n({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:r=0,multiline:i=!1}){let[a,l]=bn(()=>No(e).length),d=kn(null),[x,C]=bn(0),b=kn(null),{stdout:T}=nr(),h=Po(()=>No(e),[e]),{lines:y,lineStarts:v,lineLengths:j}=Po(()=>sr(h),[h]),{row:z,col:X}=Po(()=>Cn(a,v,j),[a,v,j]),ie=Math.max(1,(T?.columns??80)-r);wn(()=>{d.current!==e?(l(h.length),b.current=null):l(U=>so(U,h.length)),d.current=e},[e,h.length]),wn(()=>{C(U=>{let A=U;X<A?A=X:X>=A+ie&&(A=X-ie+1);let N=j[z]??0,L=X===N?N+1:N,W=Math.max(0,L-ie);return A>W&&(A=W),A<0&&(A=0),A})},[ie,X,z,j]);let q=yn((U,A)=>{d.current=U,t(U),l(A),b.current=null},[t]),Ce=yn(async(U,A)=>{if(!n)return;let{row:N,col:L}=Cn(a,v,j),W=y[N]??[],E=j[N]??0,ge=y.length>1;if(i&&(A.meta&&A.return||A.ctrl&&U==="j"||A.shift&&A.return)){let _=[...h.slice(0,a),`
66
- `,...h.slice(a)].join("");q(_,a+1);return}if(A.return){o(e);return}if(A.leftArrow){A.ctrl||A.meta?(L===0&&N>0?l(v[N]-1):l(v[N]+Eo(W,L)),b.current=null):(L===0&&N>0?l(v[N]-1):l(_=>so(_-1,h.length)),b.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(L>=E&&N<y.length-1?l(v[N+1]):l(v[N]+xn(W,L)),b.current=null):(L>=E&&N<y.length-1?l(v[N+1]):l(_=>so(_+1,h.length)),b.current=null);return}if(i&&ge&&A.upArrow){let _=b.current??L,p=Math.max(0,N-1),re=Math.min(_,j[p]??0);l((v[p]??0)+re),b.current=_;return}if(i&&ge&&A.downArrow){let _=b.current??L,p=Math.min(y.length-1,N+1),re=Math.min(_,j[p]??0);l((v[p]??0)+re),b.current=_;return}if(A.ctrl){if(U==="a"){l(v[N]??0),b.current=null;return}if(U==="e"){l((v[N]??0)+E),b.current=null;return}if(U==="u"){if(L>0){let _=v[N]??0,p=[...h.slice(0,_),...h.slice(a)].join("");q(p,_)}return}if(U==="k"){if(L<E){let _=(v[N]??0)+E,p=[...h.slice(0,a),...h.slice(_)].join("");q(p,a)}return}if(U==="w"){if(L===0&&N>0){let p=[...h.slice(0,a-1),...h.slice(a)].join("");q(p,a-1);return}let _=Eo(W,L);if(_!==L){let p=(v[N]??0)+_,re=[...h.slice(0,p),...h.slice(a)].join("");q(re,p)}return}if(U==="d"){if(a<h.length){let _=[...h.slice(0,a),...h.slice(a+1)].join("");q(_,a)}return}return}if(A.meta){U==="b"?(L===0&&N>0?l(v[N]-1):l(v[N]+Eo(W,L)),b.current=null):U==="f"&&(L>=E&&N<y.length-1?l(v[N+1]):l(v[N]+xn(W,L)),b.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let _=[...h.slice(0,a-1),...h.slice(a)].join("");q(_,a-1);return}if(!(A.tab||A.escape)&&U.length>0){let _=i?U.replace(/\r\n/g,`
69
+ `)}function Ze(e){return Io(e)}async function to(e,t){return Io(e)?fn(e,t):{success:!1,error:`Unknown client tool: ${e}`}}import{Box as ve,Text as V,useInput as Bo}from"ink";import Jo from"ink-spinner";import{useCallback as Go,useEffect as fo,useRef as rs,useState as Fr}from"react";import{Box as oo,Text as _t}from"ink";import{jsx as no,jsxs as Dt}from"react/jsx-runtime";function mn(e,t){return e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function gn({items:e,activeIndex:t,selectedIds:o,multiSelect:s=!1,visible:n,title:r,pageSize:i=10}){if(!n||e.length===0)return null;let a=process.stdout.columns??80,l=s?4:0,d=Math.max(20,a-2-2-l),b=Math.max(1,i),C=Math.floor(t/b)*b,x=Math.min(e.length,C+b),T=e.slice(C,x);return Dt(oo,{flexDirection:"column",marginBottom:1,children:[no(_t,{bold:!0,color:"cyan",children:r}),no(oo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:T.map((h,y)=>{let j=C+y===t,z=o?.has(h.id),X=mn(h.name,d),ie=h.description?mn(h.description,Math.max(0,d-l)):"",q=s?" ".repeat(l):"";return Dt(oo,{paddingX:1,flexDirection:"column",children:[Dt(oo,{children:[s&&no(_t,{color:z?"green":"gray",children:z?"[\u2713] ":"[ ] "}),no(_t,{backgroundColor:j?"cyan":void 0,color:j?"black":z?"green":"white",bold:!0,children:X})]}),ie&&Dt(_t,{dimColor:!0,children:[q,"\xB7 ",ie]})]},h.id)})}),Dt(_t,{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>b?` \xB7 Showing ${C+1}-${x} of ${e.length}`:""]})]})}import{Box as vo,Text as Ot}from"ink";import{jsx as Lt,jsxs as Ao}from"react/jsx-runtime";function hn({suggestions:e,activeIndex:t,visible:o}){return!o||e.length===0?null:Ao(vo,{flexDirection:"column",marginBottom:1,children:[Lt(vo,{borderStyle:"single",borderColor:"gray",flexDirection:"column",children:e.map((s,n)=>{let r=n===t,i=s.aliases.length>0?` (${s.aliases.join(", ")})`:"";return Ao(vo,{paddingX:1,children:[Ao(Ot,{backgroundColor:r?"cyan":void 0,color:r?"black":"cyan",bold:r,children:["/",s.name]}),Lt(Ot,{dimColor:!0,children:i}),Lt(Ot,{children:" - "}),Lt(Ot,{color:r?"white":"gray",children:s.description})]},s.name)})}),Lt(Ot,{dimColor:!0,children:"\u2191\u2193 Navigate \xB7 Tab/Enter Select \xB7 Esc Cancel"})]})}import{Box as or,Text as yn,useInput as nr,useStdout as sr}from"ink";import{useCallback as wn,useEffect as kn,useMemo as Po,useRef as xn,useState as bn}from"react";import{jsx as _o}from"react/jsx-runtime";function so(e,t){return e<0?0:e>t?t:e}function No(e){return Array.from(e)}function ro(e){return/\s/.test(e)}function Eo(e,t){let o=t;for(;o>0&&ro(e[o-1]??"");)o-=1;for(;o>0&&!ro(e[o-1]??"");)o-=1;return o}function Cn(e,t){let o=t;for(;o<e.length&&ro(e[o]??"");)o+=1;for(;o<e.length&&!ro(e[o]??"");)o+=1;return o}function rr(e){let t=[],o=[],s=[],n=0;o.push(0),e.forEach((i,a)=>{if(i===`
70
+ `){t.push(s),s=[],n=a+1,o.push(n);return}s.push(i)}),t.push(s);let r=t.map(i=>i.length);return{lines:t,lineStarts:o,lineLengths:r}}function $n(e,t,o){for(let n=0;n<t.length;n+=1){let r=t[n]??0,i=o[n]??0,a=r+i;if(e<=a)return{row:n,col:e-r}}let s=Math.max(0,t.length-1);return{row:s,col:o[s]??0}}var ir=2;function Sn({value:e,onChange:t,onSubmit:o,onPaste:s,focus:n=!0,leadingOffset:r=0,multiline:i=!1}){let[a,l]=bn(()=>No(e).length),d=xn(null),[b,C]=bn(0),x=xn(null),{stdout:T}=sr(),h=Po(()=>No(e),[e]),{lines:y,lineStarts:v,lineLengths:j}=Po(()=>rr(h),[h]),{row:z,col:X}=Po(()=>$n(a,v,j),[a,v,j]),ie=Math.max(1,(T?.columns??80)-r);kn(()=>{d.current!==e?(l(h.length),x.current=null):l(U=>so(U,h.length)),d.current=e},[e,h.length]),kn(()=>{C(U=>{let A=U;X<A?A=X:X>=A+ie&&(A=X-ie+1);let N=j[z]??0,L=X===N?N+1:N,M=Math.max(0,L-ie);return A>M&&(A=M),A<0&&(A=0),A})},[ie,X,z,j]);let q=wn((U,A)=>{d.current=U,t(U),l(A),x.current=null},[t]),Ce=wn(async(U,A)=>{if(!n)return;let{row:N,col:L}=$n(a,v,j),M=y[N]??[],E=j[N]??0,ge=y.length>1;if(i&&(A.meta&&A.return||A.ctrl&&U==="j"||A.shift&&A.return)){let _=[...h.slice(0,a),`
71
+ `,...h.slice(a)].join("");q(_,a+1);return}if(A.return){o(e);return}if(A.leftArrow){A.ctrl||A.meta?(L===0&&N>0?l(v[N]-1):l(v[N]+Eo(M,L)),x.current=null):(L===0&&N>0?l(v[N]-1):l(_=>so(_-1,h.length)),x.current=null);return}if(A.rightArrow){A.ctrl||A.meta?(L>=E&&N<y.length-1?l(v[N+1]):l(v[N]+Cn(M,L)),x.current=null):(L>=E&&N<y.length-1?l(v[N+1]):l(_=>so(_+1,h.length)),x.current=null);return}if(i&&ge&&A.upArrow){let _=x.current??L,p=Math.max(0,N-1),re=Math.min(_,j[p]??0);l((v[p]??0)+re),x.current=_;return}if(i&&ge&&A.downArrow){let _=x.current??L,p=Math.min(y.length-1,N+1),re=Math.min(_,j[p]??0);l((v[p]??0)+re),x.current=_;return}if(A.ctrl){if(U==="a"){l(v[N]??0),x.current=null;return}if(U==="e"){l((v[N]??0)+E),x.current=null;return}if(U==="u"){if(L>0){let _=v[N]??0,p=[...h.slice(0,_),...h.slice(a)].join("");q(p,_)}return}if(U==="k"){if(L<E){let _=(v[N]??0)+E,p=[...h.slice(0,a),...h.slice(_)].join("");q(p,a)}return}if(U==="w"){if(L===0&&N>0){let p=[...h.slice(0,a-1),...h.slice(a)].join("");q(p,a-1);return}let _=Eo(M,L);if(_!==L){let p=(v[N]??0)+_,re=[...h.slice(0,p),...h.slice(a)].join("");q(re,p)}return}if(U==="d"){if(a<h.length){let _=[...h.slice(0,a),...h.slice(a+1)].join("");q(_,a)}return}return}if(A.meta){U==="b"?(L===0&&N>0?l(v[N]-1):l(v[N]+Eo(M,L)),x.current=null):U==="f"&&(L>=E&&N<y.length-1?l(v[N+1]):l(v[N]+Cn(M,L)),x.current=null);return}if(A.backspace||A.delete){if(a<=0)return;let _=[...h.slice(0,a-1),...h.slice(a)].join("");q(_,a-1);return}if(!(A.tab||A.escape)&&U.length>0){let _=i?U.replace(/\r\n/g,`
67
72
  `).replace(/\r/g,`
68
- `):U.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=rr||_.includes(`
69
- `))&&s){let H=!1,P={text:_,preventDefault:()=>{H=!0}};if(await Promise.resolve(s(P)),H)return}let re=No(_),we=[...h.slice(0,a),...re,...h.slice(a)].join("");q(we,a+re.length)}},[h,a,n,j,v,y,i,s,o,q,e]);return or(Ce,{isActive:n}),_o(tr,{flexDirection:"column",children:y.map((U,A)=>{let N=A===z,W=(N&&X===U.length?[...U," "]:U).slice(x,x+ie),E=W.join("");if(!N)return _o(hn,{children:E||" "},A);let ge=so(X-x,Math.max(0,W.length-1)),_=W.slice(0,ge).join(""),p=W[ge]??" ",re=W.slice(ge+1).join(""),P=`${_}\x1B[7m${p}\x1B[27m${re}`;return _o(hn,{children:P},A)})})}import{Box as Ge,Text as ct}from"ink";import Ro from"react";import{Text as Re}from"ink";import ir from"react";import{Fragment as cr,jsx as Fe,jsxs as In}from"react/jsx-runtime";var Do=2,Oo=1,Lo=2,ar=1,Sn=3,Tn=4,lr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Fe(Re,{color:n,children:e});let r=[],i=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>i&&r.push(Fe(Re,{color:n,children:e.slice(i,l.index)},`t-${i}`));let d=l[0],x=null,C=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Do*2)x=Fe(Re,{bold:!0,color:n,children:d.slice(Do,-Do)},C);else if(d.length>Oo*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)))x=Fe(Re,{italic:!0,color:n,children:d.slice(Oo,-Oo)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Lo*2)x=Fe(Re,{strikethrough:!0,color:n,children:d.slice(Lo,-Lo)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>ar){let b=d.match(/^(`+)(.+?)\1$/s);b&&b[2]&&(x=Fe(Re,{color:s,children:b[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let b=d.match(/\[(.*?)\]\((.*?)\)/);if(b){let T=b[1],h=b[2];x=In(Re,{color:n,children:[T,In(Re,{color:o,children:[" (",h,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Sn+Tn-1?x=Fe(Re,{underline:!0,color:n,children:d.slice(Sn,-Tn)},C):d.match(/^https?:\/\//)&&(x=Fe(Re,{color:o,children:d},C))}catch{x=null}r.push(x??Fe(Re,{color:n,children:d},C)),i=a.lastIndex}return i<e.length&&r.push(Fe(Re,{color:n,children:e.slice(i)},`t-${i}`)),Fe(cr,{children:r.filter(d=>d!==null)})},Rt=ir.memo(lr);import{Fragment as hr,jsx as ye,jsxs as Nn}from"react/jsx-runtime";var ur=1,Pn=1,dr=1,fr=1,pr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(Ge,{paddingLeft:Pn,flexDirection:"column",children:ye(ct,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,r=/^([ \t]*)([-*+]) +(.*)/,i=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],x=!1,C=!0,b=[],T="";function h(y){y&&(d.push(y),C=!1)}return o.forEach((y,v)=>{let j=`line-${v}`;if(x){let A=y.match(n);A&&A[1].startsWith(T[0])&&A[1].length>=T.length?(h(ye(vn,{content:b},j)),x=!1,b=[],T=""):b.push(y);return}let z=y.match(n),X=y.match(s),ie=y.match(r),q=y.match(i),Ce=y.match(a),U=y.match(l);if(z)x=!0,T=z[1];else if(Ce)h(ye(Ge,{children:ye(ct,{dimColor:!0,children:"---"})},j));else if(X){let A=X[1].length,N=X[2],L=A<=2?"cyan":"blue";h(ye(Ge,{children:ye(ct,{color:L,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Rt,{text:N,defaultColor:L,linkColor:"cyan",codeColor:"yellow"})})},j))}else if(U){let A=U[1];h(ye(Ge,{paddingLeft:1,children:Nn(ct,{dimColor:!0,children:["> ",ye(Rt,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},j))}else if(ie){let A=ie[1],N=ie[2],L=ie[3];h(ye(An,{itemText:L,type:"ul",marker:N,leadingWhitespace:A},j))}else if(q){let A=q[1],N=q[2],L=q[3];h(ye(An,{itemText:L,type:"ol",marker:N,leadingWhitespace:A},j))}else y.trim().length===0?C||(d.push(ye(Ge,{height:ur},`spacer-${v}`)),C=!0):h(ye(Ge,{children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:y,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},j))}),x&&h(ye(vn,{content:b},"line-eof")),ye(hr,{children:d})},mr=({content:e})=>{let t=e.join(`
70
- `);return ye(Ge,{paddingLeft:Pn,flexDirection:"column",children:ye(ct,{color:"yellow",children:t})})},vn=Ro.memo(mr),gr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,r=n.length,i=s.length;return Nn(Ge,{paddingLeft:i+dr,flexDirection:"row",children:[ye(Ge,{width:r,children:ye(ct,{children:n})}),ye(Ge,{flexGrow:fr,children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},An=Ro.memo(gr),Uo=Ro.memo(pr);import{execFile as yr}from"child_process";import wr from"fs";import xt from"fs/promises";import En from"os";import ao from"path";import{promisify as kr}from"util";var io=kr(yr);async function br(){let e=ao.join(En.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
73
+ `):U.replace(/\r?\n/g,"");if(!_||(_=_.replace(/^\x1b?\[200~/,"").replace(/\x1b?\[201~$/,""),!_))return;if((_.length>=ir||_.includes(`
74
+ `))&&s){let H=!1,P={text:_,preventDefault:()=>{H=!0}};if(await Promise.resolve(s(P)),H)return}let re=No(_),we=[...h.slice(0,a),...re,...h.slice(a)].join("");q(we,a+re.length)}},[h,a,n,j,v,y,i,s,o,q,e]);return nr(Ce,{isActive:n}),_o(or,{flexDirection:"column",children:y.map((U,A)=>{let N=A===z,M=(N&&X===U.length?[...U," "]:U).slice(b,b+ie),E=M.join("");if(!N)return _o(yn,{children:E||" "},A);let ge=so(X-b,Math.max(0,M.length-1)),_=M.slice(0,ge).join(""),p=M[ge]??" ",re=M.slice(ge+1).join(""),P=`${_}\x1B[7m${p}\x1B[27m${re}`;return _o(yn,{children:P},A)})})}import{Box as Ge,Text as ct}from"ink";import Ro from"react";import{Text as Re}from"ink";import ar from"react";import{Fragment as ur,jsx as Fe,jsxs as vn}from"react/jsx-runtime";var Do=2,Oo=1,Lo=2,lr=1,Tn=3,In=4,cr=({text:e,defaultColor:t,linkColor:o,codeColor:s})=>{let n=t;if(!/[*_~`<[https?:]/.test(e))return Fe(Re,{color:n,children:e});let r=[],i=0,a=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g,l;for(;(l=a.exec(e))!==null;){l.index>i&&r.push(Fe(Re,{color:n,children:e.slice(i,l.index)},`t-${i}`));let d=l[0],b=null,C=`m-${l.index}`;try{if(d.startsWith("**")&&d.endsWith("**")&&d.length>Do*2)b=Fe(Re,{bold:!0,color:n,children:d.slice(Do,-Do)},C);else if(d.length>Oo*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)))b=Fe(Re,{italic:!0,color:n,children:d.slice(Oo,-Oo)},C);else if(d.startsWith("~~")&&d.endsWith("~~")&&d.length>Lo*2)b=Fe(Re,{strikethrough:!0,color:n,children:d.slice(Lo,-Lo)},C);else if(d.startsWith("`")&&d.endsWith("`")&&d.length>lr){let x=d.match(/^(`+)(.+?)\1$/s);x&&x[2]&&(b=Fe(Re,{color:s,children:x[2]},C))}else if(d.startsWith("[")&&d.includes("](")&&d.endsWith(")")){let x=d.match(/\[(.*?)\]\((.*?)\)/);if(x){let T=x[1],h=x[2];b=vn(Re,{color:n,children:[T,vn(Re,{color:o,children:[" (",h,")"]})]},C)}}else d.startsWith("<u>")&&d.endsWith("</u>")&&d.length>Tn+In-1?b=Fe(Re,{underline:!0,color:n,children:d.slice(Tn,-In)},C):d.match(/^https?:\/\//)&&(b=Fe(Re,{color:o,children:d},C))}catch{b=null}r.push(b??Fe(Re,{color:n,children:d},C)),i=a.lastIndex}return i<e.length&&r.push(Fe(Re,{color:n,children:e.slice(i)},`t-${i}`)),Fe(ur,{children:r.filter(d=>d!==null)})},Rt=ar.memo(cr);import{Fragment as yr,jsx as ye,jsxs as En}from"react/jsx-runtime";var dr=1,Nn=1,fr=1,pr=1,mr=({text:e,renderMarkdown:t=!0})=>{if(!e)return null;if(!t)return ye(Ge,{paddingLeft:Nn,flexDirection:"column",children:ye(ct,{wrap:"wrap",children:e})});let o=e.split(/\r?\n/),s=/^ *(#{1,4}) +(.*)/,n=/^ *(`{3,}|~{3,}) *(\w*?) *$/,r=/^([ \t]*)([-*+]) +(.*)/,i=/^([ \t]*)(\d+)\. +(.*)/,a=/^ *([-*_] *){3,} *$/,l=/^ *> ?(.*)/,d=[],b=!1,C=!0,x=[],T="";function h(y){y&&(d.push(y),C=!1)}return o.forEach((y,v)=>{let j=`line-${v}`;if(b){let A=y.match(n);A&&A[1].startsWith(T[0])&&A[1].length>=T.length?(h(ye(An,{content:x},j)),b=!1,x=[],T=""):x.push(y);return}let z=y.match(n),X=y.match(s),ie=y.match(r),q=y.match(i),Ce=y.match(a),U=y.match(l);if(z)b=!0,T=z[1];else if(Ce)h(ye(Ge,{children:ye(ct,{dimColor:!0,children:"---"})},j));else if(X){let A=X[1].length,N=X[2],L=A<=2?"cyan":"blue";h(ye(Ge,{children:ye(ct,{color:L,...(A===4?"italic":"bold")==="italic"?{italic:!0}:{bold:!0},children:ye(Rt,{text:N,defaultColor:L,linkColor:"cyan",codeColor:"yellow"})})},j))}else if(U){let A=U[1];h(ye(Ge,{paddingLeft:1,children:En(ct,{dimColor:!0,children:["> ",ye(Rt,{text:A,defaultColor:"gray",linkColor:"cyan",codeColor:"yellow"})]})},j))}else if(ie){let A=ie[1],N=ie[2],L=ie[3];h(ye(Pn,{itemText:L,type:"ul",marker:N,leadingWhitespace:A},j))}else if(q){let A=q[1],N=q[2],L=q[3];h(ye(Pn,{itemText:L,type:"ol",marker:N,leadingWhitespace:A},j))}else y.trim().length===0?C||(d.push(ye(Ge,{height:dr},`spacer-${v}`)),C=!0):h(ye(Ge,{children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:y,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})},j))}),b&&h(ye(An,{content:x},"line-eof")),ye(yr,{children:d})},gr=({content:e})=>{let t=e.join(`
75
+ `);return ye(Ge,{paddingLeft:Nn,flexDirection:"column",children:ye(ct,{color:"yellow",children:t})})},An=Ro.memo(gr),hr=({itemText:e,type:t,marker:o,leadingWhitespace:s=""})=>{let n=t==="ol"?`${o}. `:`${o} `,r=n.length,i=s.length;return En(Ge,{paddingLeft:i+fr,flexDirection:"row",children:[ye(Ge,{width:r,children:ye(ct,{children:n})}),ye(Ge,{flexGrow:pr,children:ye(ct,{wrap:"wrap",children:ye(Rt,{text:e,defaultColor:void 0,linkColor:"cyan",codeColor:"yellow"})})})]})},Pn=Ro.memo(hr),Uo=Ro.memo(mr);import{execFile as wr}from"child_process";import kr from"fs";import bt from"fs/promises";import _n from"os";import ao from"path";import{promisify as xr}from"util";var io=xr(wr);async function br(){let e=ao.join(_n.tmpdir(),`entrydesk-clipboard-${Date.now()}.png`);try{let t=`
71
76
  set imageData to the clipboard as "PNGf"
72
77
  set fileRef to open for access POSIX file "${e}" with write permission
73
78
  set eof fileRef to 0
74
79
  write imageData to fileRef
75
80
  close access fileRef
76
- `;return await io("osascript",["-e",t]),(await xt.stat(e)).size===0?void 0:{buffer:await xt.readFile(e),mime:"image/png"}}catch{return}finally{try{wr.existsSync(e)&&await xt.unlink(e)}catch{}}}async function xr(){try{let e=`
81
+ `;return await io("osascript",["-e",t]),(await bt.stat(e)).size===0?void 0:{buffer:await bt.readFile(e),mime:"image/png"}}catch{return}finally{try{kr.existsSync(e)&&await bt.unlink(e)}catch{}}}async function Cr(){try{let e=`
77
82
  Add-Type -AssemblyName System.Windows.Forms
78
83
  $img = [System.Windows.Forms.Clipboard]::GetImage()
79
84
  if ($img) {
@@ -81,10 +86,10 @@ You have access to filesystem tools that allow you to interact with the user's l
81
86
  $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
82
87
  [System.Convert]::ToBase64String($ms.ToArray())
83
88
  }
84
- `,{stdout:t}=await io("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 Cr(){try{let{stdout:e}=await io("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 io("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 xr();if(e==="linux")return Cr()}var $r=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 Dn(e){let t=ao.extname(e).toLowerCase();return $r.has(t)}function Sr(e){let t=ao.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 lo(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 On(e){let t=lo(e);if(/^https?:\/\//.test(t))return!1;try{return await xt.access(t),!0}catch{return!1}}async function Ln(e){let t=lo(e);try{if(!(await xt.stat(t)).isFile())return;let s=await xt.readFile(t),n=Sr(t),r=ao.basename(t);return{buffer:s,mimeType:n,filename:r}}catch{return}}var Ue="\x1B[2m",se="\x1B[0m",Ie="\x1B[36m",Ct="\x1B[32m",Rn="\x1B[31m",ft="\x1B[38;2;59;91;204m",jo="\x1B[38;2;126;200;248m",Fo="\x1B[38;2;244;196;78m";import{useState as Qe}from"react";import{v4 as Un}from"uuid";function jn(e,t){let[o,s]=Qe({status:"loading"}),[n,r]=Qe([]),[i,a]=Qe(""),[l,d]=Qe(()=>e||Un()),[x,C]=Qe(t),[b,T]=Qe(!!e),[h,y]=Qe(null),[v,j]=Qe(""),[z,X]=Qe(!1),ie=Ce=>{r(U=>[...U,{role:"system",content:Ce}])};return{state:o,setState:s,messages:n,setMessages:r,input:i,setInput:a,chatId:l,setChatId:d,currentChatTitle:x,setCurrentChatTitle:C,hasPersistedChat:b,setHasPersistedChat:T,credentials:h,setCredentials:y,currentResponse:v,setCurrentResponse:j,fullOutput:z,setFullOutput:X,addSystemMessage:ie,startNewChat:Ce=>{let U=Un();d(U),C(void 0),T(!1),r([]),Ce&&ie(Ce)}}}import{useEffect as Tr,useState as Fn}from"react";function Wn(e){let[t,o]=Fn(null),[s,n]=Fn(!0);return Tr(()=>{let r=!1;async function i(){try{let a=await fe();if(r)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(r)return;if(a instanceof 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 i(),()=>{r=!0}},[e]),{credentials:t,loading:s}}import{useEffect as Ir,useState as Ut}from"react";function Bn(e){let[t,o]=Ut([]),[s,n]=Ut([]),[r,i]=Ut([]),[a,l]=Ut([]),[d,x]=Ut(!1);return Ir(()=>{if(!e)return;let C=!1;x(!0);async function b(){if(e)try{let T=new G,[h,y,v,j]=await Promise.all([T.getConnectors(e.accessToken,e.workspaceId),T.getModels(e.accessToken,e.workspaceId),T.getAgents(e.accessToken,e.workspaceId),T.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;o(h.connectors),n(y.models),i(v.agents),l(j.providers??[])}catch{}finally{C||x(!1)}}return b(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:r,modelProviders:a,loading:d}}import $t from"fs";import Jn from"path";import{useCallback as vr}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 r=n.stdout.trim();return t||r.length<=200?r:r.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
89
+ `,{stdout:t}=await io("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 io("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 io("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 Dn(){let e=_n.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 On(e){let t=ao.extname(e).toLowerCase();return Sr.has(t)}function Tr(e){let t=ao.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 lo(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 Ln(e){let t=lo(e);if(/^https?:\/\//.test(t))return!1;try{return await bt.access(t),!0}catch{return!1}}async function Rn(e){let t=lo(e);try{if(!(await bt.stat(t)).isFile())return;let s=await bt.readFile(t),n=Tr(t),r=ao.basename(t);return{buffer:s,mimeType:n,filename:r}}catch{return}}var Ue="\x1B[2m",se="\x1B[0m",Ie="\x1B[36m",Ct="\x1B[32m",Un="\x1B[31m",ft="\x1B[38;2;59;91;204m",jo="\x1B[38;2;126;200;248m",Fo="\x1B[38;2;244;196;78m";import{useState as Qe}from"react";import{v4 as jn}from"uuid";function Fn(e,t){let[o,s]=Qe({status:"loading"}),[n,r]=Qe([]),[i,a]=Qe(""),[l,d]=Qe(()=>e||jn()),[b,C]=Qe(t),[x,T]=Qe(!!e),[h,y]=Qe(null),[v,j]=Qe(""),[z,X]=Qe(!1),ie=Ce=>{r(U=>[...U,{role:"system",content:Ce}])};return{state:o,setState:s,messages:n,setMessages:r,input:i,setInput:a,chatId:l,setChatId:d,currentChatTitle:b,setCurrentChatTitle:C,hasPersistedChat:x,setHasPersistedChat:T,credentials:h,setCredentials:y,currentResponse:v,setCurrentResponse:j,fullOutput:z,setFullOutput:X,addSystemMessage:ie,startNewChat:Ce=>{let U=jn();d(U),C(void 0),T(!1),r([]),Ce&&ie(Ce)}}}import{useEffect as Ir,useState as Mn}from"react";function Wn(e){let[t,o]=Mn(null),[s,n]=Mn(!0);return Ir(()=>{let r=!1;async function i(){try{let a=await fe();if(r)return;o({accessToken:a.accessToken,workspaceId:a.workspaceId}),n(!1)}catch(a){if(r)return;if(a instanceof 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 i(),()=>{r=!0}},[e]),{credentials:t,loading:s}}import{useEffect as vr,useState as Ut}from"react";function Bn(e){let[t,o]=Ut([]),[s,n]=Ut([]),[r,i]=Ut([]),[a,l]=Ut([]),[d,b]=Ut(!1);return vr(()=>{if(!e)return;let C=!1;b(!0);async function x(){if(e)try{let T=new G,[h,y,v,j]=await Promise.all([T.getConnectors(e.accessToken,e.workspaceId),T.getModels(e.accessToken,e.workspaceId),T.getAgents(e.accessToken,e.workspaceId),T.getModelProviders(e.accessToken,e.workspaceId)]);if(C)return;o(h.connectors),n(y.models),i(v.agents),l(j.providers??[])}catch{}finally{C||b(!1)}}return x(),()=>{C=!0}},[e]),{availableConnectors:t,availableModels:s,availableAgents:r,modelProviders:a,loading:d}}import $t from"fs";import Gn from"path";import{useCallback as Ar}from"react";import{v4 as Pr}from"uuid";function Jn(e,t){if(!e)return"(no result)";if(typeof e!="object"){let n=String(e);return t||n.length<=200?n:n.slice(0,200)+"..."}let o=e;if("structuredContent"in o&&o.structuredContent){let n=o.structuredContent;if(n.stdout&&typeof n.stdout=="string"){let r=n.stdout.trim();return t||r.length<=200?r:r.slice(0,200)+"..."}}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
85
90
  `);return n?t||n.length<=200?n:n.slice(0,200)+"...":"(result)"}let s=JSON.stringify(e,null,t?2:void 0);return t||s.length<=200?s:s.slice(0,200)+"..."}function pt(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(`${Ue}[Thinking]
86
- ${s.text}${se}`):o.push(`${Ue}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${Ie}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let r=JSON.stringify(s.args,null,t?2:void 0),i=t||r.length<=100?r:r.slice(0,100)+"...";n.push(`${Ue}\u2502 Args: ${i}${se}`)}s.result!==void 0?(n.push(`${Ct}\u2502 Result: ${Mn(s.result,t)}${se}`),n.push(`${Ie}\u2514\u2500 completed${se}`)):n.push(`${Ie}\u2514\u2500${se}`),o.push(n.join(`
87
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),r=[];if(r.push(`${Ie}\u250C\u2500 Tool: ${n}${se}`),s.input){let i=JSON.stringify(s.input,null,t?2:void 0),a=t||i.length<=100?i:i.slice(0,100)+"...";r.push(`${Ue}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(r.push(`${Ct}\u2502 Output: ${Mn(s.output,t)}${se}`),r.push(`${Ie}\u2514\u2500 completed${se}`)):s.state==="error"?r.push(`${Ie}\u2514\u2500 failed${se}`):r.push(`${Ie}\u2514\u2500${se}`),o.push(r.join(`
91
+ ${s.text}${se}`):o.push(`${Ue}[Thinking...]${se}`);else if(s.type==="tool-call"&&s.toolName){let n=[];if(n.push(`${Ie}\u250C\u2500 Tool: ${s.toolName}${se}`),s.args){let r=JSON.stringify(s.args,null,t?2:void 0),i=t||r.length<=100?r:r.slice(0,100)+"...";n.push(`${Ue}\u2502 Args: ${i}${se}`)}s.result!==void 0?(n.push(`${Ct}\u2502 Result: ${Jn(s.result,t)}${se}`),n.push(`${Ie}\u2514\u2500 completed${se}`)):n.push(`${Ie}\u2514\u2500${se}`),o.push(n.join(`
92
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=s.title||s.type.slice(5).replace(/__/g," "),r=[];if(r.push(`${Ie}\u250C\u2500 Tool: ${n}${se}`),s.input){let i=JSON.stringify(s.input,null,t?2:void 0),a=t||i.length<=100?i:i.slice(0,100)+"...";r.push(`${Ue}\u2502 Input: ${a}${se}`)}s.output!==void 0&&s.state==="output-available"?(r.push(`${Ct}\u2502 Output: ${Jn(s.output,t)}${se}`),r.push(`${Ie}\u2514\u2500 completed${se}`)):s.state==="error"?r.push(`${Ie}\u2514\u2500 failed${se}`):r.push(`${Ie}\u2514\u2500${se}`),o.push(r.join(`
88
93
  `))}return o.join(`
89
94
 
90
95
  `).trim()}var co=class{pendingToolCalls=new Map;hasPending(){return this.pendingToolCalls.size>0}hasExecuting(){for(let t of this.pendingToolCalls.values())if(t.status==="executing")return!0;return!1}clear(t){this.pendingToolCalls.delete(t)}buildToolDisplay(){if(this.pendingToolCalls.size===0)return"";let t=[];for(let[,o]of this.pendingToolCalls){let s=o.toolName.replace(/__/g," "),n=`
@@ -107,18 +112,18 @@ ${Ie}\u2514\u2500 completed${se}
107
112
  `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}handleToolError(t,o){if(!t.toolCallId)return null;let n=(this.pendingToolCalls.get(t.toolCallId)?.toolName||t.toolName||"Tool").replace(/__/g," "),r=t.errorText||"Unknown error",i=r.length>200?r.slice(0,200)+"...":r;return o+=`
108
113
 
109
114
  ${Ie}\u250C\u2500 Tool: ${n}${se}`,o+=`
110
- ${Rn}\u2502 Error: ${i}${se}`,o+=`
115
+ ${Un}\u2502 Error: ${i}${se}`,o+=`
111
116
  ${Ie}\u2514\u2500 failed${se}
112
- `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var jt=Jn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
117
+ `,this.pendingToolCalls.delete(t.toolCallId),{fullResponse:o,toolDisplay:this.buildToolDisplay()}}};var jt=Gn.join(process.env.HOME||"/tmp",".entrydesk","stream-debug.log");function ae(e,t){if(!process.env.DEBUG)return;let s=`[${new Date().toISOString()}] ${e}`;t!==void 0&&(s+=`
113
118
  DATA: ${JSON.stringify(t,null,2)}`),s+=`
114
- `;try{$t.appendFileSync(jt,s)}catch{}}function Pr(){try{if($t.existsSync(jt)&&$t.unlinkSync(jt),process.env.DEBUG){let e=Jn.dirname(jt);$t.existsSync(e)||$t.mkdirSync(e,{recursive:!0}),$t.writeFileSync(jt,`=== Debug session started at ${new Date().toISOString()} ===
115
- `)}}catch{}}function uo(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:r,webSearch:i,imageGeneration:a,chart:l,localTools:d,fullOutput:x,setMessages:C,setState:b,setCurrentResponse:T,setCredentials:h,setHasPersistedChat:y,getFileIds:v,clearFiles:j}){let z=d?Qt():void 0,X=d?eo():void 0;return{sendMessage:vr(async(q,Ce,U)=>{Pr(),ae("=== sendMessage called ===",{text:q,localTools:d,clientToolsCount:z?.length});let A=Ce||t?.accessToken,N=U||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,h(E)}catch(E){if(E instanceof qe){if(E.code==="not-logged-in"){b({status:"not-logged-in"});return}if(E.code==="no-workspace"){b({status:"no-workspace"});return}}let ge=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:ge});return}else try{let E=await lt();E!==A&&(A=E,h({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof qe&&E.code==="not-logged-in"){b({status:"not-logged-in"});return}let ge=E instanceof Error?E.message:"Authentication failed";b({status:"error",message:ge});return}C(E=>[...E,{role:"user",content:q}]),b({status:"sending"}),T("");let L=null,W=null;try{let E=new G,ge=v?.()??[],_={id:e,message:{id:Ar(),createdAt:new Date,role:"user",parts:[{type:"text",text:q}]}};ge.length>0&&(_.fileIds=ge),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=r,_.enableWebSearch=i,_.enableImageGeneration=a,_.enableChart=l),z&&(_.clientTools=z),X&&(_.clientToolSystemPrompt=X);let p=await E.chat(A,N,_);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");L=p.body.getReader();let re=new TextDecoder,we="",H="",P="",ee="",Q="",pe="",le="",B=new co,Z=[],K=[],de=[],Se=()=>{let F=B.hasExecuting();F&&!W?W=setInterval(()=>{if(!B.hasExecuting()){W&&(clearInterval(W),W=null);return}T(H+B.buildToolDisplay())},1e3):!F&&W&&(clearInterval(W),W=null)};for(;;){let{done:F,value:ne}=await L.read();if(F)break;we+=re.decode(ne,{stream:!0});let O=we.split(`
119
+ `;try{$t.appendFileSync(jt,s)}catch{}}function Nr(){try{if($t.existsSync(jt)&&$t.unlinkSync(jt),process.env.DEBUG){let e=Gn.dirname(jt);$t.existsSync(e)||$t.mkdirSync(e,{recursive:!0}),$t.writeFileSync(jt,`=== Debug session started at ${new Date().toISOString()} ===
120
+ `)}}catch{}}function uo(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}function Vn({chatId:e,credentials:t,currentAgentId:o,currentModel:s,activeConnectorIds:n,sandbox:r,webSearch:i,imageGeneration:a,chart:l,localTools:d,fullOutput:b,setMessages:C,setState:x,setCurrentResponse:T,setCredentials:h,setHasPersistedChat:y,getFileIds:v,clearFiles:j}){let z=d?Qt():void 0,X=d?eo():void 0;return{sendMessage:Ar(async(q,Ce,U)=>{Nr(),ae("=== sendMessage called ===",{text:q,localTools:d,clientToolsCount:z?.length});let A=Ce||t?.accessToken,N=U||t?.workspaceId;if(!A||!N)try{let E=await fe();A=E.accessToken,N=E.workspaceId,h(E)}catch(E){if(E instanceof qe){if(E.code==="not-logged-in"){x({status:"not-logged-in"});return}if(E.code==="no-workspace"){x({status:"no-workspace"});return}}let ge=E instanceof Error?E.message:"Authentication failed";x({status:"error",message:ge});return}else try{let E=await lt();E!==A&&(A=E,h({accessToken:E,workspaceId:N}))}catch(E){if(E instanceof qe&&E.code==="not-logged-in"){x({status:"not-logged-in"});return}let ge=E instanceof Error?E.message:"Authentication failed";x({status:"error",message:ge});return}C(E=>[...E,{role:"user",content:q}]),x({status:"sending"}),T("");let L=null,M=null;try{let E=new G,ge=v?.()??[],_={id:e,message:{id:Pr(),createdAt:new Date,role:"user",parts:[{type:"text",text:q}]}};ge.length>0&&(_.fileIds=ge),o?_.agentId=o:(s&&(_.model=s),_.connectorIds=n??[],_.enableSandbox=r,_.enableWebSearch=i,_.enableImageGeneration=a,_.enableChart=l),z&&(_.clientTools=z),X&&(_.clientToolSystemPrompt=X);let p=await E.chat(A,N,_);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");L=p.body.getReader();let re=new TextDecoder,we="",H="",P="",ee="",Q="",pe="",le="",W=new co,Z=[],K=[],de=[],Se=()=>{let F=W.hasExecuting();F&&!M?M=setInterval(()=>{if(!W.hasExecuting()){M&&(clearInterval(M),M=null);return}T(H+W.buildToolDisplay())},1e3):!F&&M&&(clearInterval(M),M=null)};for(;;){let{done:F,value:ne}=await L.read();if(F)break;we+=re.decode(ne,{stream:!0});let O=we.split(`
116
121
  `);we=O.pop()||"";for(let f of O)if(f.trim()!=="data: [DONE]"&&f.startsWith("data: "))try{let w=JSON.parse(f.slice(6));switch(ae(`SSE event received: ${w.type}`,w),w.type){case"reasoning-start":ee=w.id||"0",P="";break;case"reasoning-delta":w.delta&&(P+=w.delta,T(`${Ue}[Thinking...]${se}
117
- ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let $={type:"reasoning",id:ee,text:P,state:"done"};Q&&($.providerMetadata={anthropic:{signature:Q}}),K.push($),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T("");break;case"text-delta":w.delta&&(B.hasPending()&&(H=B.flushPending(H)),H+=w.delta,pe+=w.delta,T(H));break;case"tool-input-start":{let $=B.handleToolInputStart(w);$&&T(H+$),Se();break}case"tool-input-delta":{let $=B.handleToolInputDelta(w);$&&T(H+$),Se();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?Ze(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let $=uo(w.args??w.input);K.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added tool to messageParts",{messagePartsCount:K.length})}if(d&&w.toolCallId&&w.toolName&&Ze(w.toolName)){let $=uo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),T(H+B.buildToolDisplay()+`
118
- [Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?Ze(w.toolName):!1});break}case"tool-output-start":{let $=B.handleToolOutputStart(w);$&&T(H+$),Se();break}case"tool-output-delta":{let $=B.handleToolOutputDelta(w);$&&T(H+$),Se();break}case"tool-output-end":{let $=B.handleToolOutputEnd(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"tool-input-error":case"tool-output-error":{let $=B.handleToolError(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let F=K.findIndex(O=>O.type!=="reasoning"),ne=F===-1?K.length:F;K.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:K.length,messageParts:K.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let F=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),B.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),B.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),T(H+B.buildToolDisplay()),Se();let w=await to(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let $=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:$}],isError:!w.success}),w.success){B.handleToolOutputStart({toolCallId:f.toolCallId}),B.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=B.handleToolOutputEnd({toolCallId:f.toolCallId},H);te&&(H=te.fullResponse)}else{let te=B.handleToolError({toolCallId:f.toolCallId,errorText:w.error},H);te&&(H=te.fullResponse)}T(H+B.buildToolDisplay()),Se()}Z.length=0;for(let f of F){let w=K.find($=>($.type==="tool-input-available"||$.type==="tool-call")&&$.toolCallId===f.toolCallId);if(w){let $=[];for(let R of f.content)R.type==="text"?$.push(R.text):R.type==="image"?$.push("[Image]"):R.type==="audio"?$.push("[Audio]"):(R.type==="resource"||R.type==="resource_link")&&$.push("[Resource]");let te=$.join(`
122
+ ${P}`)),w.providerMetadata?.anthropic?.signature&&(Q=w.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let $={type:"reasoning",id:ee,text:P,state:"done"};Q&&($.providerMetadata={anthropic:{signature:Q}}),K.push($),ae("Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T("");break;case"text-delta":w.delta&&(W.hasPending()&&(H=W.flushPending(H)),H+=w.delta,pe+=w.delta,T(H));break;case"tool-input-start":{let $=W.handleToolInputStart(w);$&&T(H+$),Se();break}case"tool-input-delta":{let $=W.handleToolInputDelta(w);$&&T(H+$),Se();break}case"tool-call":case"tool-input-available":{if(ae(`=== Tool event: ${w.type} ===`,{toolCallId:w.toolCallId,toolName:w.toolName,localTools:d,isClientToolResult:w.toolName?Ze(w.toolName):"no toolName",args:w.args,input:w.input}),w.toolCallId&&w.toolName){let $=uo(w.args??w.input);K.push({type:w.type,toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added tool to messageParts",{messagePartsCount:K.length})}if(d&&w.toolCallId&&w.toolName&&Ze(w.toolName)){let $=uo(w.args??w.input);Z.push({toolCallId:w.toolCallId,toolName:w.toolName,args:$}),ae("Added to pendingClientTools",{pendingCount:Z.length,pendingClientTools:Z}),T(H+W.buildToolDisplay()+`
123
+ [Executing ${w.toolName} locally...]`)}else ae("NOT added to pendingClientTools - conditions not met",{localTools:d,hasToolCallId:!!w.toolCallId,hasToolName:!!w.toolName,isClientTool:w.toolName?Ze(w.toolName):!1});break}case"tool-output-start":{let $=W.handleToolOutputStart(w);$&&T(H+$),Se();break}case"tool-output-delta":{let $=W.handleToolOutputDelta(w);$&&T(H+$),Se();break}case"tool-output-end":{let $=W.handleToolOutputEnd(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"tool-input-error":case"tool-output-error":{let $=W.handleToolError(w,H);$&&(H=$.fullResponse,T(H+$.toolDisplay)),Se();break}case"start":w.messageId&&(le=w.messageId,ae("Captured messageId from start event",{messageId:le}));break;case"start-step":case"text-start":case"text-end":case"finish-step":case"message-metadata":case"finish":break;case"error":w.errorText&&console.error("Stream error:",w.errorText);break}}catch{}}if(pe){let F=K.findIndex(O=>O.type!=="reasoning"),ne=F===-1?K.length:F;K.splice(ne,0,{type:"text",text:pe}),ae("Added accumulated text to messageParts",{textLength:pe.length,insertIndex:ne})}for(ae("=== Initial stream ended ===",{pendingClientToolsCount:Z.length,pendingClientTools:Z,messagePartsCount:K.length,messageParts:K.map(F=>({type:F.type,toolCallId:F.toolCallId,toolName:F.toolName}))});Z.length>0;){ae("=== Starting pending tools execution loop ===",{pendingCount:Z.length});let F=[];for(let f of Z){ae(`Executing tool: ${f.toolName}`,{toolCallId:f.toolCallId,args:f.args}),W.handleToolInputStart({toolCallId:f.toolCallId,toolName:f.toolName}),W.handleToolInputDelta({toolCallId:f.toolCallId,inputTextDelta:JSON.stringify(f.args)}),T(H+W.buildToolDisplay()),Se();let w=await to(f.toolName,f.args);ae(`Tool execution result: ${f.toolName}`,{success:w.success,resultPreview:w.success?JSON.stringify(w.result).slice(0,200):w.error});let $=w.success?JSON.stringify(w.result):w.error||"Unknown error";if(F.push({toolCallId:f.toolCallId,toolName:f.toolName,content:[{type:"text",text:$}],isError:!w.success}),w.success){W.handleToolOutputStart({toolCallId:f.toolCallId}),W.handleToolOutputDelta({toolCallId:f.toolCallId,outputTextDelta:JSON.stringify(w.result).slice(0,200)});let te=W.handleToolOutputEnd({toolCallId:f.toolCallId},H);te&&(H=te.fullResponse)}else{let te=W.handleToolError({toolCallId:f.toolCallId,errorText:w.error},H);te&&(H=te.fullResponse)}T(H+W.buildToolDisplay()),Se()}Z.length=0;for(let f of F){let w=K.find($=>($.type==="tool-input-available"||$.type==="tool-call")&&$.toolCallId===f.toolCallId);if(w){let $=[];for(let R of f.content)R.type==="text"?$.push(R.text):R.type==="image"?$.push("[Image]"):R.type==="audio"?$.push("[Audio]"):(R.type==="resource"||R.type==="resource_link")&&$.push("[Resource]");let te=$.join(`
119
124
  `);de.push({type:`tool-${w.toolName}`,toolName:w.toolName,toolCallId:w.toolCallId,input:w.args,output:te,isError:f.isError})}}if(ae("=== Sending clientToolResults for continuation ===",{toolResultsCount:F.length,toolResults:F.map(f=>({toolCallId:f.toolCallId,toolName:f.toolName,isError:f.isError}))}),L)try{L.releaseLock()}catch{}let ne={id:e,clientToolResults:F};o?ne.agentId=o:(s&&(ne.model=s),ne.connectorIds=n??[],ne.enableSandbox=r,ne.enableWebSearch=i,ne.enableImageGeneration=a,ne.enableChart=l),z&&(ne.clientTools=z),X&&(ne.clientToolSystemPrompt=X),ae("=== Sending continuation request ===",{chatId:e,hasAgentId:!!ne.agentId,hasModel:!!ne.model,clientToolResultsCount:F.length});let O=await E.chat(A,N,ne);if(ae("=== Continuation response received ===",{ok:O.ok,status:O.status}),!O.ok){let f=await O.text();throw new Error(`Continuation failed: ${O.status}: ${f}`)}if(!O.body)break;for(ae("=== Processing continuation stream ==="),L=O.body.getReader(),K.length=0,pe="",P="",ee="",Q="";;){let{done:f,value:w}=await L.read();if(f){ae("=== Continuation stream done ===");break}we+=re.decode(w,{stream:!0});let $=we.split(`
120
125
  `);we=$.pop()||"";for(let te of $)if(te.trim()!=="data: [DONE]"&&te.startsWith("data: "))try{let R=JSON.parse(te.slice(6));switch(ae(`Continuation SSE: ${R.type}`,R),R.type){case"reasoning-start":ee=R.id||"0",P="";break;case"reasoning-delta":R.delta&&(P+=R.delta,T(`${Ue}[Thinking...]${se}
121
- ${P}`)),R.providerMetadata?.anthropic?.signature&&(Q=R.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let xe={type:"reasoning",id:ee,text:P,state:"done"};Q&&(xe.providerMetadata={anthropic:{signature:Q}}),K.push(xe),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T(H);break;case"text-delta":R.delta&&(H+=R.delta,pe+=R.delta,T(H));break;case"tool-call":case"tool-input-available":if(R.toolCallId&&R.toolName){let xe=uo(R.args??R.input);K.push({type:R.type,toolCallId:R.toolCallId,toolName:R.toolName,args:xe})}if(d&&R.toolCallId&&R.toolName&&Ze(R.toolName)){let xe=uo(R.args??R.input);Z.push({toolCallId:R.toolCallId,toolName:R.toolName,args:xe}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",R);break}}catch{}}if(pe){let f=K.findIndex($=>$.type!=="reasoning"),w=f===-1?K.length:f;K.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:K.length,fullResponseLength:H.length})}if(d&&z&&z.length>0){let F=[];for(let O of de)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 K)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=pt(F,x);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:K.filter(O=>O.type==="text").length,contentLength:ne.length}),C(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:H.length,fullResponsePreview:H.slice(0,200)});try{let{messages:F}=await E.getMessages(A,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=pt(O,x);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),C(O=>[...O,{role:"assistant",content:H}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),C(ne=>[...ne,{role:"assistant",content:H}])}}ae("=== Message handling complete ==="),T(""),b({status:"ready"}),y(!0),ge.length>0&&j?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let ge=E instanceof Error?E.message:"Failed to send message";b({status:"error",message:ge})}finally{if(W&&(clearInterval(W),W=null),L)try{L.releaseLock()}catch{}}},[t,e,o,s,n,r,i,a,l,d,z,X,x,C,b,T,h,y,v,j])}}import{useState as Ft}from"react";var Vn={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"}},Hn=new Map(Object.values(Vn).map(e=>[e.apiKey,e.name]));function Kn(){return Object.values(Vn)}function zn(e,t,o,s,n){let[r,i]=Ft(e),[a,l]=Ft(t),[d,x]=Ft(o),[C,b]=Ft(s),[T,h]=Ft(n);return{sandbox:r,setSandbox:i,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:x,chart:C,setChart:b,fileSystem:T,setFileSystem:h,capabilityLabelMap:Hn}}import{useEffect as Nr,useState as Er}from"react";function qn(e,t){let[o,s]=Er(null);return Nr(()=>{let n=!1;async function r(){if(!e||!t){s(null);return}try{let a=await new G().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return r(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Wo}from"react";function Yn(e,t,o){let[s,n]=Wo(e),[r,i]=Wo(t),[a,l]=Wo(o);return{currentModel:s,setCurrentModel:n,currentAgentId:r,setCurrentAgentId:i,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Dr,useInput as Or}from"ink";import{useCallback as et,useRef as Lr,useState as Ee}from"react";import{spawn as _r}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 r=_r(s,n,{stdio:"ignore",detached:!0});r.once("error",i=>{o(i)}),r.once("spawn",()=>{r.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:
126
+ ${P}`)),R.providerMetadata?.anthropic?.signature&&(Q=R.providerMetadata.anthropic.signature);break;case"reasoning-end":if(P){let be={type:"reasoning",id:ee,text:P,state:"done"};Q&&(be.providerMetadata={anthropic:{signature:Q}}),K.push(be),ae("Continuation: Added reasoning to messageParts",{reasoningLength:P.length,hasSignature:!!Q,messagePartsCount:K.length})}P="",Q="",T(H);break;case"text-delta":R.delta&&(H+=R.delta,pe+=R.delta,T(H));break;case"tool-call":case"tool-input-available":if(R.toolCallId&&R.toolName){let be=uo(R.args??R.input);K.push({type:R.type,toolCallId:R.toolCallId,toolName:R.toolName,args:be})}if(d&&R.toolCallId&&R.toolName&&Ze(R.toolName)){let be=uo(R.args??R.input);Z.push({toolCallId:R.toolCallId,toolName:R.toolName,args:be}),ae("Continuation: Added to pendingClientTools",{pendingCount:Z.length})}break;case"finish":ae("Continuation finish event",R);break}}catch{}}if(pe){let f=K.findIndex($=>$.type!=="reasoning"),w=f===-1?K.length:f;K.splice(w,0,{type:"text",text:pe})}ae("=== Continuation stream processing complete ===",{pendingClientToolsCount:Z.length,messagePartsCount:K.length,fullResponseLength:H.length})}if(d&&z&&z.length>0){let F=[];for(let O of de)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 K)O.type==="text"&&O.text&&F.push({type:"text",text:O.text});let ne=pt(F,b);ae("=== Using formatted parts for local tools ===",{executedToolsCount:de.length,textPartsCount:K.filter(O=>O.type==="text").length,contentLength:ne.length}),C(O=>[...O,{role:"assistant",content:ne,parts:F}])}else{ae("=== Fetching message from API ===",{fullResponseLength:H.length,fullResponsePreview:H.slice(0,200)});try{let{messages:F}=await E.getMessages(A,N,e,10);ae("=== API messages received ===",{count:F.length,roles:F.map(O=>O.role)});let ne=F.find(O=>O.role==="assistant");if(ne){let O=ne.parts,f=pt(O,b);ae("=== Setting message from API ===",{partsCount:O.length,partTypes:O.map(w=>w.type),contentLength:f.length,contentPreview:f.slice(0,200)}),C(w=>[...w,{role:"assistant",content:f,parts:O}])}else ae("=== No assistant message found, using fallback ==="),C(O=>[...O,{role:"assistant",content:H}])}catch(F){ae("=== API fetch failed, using fallback ===",{error:F instanceof Error?F.message:String(F)}),C(ne=>[...ne,{role:"assistant",content:H}])}}ae("=== Message handling complete ==="),T(""),x({status:"ready"}),y(!0),ge.length>0&&j?.()}catch(E){ae("=== ERROR ===",{message:E instanceof Error?E.message:String(E),stack:E instanceof Error?E.stack:void 0});let ge=E instanceof Error?E.message:"Failed to send message";x({status:"error",message:ge})}finally{if(M&&(clearInterval(M),M=null),L)try{L.releaseLock()}catch{}}},[t,e,o,s,n,r,i,a,l,d,z,X,b,C,x,T,h,y,v,j])}}import{useState as Ft}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"}},Kn=new Map(Object.values(Hn).map(e=>[e.apiKey,e.name]));function zn(){return Object.values(Hn)}function qn(e,t,o,s,n){let[r,i]=Ft(e),[a,l]=Ft(t),[d,b]=Ft(o),[C,x]=Ft(s),[T,h]=Ft(n);return{sandbox:r,setSandbox:i,webSearch:a,setWebSearch:l,imageGeneration:d,setImageGeneration:b,chart:C,setChart:x,fileSystem:T,setFileSystem:h,capabilityLabelMap:Kn}}import{useEffect as Er,useState as _r}from"react";function Yn(e,t){let[o,s]=_r(null);return Er(()=>{let n=!1;async function r(){if(!e||!t){s(null);return}try{let a=await new G().getAgent(t.accessToken,t.workspaceId,e);n||s(a)}catch{n||s(null)}}return r(),()=>{n=!0}},[e,t]),{currentAgentDetails:o}}import{useState as Mo}from"react";function Xn(e,t,o){let[s,n]=Mo(e),[r,i]=Mo(t),[a,l]=Mo(o);return{currentModel:s,setCurrentModel:n,currentAgentId:r,setCurrentAgentId:i,activeConnectorIds:a,setActiveConnectorIds:l}}import{useApp as Or,useInput as Lr}from"ink";import{useCallback as et,useRef as Rr,useState as Ee}from"react";import{spawn as Dr}from"child_process";function Zn(e){return new Promise((t,o)=>{let s,n;process.platform==="darwin"?(s="open",n=[e]):process.platform==="win32"?(s="cmd",n=["/c","start","",e]):(s="xdg-open",n=[e]);let r=Dr(s,n,{stdio:"ignore",detached:!0});r.once("error",i=>{o(i)}),r.once("spawn",()=>{r.unref(),t()})})}var Qn=[{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 es(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase();return t?Qn.filter(o=>o.name.startsWith(t)||o.aliases.some(s=>s.startsWith(t))):Qn}function ts(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 os=`Available commands:
122
127
  /help, /h, /? Show this help message
123
128
  /clear, /cls, /new Start a new chat
124
129
  /model [name], /m Show current model or switch to [name]
@@ -142,7 +147,7 @@ Note: For detailed usage with sorting/limits, use: entrydesk usage --help
142
147
 
143
148
  Keyboard shortcuts:
144
149
  Ctrl+O Toggle full output mode
145
- Ctrl+C Exit`;function Bo(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function os({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:r,currentModel:i,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:x,setCurrentAgentDetails:C,activeConnectorIds:b,setActiveConnectorIds:T,sandbox:h,setSandbox:y,webSearch:v,setWebSearch:j,imageGeneration:z,setImageGeneration:X,chart:ie,setChart:q,fileSystem:Ce,setFileSystem:U,availableModels:A,availableAgents:N,availableConnectors:L,messages:W,hasPersistedChat:E,setHasPersistedChat:ge,setMessages:_,addSystemMessage:p,startNewChat:re,sendMessage:we,setFullOutput:H,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:B=!1}){let{exit:Z}=Dr(),[K,de]=Ee([]),[Se,F]=Ee(0),[ne,O]=Ee(!1),[f,w]=Ee(null),[$,te]=Ee([]),[R,xe]=Ee(0),[ot,nt]=Ee(new Set),[De,st]=Ee(new Set),[xo,Kt]=Ee([]),[je,gt]=Ee([]),[He,zt]=Ee([]),[rt,Co]=Ee([]),[Me,Ke]=Ee(null),[qt,ht]=Ee(""),dt=Lr(!1),[it,yt]=Ee(!1),wt=et(async()=>{if(!P)return[];let I=new G,g=[],c;do{let u=await I.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.skills),c=u.nextKey}while(c);return gt(g),g},[P]),kt=et(async()=>{if(!P)return[];let I=new G,g=[],c;do{let u=await I.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.schedules),c=u.nextKey}while(c);return zt(g),g},[P]),Ne=et(async I=>{if(I==="model"){if(A.length===0){p("No models available.");return}let g=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=i?g.findIndex(u=>u.id===i):-1;xe(Math.max(c,0)),w("model")}else if(I==="agent"){if(N.length===0){p("No agents available.");return}let g=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=l?g.findIndex(u=>u.id===l):-1;xe(Math.max(c,0)),w("agent")}else if(I==="skills"){let g=je;if(g.length===0)try{g=await wt()}catch{p("Failed to load skills.");return}if(g.length===0){p("No skills available.");return}let c=g.map(u=>({id:u.id,name:u.name,description:u.description}));te(c),xe(0),w("skills")}else if(I==="schedules"){let g=He;if(g.length===0)try{g=await kt()}catch{p("Failed to load schedules.");return}if(g.length===0){p("No schedules found.");return}let c=g.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(c),xe(0),w("schedules")}else if(I==="connectors"){if(L.length===0){p("No connectors available.");return}let g=L.map(c=>({id:c.id,name:c.name}));te(g),xe(0),nt(new Set(b||[])),w("connectors")}else if(I==="capabilities"){let g=Kn().map(u=>({id:u.id,name:u.name,description:u.description}));te(g),xe(0);let c=new Set;h&&c.add("sandbox"),v&&c.add("webSearch"),z&&c.add("imageGeneration"),ie&&c.add("chart"),Ce&&c.add("fileSystem"),st(c),w("capabilities")}else if(I==="chats"){if(!P){p("Not authenticated.");return}try{let g=new G,{chats:c}=await g.getChats(P.accessToken,P.workspaceId,20);if(c.length===0){p("No chats available.");return}Kt(c);let u=c.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));te(u);let m=u.findIndex(S=>S.id===o);xe(Math.max(m,0)),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let g=J.getProfileNames(),c=J.getCurrentProfileName(),u=g.map(S=>({id:S,name:S,description:S===c?"(current)":void 0}));te(u);let m=u.findIndex(S=>S.id===c);xe(Math.max(m,0)),w("profile")}O(!1),de([])},[A,N,je,He,L,b,i,l,wt,kt,h,v,z,ie,Ce,P,o,p]),he=et(I=>{let g=oe.getAll(I);a(g.model?.default),d(void 0),C(null);let c=g.connectors?.defaults;T(c&&c.length>0?c:void 0);let u=g.capabilities;y(u?.sandbox??pe.sandbox),j(u?.webSearch??pe.webSearch),X(u?.imageGeneration??pe.imageGeneration),q(u?.chart??pe.chart);let m=g.localTools;U(m?.fileSystem??pe.fileSystem)},[a,d,C,T,y,j,X,q,U,pe]),ze=et(async()=>{try{let I=await fe();ee({accessToken:I.accessToken,workspaceId:I.workspaceId}),Q({status:"ready"})}catch(I){if(ee(null),I instanceof qe){if(I.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(I.code==="no-workspace"){Q({status:"no-workspace"});return}}let g=I instanceof Error?I.message:"Failed to authenticate";Q({status:"error",message:g})}},[ee,Q]),bt=et(async I=>{switch(I.type){case"help":return p(ts),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(I.value){let g=I.value.toLowerCase(),c=A.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(c)l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id);else{let u=A.map(m=>m.name).join(", ");p(`Model "${I.value}" not found.
150
+ Ctrl+C Exit`;function Wo(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} min`;case"hours":return`Every ${t.every} hr`;case"days":return`Every ${t.every} day at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":return`Every ${t.every} week`;case"months":return`Every ${t.every} month`;default:return"Unknown"}}function ns({input:e,setInput:t,chatId:o,setChatId:s,currentChatTitle:n,setCurrentChatTitle:r,currentModel:i,setCurrentModel:a,currentAgentId:l,setCurrentAgentId:d,currentAgentDetails:b,setCurrentAgentDetails:C,activeConnectorIds:x,setActiveConnectorIds:T,sandbox:h,setSandbox:y,webSearch:v,setWebSearch:j,imageGeneration:z,setImageGeneration:X,chart:ie,setChart:q,fileSystem:Ce,setFileSystem:U,availableModels:A,availableAgents:N,availableConnectors:L,messages:M,hasPersistedChat:E,setHasPersistedChat:ge,setMessages:_,addSystemMessage:p,startNewChat:re,sendMessage:we,setFullOutput:H,credentials:P,setCredentials:ee,setState:Q,defaultCapabilities:pe,capabilityLabelMap:le,hasUploadingFiles:W=!1}){let{exit:Z}=Or(),[K,de]=Ee([]),[Se,F]=Ee(0),[ne,O]=Ee(!1),[f,w]=Ee(null),[$,te]=Ee([]),[R,be]=Ee(0),[ot,nt]=Ee(new Set),[De,st]=Ee(new Set),[bo,Kt]=Ee([]),[je,gt]=Ee([]),[He,zt]=Ee([]),[rt,Co]=Ee([]),[Be,Ke]=Ee(null),[qt,ht]=Ee(""),dt=Rr(!1),[it,yt]=Ee(!1),wt=et(async()=>{if(!P)return[];let I=new G,g=[],c;do{let u=await I.listAvailableSkills(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.skills),c=u.nextKey}while(c);return gt(g),g},[P]),kt=et(async()=>{if(!P)return[];let I=new G,g=[],c;do{let u=await I.getSchedules(P.accessToken,P.workspaceId,{limit:100,nextKey:c});g.push(...u.schedules),c=u.nextKey}while(c);return zt(g),g},[P]),Ne=et(async I=>{if(I==="model"){if(A.length===0){p("No models available.");return}let g=A.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=i?g.findIndex(u=>u.id===i):-1;be(Math.max(c,0)),w("model")}else if(I==="agent"){if(N.length===0){p("No agents available.");return}let g=N.map(u=>({id:u.id,name:u.name,description:u.description}));te(g);let c=l?g.findIndex(u=>u.id===l):-1;be(Math.max(c,0)),w("agent")}else if(I==="skills"){let g=je;if(g.length===0)try{g=await wt()}catch{p("Failed to load skills.");return}if(g.length===0){p("No skills available.");return}let c=g.map(u=>({id:u.id,name:u.name,description:u.description}));te(c),be(0),w("skills")}else if(I==="schedules"){let g=He;if(g.length===0)try{g=await kt()}catch{p("Failed to load schedules.");return}if(g.length===0){p("No schedules found.");return}let c=g.map(u=>({id:u.id,name:u.name,description:`${u.agent.name} - ${u.isActive?"Active":"Paused"}`}));te(c),be(0),w("schedules")}else if(I==="connectors"){if(L.length===0){p("No connectors available.");return}let g=L.map(c=>({id:c.id,name:c.name}));te(g),be(0),nt(new Set(x||[])),w("connectors")}else if(I==="capabilities"){let g=zn().map(u=>({id:u.id,name:u.name,description:u.description}));te(g),be(0);let c=new Set;h&&c.add("sandbox"),v&&c.add("webSearch"),z&&c.add("imageGeneration"),ie&&c.add("chart"),Ce&&c.add("fileSystem"),st(c),w("capabilities")}else if(I==="chats"){if(!P){p("Not authenticated.");return}try{let g=new G,{chats:c}=await g.getChats(P.accessToken,P.workspaceId,20);if(c.length===0){p("No chats available.");return}Kt(c);let u=c.map(S=>({id:S.id,name:S.title||"Untitled",description:new Date(S.createdAt).toLocaleDateString()}));te(u);let m=u.findIndex(S=>S.id===o);be(Math.max(m,0)),w("chats")}catch{p("Failed to load chats.")}}else if(I==="profile"){let g=J.getProfileNames(),c=J.getCurrentProfileName(),u=g.map(S=>({id:S,name:S,description:S===c?"(current)":void 0}));te(u);let m=u.findIndex(S=>S.id===c);be(Math.max(m,0)),w("profile")}O(!1),de([])},[A,N,je,He,L,x,i,l,wt,kt,h,v,z,ie,Ce,P,o,p]),he=et(I=>{let g=oe.getAll(I);a(g.model?.default),d(void 0),C(null);let c=g.connectors?.defaults;T(c&&c.length>0?c:void 0);let u=g.capabilities;y(u?.sandbox??pe.sandbox),j(u?.webSearch??pe.webSearch),X(u?.imageGeneration??pe.imageGeneration),q(u?.chart??pe.chart);let m=g.localTools;U(m?.fileSystem??pe.fileSystem)},[a,d,C,T,y,j,X,q,U,pe]),ze=et(async()=>{try{let I=await fe();ee({accessToken:I.accessToken,workspaceId:I.workspaceId}),Q({status:"ready"})}catch(I){if(ee(null),I instanceof qe){if(I.code==="not-logged-in"){Q({status:"not-logged-in"});return}if(I.code==="no-workspace"){Q({status:"no-workspace"});return}}let g=I instanceof Error?I.message:"Failed to authenticate";Q({status:"error",message:g})}},[ee,Q]),xt=et(async I=>{switch(I.type){case"help":return p(os),!0;case"clear":return re("Started a new chat."),!0;case"model":{if(I.value){let g=I.value.toLowerCase(),c=A.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(c)l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id);else{let u=A.map(m=>m.name).join(", ");p(`Model "${I.value}" not found.
146
151
  Available: ${u||"none"}`)}}else{let g=A.find(c=>c.id===i)?.name||i;p(i?`Current model: ${g}`:"No model selected. Using agent mode.")}return!0}case"agent":{if(!I.value)return N.length===0?(p("No agents available."),!0):(Ne("agent"),!0);let g=I.value.toLowerCase(),c=N.find(u=>u.id.toLowerCase()===g||u.name.toLowerCase().includes(g));if(c)c.id!==l?re(`Switched to agent: ${c.name} (new chat)`):p(`Switched to agent: ${c.name}`),d(c.id),a(void 0);else{let u=N.map(m=>m.name).join(", ");p(`Agent "${I.value}" not found.
147
152
  Available: ${u||"none"}`)}return!0}case"skills":{if(!I.value)return Ne("skills"),!0;let g=I.value.toLowerCase();return(je.length>0?Promise.resolve(je):wt().catch(()=>[])).then(u=>{let m=u.find(S=>S.id.toLowerCase()===g||S.name.toLowerCase().includes(g));p(m?`Skill: ${m.name}
148
153
  ${m.description}
@@ -151,87 +156,87 @@ Author: ${m.author.name}
151
156
  ID: ${m.id}`:`Skill "${I.value}" not found.`)}),!0}case"schedules":{if(!I.value)return Ne("schedules"),!0;let g=I.value.toLowerCase();return(He.length>0?Promise.resolve(He):kt().catch(()=>[])).then(u=>{let m=u.find(S=>S.id.toLowerCase()===g||S.name.toLowerCase().includes(g));if(m){let S=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
152
157
  Agent: ${m.agent.name}
153
158
  Status: ${m.isActive?"Active":"Paused"}
154
- Repeat: ${Bo(m.config)}
159
+ Repeat: ${Wo(m.config)}
155
160
  Next Run: ${S}
156
- ID: ${m.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(l){let c=x?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(m=>` - ${m.name}`).join(`
161
+ ID: ${m.id}`)}else p(`Schedule "${I.value}" not found.`)}),!0}case"connectors":{if(l){let c=b?.connectors||[];if(c.length===0)p("No agent connectors.");else{let u=c.map(m=>` - ${m.name}`).join(`
157
162
  `);p(`Agent connectors:
158
- ${u}`)}return!0}let g=L.filter(c=>b?.includes(c.id));if(g.length===0)p("No active connectors.");else{let c=g.map(u=>` - ${u.name}`).join(`
163
+ ${u}`)}return!0}let g=L.filter(c=>x?.includes(c.id));if(g.length===0)p("No active connectors.");else{let c=g.map(u=>` - ${u.name}`).join(`
159
164
  `);p(`Active connectors:
160
- ${c}`)}return!0}case"capabilities":{if(l){let u=(x?.capabilities||[]).map(m=>le.get(m)??m);return p(u.length>0?`Agent capabilities:
165
+ ${c}`)}return!0}case"capabilities":{if(l){let u=(b?.capabilities||[]).map(m=>le.get(m)??m);return p(u.length>0?`Agent capabilities:
161
166
  ${u.map(m=>` - ${m}`).join(`
162
167
  `)}`:"No agent capabilities."),!0}let g=[];return h&&g.push("Sandbox"),v&&g.push("Web Search"),z&&g.push("Image Generation"),ie&&g.push("Chart"),Ce&&g.push("FileSystem"),p(g.length>0?`Active capabilities:
163
168
  ${g.map(c=>` - ${c}`).join(`
164
169
  `)}`:"No capabilities enabled."),!0}case"chats":return p(n?`Current chat: ${n}`:`Current chat: ${o.slice(0,8)}...`),!0;case"workspace":{if(!P)return p("Not authenticated."),!0;let g=new G;if(!I.value){try{let{workspaces:u}=await g.getWorkspaces(P.accessToken);if(u.length===0)p("No workspaces found.");else{let m=u.map(S=>` ${S.id===P.workspaceId?"* ":" "}${S.name}
165
170
  ID: ${S.id}`);p(`Workspaces:
166
171
  ${m.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 g.getWorkspaces(P.accessToken),m=u.find(S=>S.id===c);if(!m)return p(`Workspace not found: ${c}`),!0;await $e.saveWorkspaceId(c),p(`Switched to workspace: ${m.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let g=new G;if(!I.value){try{let m=await g.getBudget(P.accessToken,P.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let c=I.value.toLowerCase();if(c==="clear"||c==="null"){try{await g.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await g.updateBudget(P.accessToken,P.workspaceId,c),p(`Budget set to: $${c}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let g=new G;try{let c=[],u,m=0,S=10;do{let Te=await g.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(c.push(...Te.monthlyUsages),u=Te.nextKey,m++,m>=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,D=0;for(let Te of c)k+=parseFloat(Te.totalCost),D+=Te.operationCount;let me=[...c].toSorted((Te,at)=>parseFloat(at.totalCost)-parseFloat(Te.totalCost)),M=10,ce=me.slice(0,M),Oe=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${D.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Te=>` ${Te.user.name}: $${parseFloat(Te.totalCost).toFixed(2)} (${Te.operationCount.toLocaleString()} ops)`)];c.length>M&&(Oe.push("",`... and ${c.length-M} more users`),Oe.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Oe.join(`
168
- `))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let g=J.getCurrentProfileName(),c=i?A.find(k=>k.id===i)?.name||i:null,u=l?N.find(k=>k.id===l)?.name||l:null,m=b?L.filter(k=>b.includes(k.id)).map(k=>k.name):[],S=[];return h&&S.push("Sandbox"),v&&S.push("Web Search"),z&&S.push("Image Gen"),ie&&S.push("Chart"),Ce&&S.push("FileSystem"),$e.getEmail().then(k=>{let D=[`Profile: ${g}${g!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(D.join(`
172
+ `)}`)}}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 g.getWorkspaces(P.accessToken),m=u.find(S=>S.id===c);if(!m)return p(`Workspace not found: ${c}`),!0;await $e.saveWorkspaceId(c),p(`Switched to workspace: ${m.name}`),p("Please restart the chat to apply changes.")}catch(u){p(`Failed to switch workspace: ${u instanceof Error?u.message:"Unknown error"}`)}return!0}case"budget":{if(!P)return p("Not authenticated."),!0;let g=new G;if(!I.value){try{let m=await g.getBudget(P.accessToken,P.workspaceId);m.budget===null?p("No budget set for this workspace."):p(`Current budget: $${m.budget}`)}catch(m){p(`Failed to get budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let c=I.value.toLowerCase();if(c==="clear"||c==="null"){try{await g.updateBudget(P.accessToken,P.workspaceId,null),p("Budget cleared.")}catch(m){p(`Failed to clear budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}let u=parseFloat(c);if(isNaN(u)||u<0)return p("Invalid budget amount. Must be a positive number."),!0;try{await g.updateBudget(P.accessToken,P.workspaceId,c),p(`Budget set to: $${c}`)}catch(m){p(`Failed to set budget: ${m instanceof Error?m.message:"Unknown error"}`)}return!0}case"usage":{if(!P)return p("Not authenticated."),!0;let g=new G;try{let c=[],u,m=0,S=10;do{let Te=await g.getMonthlyUsages(P.accessToken,P.workspaceId,{nextKey:u,limit:20});if(c.push(...Te.monthlyUsages),u=Te.nextKey,m++,m>=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,D=0;for(let Te of c)k+=parseFloat(Te.totalCost),D+=Te.operationCount;let me=[...c].toSorted((Te,at)=>parseFloat(at.totalCost)-parseFloat(Te.totalCost)),B=10,ce=me.slice(0,B),Oe=[`Total Cost: $${k.toFixed(2)}`,`Total Operations: ${D.toLocaleString()}`,`Users: ${c.length}`,"",`Top ${ce.length} Users by Cost:`,...ce.map(Te=>` ${Te.user.name}: $${parseFloat(Te.totalCost).toFixed(2)} (${Te.operationCount.toLocaleString()} ops)`)];c.length>B&&(Oe.push("",`... and ${c.length-B} more users`),Oe.push("Use CLI command for full list: entrydesk usage --limit <n> --sort-by <cost|operations>")),p(Oe.join(`
173
+ `))}catch(c){p(`Failed to get usage: ${c instanceof Error?c.message:"Unknown error"}`)}return!0}case"status":{let g=J.getCurrentProfileName(),c=i?A.find(k=>k.id===i)?.name||i:null,u=l?N.find(k=>k.id===l)?.name||l:null,m=x?L.filter(k=>x.includes(k.id)).map(k=>k.name):[],S=[];return h&&S.push("Sandbox"),v&&S.push("Web Search"),z&&S.push("Image Gen"),ie&&S.push("Chart"),Ce&&S.push("FileSystem"),$e.getEmail().then(k=>{let D=[`Profile: ${g}${g!=="default"?" (non-default)":""}`,k?`Logged in as: ${k}`:"Not logged in",P?.workspaceId?`Workspace: ${P.workspaceId}`:null,E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(D.join(`
169
174
  `))}).catch(()=>{let k=[`Profile: ${g}`,"Not logged in",E?`Chat ID: ${o}`:null,c?`Model: ${c}`:null,u?`Agent: ${u}`:null,`Connectors: ${m.length>0?m.join(", "):"none"}`,`Capabilities: ${S.length>0?S.join(", "):"none"}`].filter(Boolean);p(k.join(`
170
- `))}),!0}case"profile":{let g=I.value?I.value.split(/\s+/).filter(Boolean):[];if(g.length===0)return Ne("profile"),!0;let c=g[0]?.toLowerCase()||"list",u=g[1],m=g[2],S=J.getProfileNames(),k=J.getCurrentProfileName(),D=J.getOverrideProfile(),me=(M,ce=!1)=>{if(M)return M;if(ce&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let M=[`Profiles (${S.length}):`];for(let ce of S){let Oe=ce===k?" (current)":"";M.push(` ${ce}${Oe}`)}return p(M.join(`
171
- `)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let M=me(u,!0),ce=oe.getAll(M),Oe=await $e.getAll(M),Te=!!Oe?.accessToken,at=ce.capabilities?Object.entries(ce.capabilities).filter(([,$o])=>$o).map(([$o])=>$o):[],Gs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Vs=[`Profile: ${M}${M===k?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Gs}`,`Capabilities: ${at.length>0?at.join(", "):"none"}`,Te?`Logged in as: ${Oe?.email??"unknown"}`:"Not logged in",Te&&Oe?.workspaceId?`Workspace ID: ${Oe.workspaceId}`:null].filter(Boolean);return p(Vs.join(`
172
- `)),!0}if(c==="create"){let M=u||J.DEFAULT_PROFILE;return J.createProfile(M),p(`Profile created: ${M}`),!0}if(c==="use"||c==="switch"){let M=me(u,!0);return J.setOverrideProfile(M),J.setCurrentProfile(M),he(M),await ze(),re(`Switched to profile: ${M} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let M=me(u,!0),ce=M===k,Oe=J.deleteProfile(M),Te=`Profile deleted: ${M}`;if(ce)J.setOverrideProfile(Oe.currentProfile),he(Oe.currentProfile),await ze(),re(`${Te}
173
- Switched to profile: ${Oe.currentProfile} (new chat)`);else if(D===M){let at=J.getCurrentProfileName();J.setOverrideProfile(at),he(at),await ze(),re(`${Te}
174
- Switched to profile: ${at} (new chat)`)}else p(Te);return!0}if(c==="rename"||c==="move"||c==="mv"){let M=me(u,!0);if(!m)throw new Error("New profile name is required.");let ce=J.renameProfile(M,m);return p(`Profile renamed: ${M} -> ${m}`),D===M?(J.setOverrideProfile(m),he(m)):ce.currentProfile===m&&he(m),!0}if(c==="clone"||c==="copy"){let M=me(u,!0);if(!m)throw new Error("Target profile name is required.");let ce=oe.getAll(M);return J.createProfile(m),oe.setAll(ce,m),await $e.clear(m),p(`Profile cloned: ${M} -> ${m}`),!0}p(`Unknown profile command: ${c}`)}catch(M){let ce=M instanceof Error?M.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let g=Ye().hubUrl.replace(/\/$/,""),u=E||W.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",m=l?`?agentId=${encodeURIComponent(l)}`:"",S=`${g}${u}${m}`;try{await Xn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
175
- URL: ${S}`)}return!0}case"share":{if(!P)return p("Not authenticated."),!0;if(!(E||W.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new G().createChatShare(P.accessToken,P.workspaceId,o,"public"),S=`${Ye().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 P?E?(yt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${I.input}
176
- Type /help for available commands.`),!0;default:return!1}},[p,A,N,L,je,He,i,l,b,h,v,z,ie,Ce,o,n,Z,Ne,re,le,x,E,W,wt,kt,_,a,d,C,a,he,ze]),Yt=et(I=>{if(dt.current=!1,it){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&yt(!1));return}if(t(I),ht(I),Me!==null&&Ke(null),f&&(w(null),te([])),I.startsWith("/")&&!I.includes(" ")){let g=Qn(I);de(g),F(0),O(g.length>0)}else O(!1),de([])},[f,Me,it,t]),Nt=et((I,g=!1)=>{if(I>=0&&I<K.length){let c=K[I];O(!1),de([]),c.name==="model"?(t("/model "),Ne("model")):c.name==="agent"?(t("/agent "),Ne("agent")):c.name==="skills"?(t("/skills "),Ne("skills")):c.name==="schedules"?(t("/schedules "),Ne("schedules")):c.name==="connectors"?(t("/connectors "),Ne("connectors")):c.name==="capabilities"?(t("/capabilities "),Ne("capabilities")):c.name==="chats"?(t("/chats "),Ne("chats")):c.name==="profile"?(t("/profile "),Ne("profile")):g?(t(""),bt({type:c.name})):t(`/${c.name}`)}},[K,Ne,t,bt]),Xt=et(async I=>{dt.current=!1;let g=I.trim();if(!g||it)return;if(f==="model"&&$.length>0){let u=$[R];u&&(l?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&$.length>0){let u=$[R];u&&(u.id!==l?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&$.length>0){let u=$[R];if(u){let m=je.find(S=>S.id===u.id);m&&p(`Skill: ${m.name}
175
+ `))}),!0}case"profile":{let g=I.value?I.value.split(/\s+/).filter(Boolean):[];if(g.length===0)return Ne("profile"),!0;let c=g[0]?.toLowerCase()||"list",u=g[1],m=g[2],S=J.getProfileNames(),k=J.getCurrentProfileName(),D=J.getOverrideProfile(),me=(B,ce=!1)=>{if(B)return B;if(ce&&S.length===1)return S[0];throw new Error("Profile name is required when multiple profiles exist.")};try{if(c==="list"){let B=[`Profiles (${S.length}):`];for(let ce of S){let Oe=ce===k?" (current)":"";B.push(` ${ce}${Oe}`)}return p(B.join(`
176
+ `)),!0}if(c==="current")return p(`Current profile: ${k}`),!0;if(c==="show"){let B=me(u,!0),ce=oe.getAll(B),Oe=await $e.getAll(B),Te=!!Oe?.accessToken,at=ce.capabilities?Object.entries(ce.capabilities).filter(([,$o])=>$o).map(([$o])=>$o):[],Vs=ce.connectors?.defaults&&ce.connectors.defaults.length>0?ce.connectors.defaults.join(", "):"unset",Hs=[`Profile: ${B}${B===k?" (current)":""}`,`API URL: ${ce.apiUrl??"default"}`,`Hub URL: ${ce.hubUrl??"default"}`,`Model: ${ce.model?.default??"unset"}`,`Connectors: ${Vs}`,`Capabilities: ${at.length>0?at.join(", "):"none"}`,Te?`Logged in as: ${Oe?.email??"unknown"}`:"Not logged in",Te&&Oe?.workspaceId?`Workspace ID: ${Oe.workspaceId}`:null].filter(Boolean);return p(Hs.join(`
177
+ `)),!0}if(c==="create"){let B=u||J.DEFAULT_PROFILE;return J.createProfile(B),p(`Profile created: ${B}`),!0}if(c==="use"||c==="switch"){let B=me(u,!0);return J.setOverrideProfile(B),J.setCurrentProfile(B),he(B),await ze(),re(`Switched to profile: ${B} (new chat)`),!0}if(c==="delete"||c==="remove"||c==="rm"){let B=me(u,!0),ce=B===k,Oe=J.deleteProfile(B),Te=`Profile deleted: ${B}`;if(ce)J.setOverrideProfile(Oe.currentProfile),he(Oe.currentProfile),await ze(),re(`${Te}
178
+ Switched to profile: ${Oe.currentProfile} (new chat)`);else if(D===B){let at=J.getCurrentProfileName();J.setOverrideProfile(at),he(at),await ze(),re(`${Te}
179
+ Switched to profile: ${at} (new chat)`)}else p(Te);return!0}if(c==="rename"||c==="move"||c==="mv"){let B=me(u,!0);if(!m)throw new Error("New profile name is required.");let ce=J.renameProfile(B,m);return p(`Profile renamed: ${B} -> ${m}`),D===B?(J.setOverrideProfile(m),he(m)):ce.currentProfile===m&&he(m),!0}if(c==="clone"||c==="copy"){let B=me(u,!0);if(!m)throw new Error("Target profile name is required.");let ce=oe.getAll(B);return J.createProfile(m),oe.setAll(ce,m),await $e.clear(m),p(`Profile cloned: ${B} -> ${m}`),!0}p(`Unknown profile command: ${c}`)}catch(B){let ce=B instanceof Error?B.message:"Unknown error";p(`Profile error: ${ce}`)}return!0}case"open-in-browser":{let g=Ye().hubUrl.replace(/\/$/,""),u=E||M.some(k=>k.role!=="system")?`/chat/${o}`:"/chat/new",m=l?`?agentId=${encodeURIComponent(l)}`:"",S=`${g}${u}${m}`;try{await Zn(S),p(`Opened in browser: ${S}`)}catch(k){p(`Failed to open browser: ${k instanceof Error?k.message:"Unknown error"}
180
+ URL: ${S}`)}return!0}case"share":{if(!P)return p("Not authenticated."),!0;if(!(E||M.some(c=>c.role!=="system")))return p("No conversation to share. Start a chat first."),!0;try{let u=await new G().createChatShare(P.accessToken,P.workspaceId,o,"public"),S=`${Ye().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 P?E?(yt(!0),p("Delete this chat? (y/N)"),!0):(p("No chat to delete."),!0):(p("Not authenticated."),!0);case"quit":return Z(),!0;case"unknown":return p(`Unknown command: ${I.input}
181
+ Type /help for available commands.`),!0;default:return!1}},[p,A,N,L,je,He,i,l,x,h,v,z,ie,Ce,o,n,Z,Ne,re,le,b,E,M,wt,kt,_,a,d,C,a,he,ze]),Yt=et(I=>{if(dt.current=!1,it){(I===""||I.startsWith("/"))&&(t(I),I.startsWith("/")&&yt(!1));return}if(t(I),ht(I),Be!==null&&Ke(null),f&&(w(null),te([])),I.startsWith("/")&&!I.includes(" ")){let g=es(I);de(g),F(0),O(g.length>0)}else O(!1),de([])},[f,Be,it,t]),Nt=et((I,g=!1)=>{if(I>=0&&I<K.length){let c=K[I];O(!1),de([]),c.name==="model"?(t("/model "),Ne("model")):c.name==="agent"?(t("/agent "),Ne("agent")):c.name==="skills"?(t("/skills "),Ne("skills")):c.name==="schedules"?(t("/schedules "),Ne("schedules")):c.name==="connectors"?(t("/connectors "),Ne("connectors")):c.name==="capabilities"?(t("/capabilities "),Ne("capabilities")):c.name==="chats"?(t("/chats "),Ne("chats")):c.name==="profile"?(t("/profile "),Ne("profile")):g?(t(""),xt({type:c.name})):t(`/${c.name}`)}},[K,Ne,t,xt]),Xt=et(async I=>{dt.current=!1;let g=I.trim();if(!g||it)return;if(f==="model"&&$.length>0){let u=$[R];u&&(l?re(`Switched to model: ${u.name} (new chat)`):p(`Switched to model: ${u.name}`),a(u.id),d(void 0),C(null)),w(null),te([]),t("");return}if(f==="agent"&&$.length>0){let u=$[R];u&&(u.id!==l?re(`Switched to agent: ${u.name} (new chat)`):p(`Switched to agent: ${u.name}`),d(u.id),a(void 0)),w(null),te([]),t("");return}if(f==="skills"&&$.length>0){let u=$[R];if(u){let m=je.find(S=>S.id===u.id);m&&p(`Skill: ${m.name}
177
182
  ${m.description}
178
183
  Provider: ${m.provider}
179
184
  Author: ${m.author.name}
180
185
  ID: ${m.id}`)}w(null),te([]),t("");return}if(f==="schedules"&&$.length>0){let u=$[R];if(u){let m=He.find(S=>S.id===u.id);if(m){let S=m.nextRunAt?new Date(m.nextRunAt).toLocaleString():"-";p(`Schedule: ${m.name}
181
186
  Agent: ${m.agent.name}
182
187
  Status: ${m.isActive?"Active":"Paused"}
183
- Repeat: ${Bo(m.config)}
188
+ Repeat: ${Wo(m.config)}
184
189
  Next Run: ${S}
185
- ID: ${m.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(ot);T(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let m=L.filter(S=>ot.has(S.id)).map(S=>S.name);p(m.length>0?`Active connectors: ${m.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=De.has("sandbox"),m=De.has("webSearch"),S=De.has("imageGeneration"),k=De.has("chart"),D=De.has("fileSystem");y(u),j(m),X(S),q(k),U(D),oe.setCapabilities({sandbox:u,webSearch:m,imageGeneration:S,chart:k}),oe.setLocalTools({fileSystem:D});let me=[];u&&me.push("Sandbox"),m&&me.push("Web Search"),S&&me.push("Image Generation"),k&&me.push("Chart"),D&&me.push("FileSystem"),p(me.length>0?`Active capabilities: ${me.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&$.length>0){let u=$[R];if(u){let m=J.getCurrentProfileName();u.id!==m?(J.setOverrideProfile(u.id),J.setCurrentProfile(u.id),he(u.id),ze(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&K.length>0){Nt(Se,!0);return}Ke(null),ht(""),Co(u=>u.length>0&&u.at(-1)===g?u:[...u,g]);let c=es(g);if(c){await bt(c),t(""),O(!1);return}if(B){p("Please wait for file uploads to complete.");return}t(""),O(!1),we(g)},[we,bt,ne,K,Se,Nt,f,$,R,ot,De,L,je,He,p,t,l,re,a,d,C,T,y,j,X,q,U,B,he,ze,it,P,E,o]);return Or((I,g)=>{if(g.ctrl&&I==="c"){if(e.length>0){Yt(""),dt.current=!0,p("Press Ctrl+C again to exit.");return}if(dt.current){Z();return}Z();return}if(g.ctrl&&I==="o"){H(c=>!c);return}if(it){if(g.escape||g.return||I==="n"||I==="N"){yt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){yt(!1),t(""),P&&E&&new G().deleteChat(P.accessToken,P.workspaceId,o).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&$.length>0){if(g.upArrow){xe(c=>c<=0?$.length-1:c-1);return}if(g.downArrow){xe(c=>c>=$.length-1?0:c+1);return}if(g.escape){w(null),te([]),t("");return}if(g.return){if(f==="model"){let c=$[R];c&&(l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id))}else if(f==="agent"){let c=$[R];c&&(c.id!==l?re(`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=$[R];if(c){let u=je.find(m=>m.id===c.id);u&&p(`Skill: ${u.name}
190
+ ID: ${m.id}`)}}w(null),te([]),t("");return}if(f==="connectors"){let u=Array.from(ot);T(u.length>0?u:void 0),oe.setDefaultConnectorIds(u);let m=L.filter(S=>ot.has(S.id)).map(S=>S.name);p(m.length>0?`Active connectors: ${m.join(", ")}`:"All connectors disabled."),w(null),te([]),t("");return}if(f==="capabilities"){let u=De.has("sandbox"),m=De.has("webSearch"),S=De.has("imageGeneration"),k=De.has("chart"),D=De.has("fileSystem");y(u),j(m),X(S),q(k),U(D),oe.setCapabilities({sandbox:u,webSearch:m,imageGeneration:S,chart:k}),oe.setLocalTools({fileSystem:D});let me=[];u&&me.push("Sandbox"),m&&me.push("Web Search"),S&&me.push("Image Generation"),k&&me.push("Chart"),D&&me.push("FileSystem"),p(me.length>0?`Active capabilities: ${me.join(", ")}`:"All capabilities disabled."),w(null),te([]),t("");return}if(f==="profile"&&$.length>0){let u=$[R];if(u){let m=J.getCurrentProfileName();u.id!==m?(J.setOverrideProfile(u.id),J.setCurrentProfile(u.id),he(u.id),ze(),re(`Switched to profile: ${u.name}`)):p(`Already using profile: ${u.name}`)}w(null),te([]),t("");return}if(ne&&K.length>0){Nt(Se,!0);return}Ke(null),ht(""),Co(u=>u.length>0&&u.at(-1)===g?u:[...u,g]);let c=ts(g);if(c){await xt(c),t(""),O(!1);return}if(W){p("Please wait for file uploads to complete.");return}t(""),O(!1),we(g)},[we,xt,ne,K,Se,Nt,f,$,R,ot,De,L,je,He,p,t,l,re,a,d,C,T,y,j,X,q,U,W,he,ze,it,P,E,o]);return Lr((I,g)=>{if(g.ctrl&&I==="c"){if(e.length>0){Yt(""),dt.current=!0,p("Press Ctrl+C again to exit.");return}if(dt.current){Z();return}Z();return}if(g.ctrl&&I==="o"){H(c=>!c);return}if(it){if(g.escape||g.return||I==="n"||I==="N"){yt(!1),t(""),p("Chat deletion cancelled.");return}if(I==="y"||I==="Y"){yt(!1),t(""),P&&E&&new G().deleteChat(P.accessToken,P.workspaceId,o).then(()=>{re("Chat deleted. Started a new chat.")}).catch(u=>{p(`Failed to delete chat: ${u.message||"Unknown error"}`)});return}return}if(f&&$.length>0){if(g.upArrow){be(c=>c<=0?$.length-1:c-1);return}if(g.downArrow){be(c=>c>=$.length-1?0:c+1);return}if(g.escape){w(null),te([]),t("");return}if(g.return){if(f==="model"){let c=$[R];c&&(l?re(`Switched to model: ${c.name} (new chat)`):p(`Switched to model: ${c.name}`),a(c.id),d(void 0),C(null),oe.setDefaultModel(c.id))}else if(f==="agent"){let c=$[R];c&&(c.id!==l?re(`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=$[R];if(c){let u=je.find(m=>m.id===c.id);u&&p(`Skill: ${u.name}
186
191
  ${u.description}
187
192
  Provider: ${u.provider}
188
193
  Author: ${u.author.name}
189
194
  ID: ${u.id}`)}}else if(f==="schedules"){let c=$[R];if(c){let u=He.find(m=>m.id===c.id);if(u){let m=u.nextRunAt?new Date(u.nextRunAt).toLocaleString():"-";p(`Schedule: ${u.name}
190
195
  Agent: ${u.agent.name}
191
196
  Status: ${u.isActive?"Active":"Paused"}
192
- Repeat: ${Bo(u.config)}
197
+ Repeat: ${Wo(u.config)}
193
198
  Next Run: ${m}
194
- ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(ot);T(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=L.filter(m=>ot.has(m.id)).map(m=>m.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=De.has("sandbox"),u=De.has("webSearch"),m=De.has("imageGeneration"),S=De.has("chart"),k=De.has("fileSystem");y(c),j(u),X(m),q(S),U(k),oe.setCapabilities({sandbox:c,webSearch:u,imageGeneration:m,chart:S}),oe.setLocalTools({fileSystem:k});let D=[];c&&D.push("Sandbox"),u&&D.push("Web Search"),m&&D.push("Image Generation"),S&&D.push("Chart"),k&&D.push("FileSystem"),p(D.length>0?`Active capabilities: ${D.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=$[R];if(c){let u=xo.find(m=>m.id===c.id);u&&P&&(s(u.id),r(u.title||void 0),ge(!0),new G().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(D=>D.role==="user"||D.role==="assistant").map(D=>({role:D.role,content:pt(D.parts,!1),parts:D.parts})).filter(D=>D.content).toReversed();_(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=$[R];if(c){let u=J.getCurrentProfileName();c.id!==u?(J.setOverrideProfile(c.id),J.setCurrentProfile(c.id),he(c.id),ze(),re(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),te([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let c=$[R];c&&(f==="connectors"?nt:st)(m=>{let S=new Set(m);return S.has(c.id)?S.delete(c.id):S.add(c.id),S});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set($.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set);return}return}if(ne&&K.length>0){if(g.upArrow){F(c=>c<=0?K.length-1:c-1);return}if(g.downArrow){F(c=>c>=K.length-1?0:c+1);return}if(g.escape){O(!1),de([]);return}if(g.tab){Nt(Se);return}}if(g.upArrow){if(e.includes(`
195
- `)||rt.length===0)return;if(Me===null){ht(e);let u=rt.length-1;Ke(u),t(rt[u]);return}let c=Math.max(0,Me-1);Ke(c),t(rt[c]);return}if(g.downArrow){if(e.includes(`
196
- `)||Me===null)return;if(Me>=rt.length-1){Ke(null),t(qt);return}let c=Me+1;Ke(c),t(rt[c])}}),{suggestions:K,suggestionIndex:Se,showSuggestions:ne,argMode:f,argItems:$,argIndex:R,selectedConnectorIds:ot,selectedCapabilities:De,deleteConfirmMode:it,handleInputChange:Yt,handleSubmit:Xt}}import{useCallback as Wt,useRef as Rr,useState as Ur}from"react";function ns({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[r,i]=Ur([]),a=Rr(0),l=Wt(y=>{if(!(!Array.isArray(o)||o.length===0)){for(let v of o)if(v.models.some(z=>z.id===y))return v.id;return o[0]?.id}},[o]),d=Wt(async y=>{if(!e){n?.(y.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(y.filename,"Model providers not loaded yet. Please wait and try again.");return}let v=t?l(t):o[0]?.id;if(!v){n?.(y.filename,"No model provider available");return}let j=`file-${++a.current}`;i(z=>[...z,{id:j,filename:y.filename,mimeType:y.mimeType,status:"uploading"}]);try{let X=await new G().uploadFile(e.accessToken,e.workspaceId,y,v);i(ie=>ie.map(q=>q.id===j?{...q,status:"uploaded",fileId:X.id}:q)),s?.(y.filename)}catch(z){let X=z instanceof Error?z.message:"Upload failed";i(ie=>ie.map(q=>q.id===j?{...q,status:"error",error:X}:q)),n?.(y.filename,X)}},[e,t,l,o,s,n]),x=Wt(y=>{i(v=>v.filter(j=>j.id!==y))},[]),C=Wt(()=>{i([])},[]),b=Wt(()=>r.filter(y=>y.status==="uploaded"&&y.fileId).map(y=>y.fileId),[r]),T=r.some(y=>y.status==="uploading"),h=r.length>0;return{pendingFiles:r,addFile:d,removeFile:x,clearFiles:C,getUploadedFileIds:b,hasUploadingFiles:T,hasFiles:h}}import{jsx as Y,jsxs as ue}from"react/jsx-runtime";var Fr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Fo,Fo,jo,jo,ft,ft,ft,ft],rs=Fr.map((e,t)=>`${Wr[t]??ft}${e}${se}`).join(`
197
- `),Br=`${ft}EntryDesk${se}`,Mr=500;function Jr(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 Gr(e){let t=Jr(e);return Math.max(...t.split(`
198
- `).map(o=>o.length))}function Vr(e){let t=Gr(rs);return e>=t?rs:Br}function is({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:r,enableSandbox:i=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:x=!0}){let C=process.stdout.columns??80,b=Vr(C),T=ss(null),h=jn(s,n),{state:y,setState:v,messages:j,setMessages:z,input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:L,credentials:W,setCredentials:E,currentResponse:ge,setCurrentResponse:_,fullOutput:p,setFullOutput:re,addSystemMessage:we,startNewChat:H}=h,{credentials:P}=Wn(v);fo(()=>{P&&!W&&E(P)},[P,W,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:B}=Bn(W),{currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,activeConnectorIds:F,setActiveConnectorIds:ne}=Yn(t,e,r),O=ss(!1);fo(()=>{if(!O.current){if(O.current=!0,!t&&!e){let k=oe.getDefaultModel();k&&K(k)}if(!r&&!e){let k=oe.getDefaultConnectorIds();k&&ne(k.length>0?k:void 0)}}},[t,e,r,K,ne]);let{currentAgentDetails:f}=qn(de,W),{sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:xe,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:xo,capabilityLabelMap:Kt}=zn(i,a,l,d,x),{pendingFiles:je,addFile:gt,removeFile:He,clearFiles:zt,getUploadedFileIds:rt,hasUploadingFiles:Co,hasFiles:Me}=ns({credentials:W,currentModel:Z,modelProviders:le,onUploadSuccess:k=>{we(`\u2713 Attached: ${k}`)},onUploadError:(k,D)=>{we(`\u2717 Failed to upload ${k}: ${D}`)}}),{sendMessage:Ke}=Gn({chatId:q,credentials:W,currentAgentId:de,currentModel:Z,activeConnectorIds:F,sandbox:w,webSearch:te,imageGeneration:xe,chart:nt,localTools:st,fullOutput:p,setMessages:z,setState:v,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:L,getFileIds:rt,clearFiles:zt}),qt=Go(k=>{H(k),_("")},[H]),[ht,dt]=jr(!1),it=Go(async k=>{let D=k.text.trim(),me=lo(D);if(/^https?:\/\//.test(me))return;if(await On(D)&&Dn(me)){let ce=await Ln(D);ce&&(k.preventDefault(),await gt(ce))}},[gt]),yt=Go(async()=>{if(!(ht||y.status!=="ready")){if(B||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),dt(!0);try{let k=await _n();if(k){let D=`clipboard-${Date.now()}.png`;we(`Uploading: ${D} (${Math.round(k.buffer.length/1024)}KB)`),await gt({buffer:k.buffer,filename:D,mimeType:k.mime})}else we("No image found in clipboard. Copy an image first.")}catch(k){let D=k instanceof Error?k.message:"Failed to read clipboard";we(`Clipboard error: ${D}`)}finally{dt(!1)}}},[gt,we,ht,y.status,B,le.length]),{suggestions:wt,suggestionIndex:kt,showSuggestions:Ne,argMode:he,argItems:ze,argIndex:bt,selectedConnectorIds:Yt,selectedCapabilities:Nt,deleteConfirmMode:Xt,handleInputChange:I,handleSubmit:g}=os({input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:ne,sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:xe,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:xo,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:j,hasPersistedChat:N,setHasPersistedChat:L,setMessages:z,addSystemMessage:we,startNewChat:qt,sendMessage:Ke,setFullOutput:re,credentials:W,setCredentials:E,setState:v,defaultCapabilities:{sandbox:i,webSearch:a,imageGeneration:l,chart:d,fileSystem:x},capabilityLabelMap:Kt,hasUploadingFiles:Co});if(Mo((k,D)=>{(D.ctrl||D.meta)&&k==="v"&&yt()},{isActive:y.status==="ready"&&!he}),Mo((k,D)=>{if(!D.escape)return;let me=Date.now(),M=T.current;T.current=me,!(!M||me-M>Mr)&&(he||Ne||(T.current=null,Me&&zt(),X.length>0&&I("")))},{isActive:y.status==="ready"}),Mo((k,D)=>{D.return&&(qt("Started a new chat."),v({status:"ready"}))},{isActive:y.status==="error"}),fo(()=>{if(W&&!B&&y.status==="loading")if(!Z&&!de){let k=oe.getDefaultModel(),D=k&&Q.some(M=>M.id===k),me=D?k:Q[0]?.id;me?(D||oe.setDefaultModel(me),K(me),v({status:"ready"})):pe.length===0?v({status:"no-model"}):v({status:"ready"})}else v({status:"ready"})},[W,B,Z,de,Q,pe,y.status,K,v]),fo(()=>{o&&W&&y.status==="ready"&&Ke(o)},[W,o]),y.status==="loading")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Initializing chat..."})]})]});if(y.status==="not-logged-in")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"Not logged in"}),Y(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(y.status==="no-workspace")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No workspace selected"}),Y(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(y.status==="no-model")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),Y(V,{color:"yellow",children:"No model or agent specified"}),s&&Y(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),Y(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),Y(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(y.status==="error")return ue(ve,{flexDirection:"column",children:[Y(V,{children:b}),ue(V,{color:"red",children:["Error: ",y.message]}),Y(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":F&&F.length>0?ee.filter(k=>F.includes(k.id)).map(k=>k.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let k of f.capabilities)u.push(Kt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),xe&&u.push("Image"),nt&&u.push("Chart");st&&u.push("FileSystem");let m=J.getCurrentProfileName(),S=m!=="default";return ue(ve,{flexDirection:"column",children:[ue(ve,{marginBottom:1,flexDirection:"column",children:[Y(V,{children:b}),ue(ve,{children:[Y(V,{bold:!0,color:"cyan",children:U?`Continuing: ${U}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.9.2"]}),S&&ue(V,{color:"magenta",children:[" [",m,"]"]}),Y(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),j.map((k,D)=>{let me=k.parts&&p?pt(k.parts,!0):k.content,M=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ce=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return ue(ve,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:M,children:[ce,":"]}),Y(Uo,{text:me})]},D)}),ge&&ue(ve,{flexDirection:"column",marginBottom:1,children:[Y(V,{bold:!0,color:"blue",children:"Assistant:"}),Y(Uo,{text:ge})]}),y.status==="ready"&&Y(gn,{suggestions:wt,activeIndex:kt,visible:Ne}),y.status==="ready"&&he&&Y(mn,{items:ze,activeIndex:bt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?Yt:he==="capabilities"?Nt:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),y.status==="sending"&&!ge?ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Thinking..."})]}):y.status==="ready"&&!he?ue(ve,{flexDirection:"column",children:[Xt&&Y(ve,{marginBottom:1,children:Y(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Me&&!Xt&&ue(ve,{marginBottom:1,flexDirection:"row",gap:1,children:[Y(V,{dimColor:!0,children:"Attachments:"}),je.map((k,D)=>ue(V,{children:[k.status==="uploading"?ue(V,{color:"yellow",children:[Y(Jo,{type:"dots"})," ",k.filename]}):k.status==="error"?ue(V,{color:"red",children:["\u2717 ",k.filename]}):ue(V,{color:"green",children:["\u2713 ",k.filename]}),D<je.length-1&&Y(V,{children:", "})]},k.id))]}),ue(ve,{children:[Y(V,{color:"green",children:"> "}),Y($n,{value:X,onChange:I,onSubmit:g,onPaste:it,leadingOffset:2,multiline:!0})]})]}):null,ue(ve,{marginTop:1,flexDirection:"column",children:[ue(ve,{gap:2,children:[ue(V,{children:[Y(V,{dimColor:!0,children:"Model: "}),Y(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(k=>k.id===Z)?.name||Z||"none"})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Connectors: "}),Y(V,{color:"cyan",children:c})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Capabilities: "}),Y(V,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(V,{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 Yr}from"react/jsx-runtime";async function Kr(){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 r=n[s-1],i;if(!r.agentId){let{messages:a}=await e.getMessages(t,o,r.id,10);i=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:r,modelId:i}}var St="\x1B[2m",_e="\x1B[0m",Vo="\x1B[36m",us="\x1B[33m",mo="\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 go(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
199
+ ID: ${u.id}`)}}}else if(f==="connectors"){let c=Array.from(ot);T(c.length>0?c:void 0),oe.setDefaultConnectorIds(c);let u=L.filter(m=>ot.has(m.id)).map(m=>m.name);p(u.length>0?`Active connectors: ${u.join(", ")}`:"All connectors disabled.")}else if(f==="capabilities"){let c=De.has("sandbox"),u=De.has("webSearch"),m=De.has("imageGeneration"),S=De.has("chart"),k=De.has("fileSystem");y(c),j(u),X(m),q(S),U(k),oe.setCapabilities({sandbox:c,webSearch:u,imageGeneration:m,chart:S}),oe.setLocalTools({fileSystem:k});let D=[];c&&D.push("Sandbox"),u&&D.push("Web Search"),m&&D.push("Image Generation"),S&&D.push("Chart"),k&&D.push("FileSystem"),p(D.length>0?`Active capabilities: ${D.join(", ")}`:"All capabilities disabled.")}else if(f==="chats"){let c=$[R];if(c){let u=bo.find(m=>m.id===c.id);u&&P&&(s(u.id),r(u.title||void 0),ge(!0),new G().getMessages(P.accessToken,P.workspaceId,u.id,20).then(({messages:S})=>{let k=S.filter(D=>D.role==="user"||D.role==="assistant").map(D=>({role:D.role,content:pt(D.parts,!1),parts:D.parts})).filter(D=>D.content).toReversed();_(k),p(`Switched to: ${u.title||"Untitled"}`)}).catch(()=>{p("Failed to load chat messages.")}))}}else if(f==="profile"){let c=$[R];if(c){let u=J.getCurrentProfileName();c.id!==u?(J.setOverrideProfile(c.id),J.setCurrentProfile(c.id),he(c.id),ze(),re(`Switched to profile: ${c.name}`)):p(`Already using profile: ${c.name}`)}}w(null),te([]),t("");return}if(I===" "&&(f==="connectors"||f==="capabilities")){let c=$[R];c&&(f==="connectors"?nt:st)(m=>{let S=new Set(m);return S.has(c.id)?S.delete(c.id):S.add(c.id),S});return}if(I==="a"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set($.map(u=>u.id)));return}if(I==="n"&&(f==="connectors"||f==="capabilities")){(f==="connectors"?nt:st)(new Set);return}return}if(ne&&K.length>0){if(g.upArrow){F(c=>c<=0?K.length-1:c-1);return}if(g.downArrow){F(c=>c>=K.length-1?0:c+1);return}if(g.escape){O(!1),de([]);return}if(g.tab){Nt(Se);return}}if(g.upArrow){if(e.includes(`
200
+ `)||rt.length===0)return;if(Be===null){ht(e);let u=rt.length-1;Ke(u),t(rt[u]);return}let c=Math.max(0,Be-1);Ke(c),t(rt[c]);return}if(g.downArrow){if(e.includes(`
201
+ `)||Be===null)return;if(Be>=rt.length-1){Ke(null),t(qt);return}let c=Be+1;Ke(c),t(rt[c])}}),{suggestions:K,suggestionIndex:Se,showSuggestions:ne,argMode:f,argItems:$,argIndex:R,selectedConnectorIds:ot,selectedCapabilities:De,deleteConfirmMode:it,handleInputChange:Yt,handleSubmit:Xt}}import{useCallback as Mt,useRef as Ur,useState as jr}from"react";function ss({credentials:e,currentModel:t,modelProviders:o,onUploadSuccess:s,onUploadError:n}){let[r,i]=jr([]),a=Ur(0),l=Mt(y=>{if(!(!Array.isArray(o)||o.length===0)){for(let v of o)if(v.models.some(z=>z.id===y))return v.id;return o[0]?.id}},[o]),d=Mt(async y=>{if(!e){n?.(y.filename,"Not logged in");return}if(!Array.isArray(o)||o.length===0){n?.(y.filename,"Model providers not loaded yet. Please wait and try again.");return}let v=t?l(t):o[0]?.id;if(!v){n?.(y.filename,"No model provider available");return}let j=`file-${++a.current}`;i(z=>[...z,{id:j,filename:y.filename,mimeType:y.mimeType,status:"uploading"}]);try{let X=await new G().uploadFile(e.accessToken,e.workspaceId,y,v);i(ie=>ie.map(q=>q.id===j?{...q,status:"uploaded",fileId:X.id}:q)),s?.(y.filename)}catch(z){let X=z instanceof Error?z.message:"Upload failed";i(ie=>ie.map(q=>q.id===j?{...q,status:"error",error:X}:q)),n?.(y.filename,X)}},[e,t,l,o,s,n]),b=Mt(y=>{i(v=>v.filter(j=>j.id!==y))},[]),C=Mt(()=>{i([])},[]),x=Mt(()=>r.filter(y=>y.status==="uploaded"&&y.fileId).map(y=>y.fileId),[r]),T=r.some(y=>y.status==="uploading"),h=r.length>0;return{pendingFiles:r,addFile:d,removeFile:b,clearFiles:C,getUploadedFileIds:x,hasUploadingFiles:T,hasFiles:h}}import{jsx as Y,jsxs as ue}from"react/jsx-runtime";var Mr=[" ______ _ ____ _","| ____| | | | _ \\ | |","| |__ _ __ | |_ _ __ _ _ | | | | ___ ___| | __","| __| | '_ \\| __| '__| | | || | | |/ _ \\/ __| |/ /","| |____| | | | |_| | | |_| || |_| | __/\\__ \\ <","|______|_| |_|\\__|_| \\__, ||____/ \\___||___/_|\\_\\"," __/ |"," |___/"],Wr=[Fo,Fo,jo,jo,ft,ft,ft,ft],is=Mr.map((e,t)=>`${Wr[t]??ft}${e}${se}`).join(`
202
+ `),Br=`${ft}EntryDesk${se}`,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 Vr(e){let t=Gr(e);return Math.max(...t.split(`
203
+ `).map(o=>o.length))}function Hr(e){let t=Vr(is);return e>=t?is:Br}function as({agentId:e,model:t,message:o,chatId:s,chatTitle:n,connectorIds:r,enableSandbox:i=!0,enableWebSearch:a=!1,enableImageGeneration:l=!1,enableChart:d=!1,enableFileSystem:b=!0}){let C=process.stdout.columns??80,x=Hr(C),T=rs(null),h=Fn(s,n),{state:y,setState:v,messages:j,setMessages:z,input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,hasPersistedChat:N,setHasPersistedChat:L,credentials:M,setCredentials:E,currentResponse:ge,setCurrentResponse:_,fullOutput:p,setFullOutput:re,addSystemMessage:we,startNewChat:H}=h,{credentials:P}=Wn(v);fo(()=>{P&&!M&&E(P)},[P,M,E]);let{availableConnectors:ee,availableModels:Q,availableAgents:pe,modelProviders:le,loading:W}=Bn(M),{currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,activeConnectorIds:F,setActiveConnectorIds:ne}=Xn(t,e,r),O=rs(!1);fo(()=>{if(!O.current){if(O.current=!0,!t&&!e){let k=oe.getDefaultModel();k&&K(k)}if(!r&&!e){let k=oe.getDefaultConnectorIds();k&&ne(k.length>0?k:void 0)}}},[t,e,r,K,ne]);let{currentAgentDetails:f}=Yn(de,M),{sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:be,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:bo,capabilityLabelMap:Kt}=qn(i,a,l,d,b),{pendingFiles:je,addFile:gt,removeFile:He,clearFiles:zt,getUploadedFileIds:rt,hasUploadingFiles:Co,hasFiles:Be}=ss({credentials:M,currentModel:Z,modelProviders:le,onUploadSuccess:k=>{we(`\u2713 Attached: ${k}`)},onUploadError:(k,D)=>{we(`\u2717 Failed to upload ${k}: ${D}`)}}),{sendMessage:Ke}=Vn({chatId:q,credentials:M,currentAgentId:de,currentModel:Z,activeConnectorIds:F,sandbox:w,webSearch:te,imageGeneration:be,chart:nt,localTools:st,fullOutput:p,setMessages:z,setState:v,setCurrentResponse:_,setCredentials:E,setHasPersistedChat:L,getFileIds:rt,clearFiles:zt}),qt=Go(k=>{H(k),_("")},[H]),[ht,dt]=Fr(!1),it=Go(async k=>{let D=k.text.trim(),me=lo(D);if(/^https?:\/\//.test(me))return;if(await Ln(D)&&On(me)){let ce=await Rn(D);ce&&(k.preventDefault(),await gt(ce))}},[gt]),yt=Go(async()=>{if(!(ht||y.status!=="ready")){if(W||le.length===0){we("Please wait for resources to load before pasting images.");return}we("Reading clipboard..."),dt(!0);try{let k=await Dn();if(k){let D=`clipboard-${Date.now()}.png`;we(`Uploading: ${D} (${Math.round(k.buffer.length/1024)}KB)`),await gt({buffer:k.buffer,filename:D,mimeType:k.mime})}else we("No image found in clipboard. Copy an image first.")}catch(k){let D=k instanceof Error?k.message:"Failed to read clipboard";we(`Clipboard error: ${D}`)}finally{dt(!1)}}},[gt,we,ht,y.status,W,le.length]),{suggestions:wt,suggestionIndex:kt,showSuggestions:Ne,argMode:he,argItems:ze,argIndex:xt,selectedConnectorIds:Yt,selectedCapabilities:Nt,deleteConfirmMode:Xt,handleInputChange:I,handleSubmit:g}=ns({input:X,setInput:ie,chatId:q,setChatId:Ce,currentChatTitle:U,setCurrentChatTitle:A,currentModel:Z,setCurrentModel:K,currentAgentId:de,setCurrentAgentId:Se,currentAgentDetails:f,setCurrentAgentDetails:()=>{},activeConnectorIds:F,setActiveConnectorIds:ne,sandbox:w,setSandbox:$,webSearch:te,setWebSearch:R,imageGeneration:be,setImageGeneration:ot,chart:nt,setChart:De,fileSystem:st,setFileSystem:bo,availableModels:Q,availableAgents:pe,availableConnectors:ee,messages:j,hasPersistedChat:N,setHasPersistedChat:L,setMessages:z,addSystemMessage:we,startNewChat:qt,sendMessage:Ke,setFullOutput:re,credentials:M,setCredentials:E,setState:v,defaultCapabilities:{sandbox:i,webSearch:a,imageGeneration:l,chart:d,fileSystem:b},capabilityLabelMap:Kt,hasUploadingFiles:Co});if(Bo((k,D)=>{(D.ctrl||D.meta)&&k==="v"&&yt()},{isActive:y.status==="ready"&&!he}),Bo((k,D)=>{if(!D.escape)return;let me=Date.now(),B=T.current;T.current=me,!(!B||me-B>Jr)&&(he||Ne||(T.current=null,Be&&zt(),X.length>0&&I("")))},{isActive:y.status==="ready"}),Bo((k,D)=>{D.return&&(qt("Started a new chat."),v({status:"ready"}))},{isActive:y.status==="error"}),fo(()=>{if(M&&!W&&y.status==="loading")if(!Z&&!de){let k=oe.getDefaultModel(),D=k&&Q.some(B=>B.id===k),me=D?k:Q[0]?.id;me?(D||oe.setDefaultModel(me),K(me),v({status:"ready"})):pe.length===0?v({status:"no-model"}):v({status:"ready"})}else v({status:"ready"})},[M,W,Z,de,Q,pe,y.status,K,v]),fo(()=>{o&&M&&y.status==="ready"&&Ke(o)},[M,o]),y.status==="loading")return ue(ve,{flexDirection:"column",children:[Y(V,{children:x}),ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Initializing chat..."})]})]});if(y.status==="not-logged-in")return ue(ve,{flexDirection:"column",children:[Y(V,{children:x}),Y(V,{color:"yellow",children:"Not logged in"}),Y(V,{dimColor:!0,children:"Run `entrydesk login` to authenticate first."})]});if(y.status==="no-workspace")return ue(ve,{flexDirection:"column",children:[Y(V,{children:x}),Y(V,{color:"yellow",children:"No workspace selected"}),Y(V,{dimColor:!0,children:"Run `entrydesk workspaces` to select a workspace first."})]});if(y.status==="no-model")return ue(ve,{flexDirection:"column",children:[Y(V,{children:x}),Y(V,{color:"yellow",children:"No model or agent specified"}),s&&Y(V,{dimColor:!0,children:"Could not determine the model used in this chat."}),Y(V,{dimColor:!0,children:"Please specify a model with --model or use an agent with -a."}),Y(V,{dimColor:!0,children:"Example: entrydesk chat -c 1 -i --model gemini-2.5-flash-lite"})]});if(y.status==="error")return ue(ve,{flexDirection:"column",children:[Y(V,{children:x}),ue(V,{color:"red",children:["Error: ",y.message]}),Y(V,{dimColor:!0,children:"Press Enter to start a new chat, or Ctrl+C to exit"})]});let c=de?f?f.connectors&&f.connectors.length>0?f.connectors.map(k=>k.name).join(", "):"none":"loading...":F&&F.length>0?ee.filter(k=>F.includes(k.id)).map(k=>k.name).join(", ")||`${F.length} connector(s)`:"none",u=[];if(de)if(f?.capabilities)for(let k of f.capabilities)u.push(Kt.get(k)??k);else u.push("loading...");else w&&u.push("Sandbox"),te&&u.push("Web"),be&&u.push("Image"),nt&&u.push("Chart");st&&u.push("FileSystem");let m=J.getCurrentProfileName(),S=m!=="default";return ue(ve,{flexDirection:"column",children:[ue(ve,{marginBottom:1,flexDirection:"column",children:[Y(V,{children:x}),ue(ve,{children:[Y(V,{bold:!0,color:"cyan",children:U?`Continuing: ${U}`:"EntryDesk CLI"}),ue(V,{dimColor:!0,children:[" v","1.10.0"]}),S&&ue(V,{color:"magenta",children:[" [",m,"]"]}),Y(V,{dimColor:!0,children:" (type /help for commands)"})]})]}),j.map((k,D)=>{let me=k.parts&&p?pt(k.parts,!0):k.content,B=k.role==="user"?"green":k.role==="system"?"yellow":"blue",ce=k.role==="user"?"You":k.role==="system"?"System":"Assistant";return ue(ve,{flexDirection:"column",marginBottom:1,children:[ue(V,{bold:!0,color:B,children:[ce,":"]}),Y(Uo,{text:me})]},D)}),ge&&ue(ve,{flexDirection:"column",marginBottom:1,children:[Y(V,{bold:!0,color:"blue",children:"Assistant:"}),Y(Uo,{text:ge})]}),y.status==="ready"&&Y(hn,{suggestions:wt,activeIndex:kt,visible:Ne}),y.status==="ready"&&he&&Y(gn,{items:ze,activeIndex:xt,pageSize:he==="agent"||he==="skills"||he==="model"?5:10,selectedIds:he==="connectors"?Yt:he==="capabilities"?Nt:void 0,multiSelect:he==="connectors"||he==="capabilities",visible:!0,title:he==="model"?"Select model:":he==="agent"?"Select agent:":he==="skills"?"Select skill:":he==="connectors"?"Select connectors:":he==="capabilities"?"Select capabilities:":"Select chat:"}),y.status==="sending"&&!ge?ue(ve,{children:[Y(V,{color:"cyan",children:Y(Jo,{type:"dots"})}),Y(V,{children:" Thinking..."})]}):y.status==="ready"&&!he?ue(ve,{flexDirection:"column",children:[Xt&&Y(ve,{marginBottom:1,children:Y(V,{color:"yellow",children:"\u26A0\uFE0F Delete this chat? (y/N) "})}),Be&&!Xt&&ue(ve,{marginBottom:1,flexDirection:"row",gap:1,children:[Y(V,{dimColor:!0,children:"Attachments:"}),je.map((k,D)=>ue(V,{children:[k.status==="uploading"?ue(V,{color:"yellow",children:[Y(Jo,{type:"dots"})," ",k.filename]}):k.status==="error"?ue(V,{color:"red",children:["\u2717 ",k.filename]}):ue(V,{color:"green",children:["\u2713 ",k.filename]}),D<je.length-1&&Y(V,{children:", "})]},k.id))]}),ue(ve,{children:[Y(V,{color:"green",children:"> "}),Y(Sn,{value:X,onChange:I,onSubmit:g,onPaste:it,leadingOffset:2,multiline:!0})]})]}):null,ue(ve,{marginTop:1,flexDirection:"column",children:[ue(ve,{gap:2,children:[ue(V,{children:[Y(V,{dimColor:!0,children:"Model: "}),Y(V,{color:"magenta",children:de?f?.model?.name||"loading...":Q.find(k=>k.id===Z)?.name||Z||"none"})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Connectors: "}),Y(V,{color:"cyan",children:c})]}),ue(V,{children:[Y(V,{dimColor:!0,children:"Capabilities: "}),Y(V,{color:"green",children:u.length>0?u.join(", "):"none"})]})]}),ue(V,{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 zr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8").trim()}async function qr(e,t,o,s){if(s<1)return console.error("Chat number must be 1 or greater"),null;let{chats:n}=await e.getChats(t,o,20);if(n.length===0)return console.error("No chats found. Start a new chat first."),null;if(s>n.length)return console.error(`Chat number ${s} not found. You have ${n.length} recent chats.`),console.error("Use `entrydesk chats` to see available chats."),null;let r=n[s-1],i;if(!r.agentId){let{messages:a}=await e.getMessages(t,o,r.id,10);i=a.find(d=>d.role==="assistant"&&d.modelId)?.modelId}return{chat:r,modelId:i}}var St="\x1B[2m",_e="\x1B[0m",Vo="\x1B[36m",ds="\x1B[33m",mo="\x1B[32m",ls="stream-json";function cs(e,t,o,s){e&&t&&(console.error(`Error: Cannot use both ${o} and ${s}`),process.exit(1))}function go(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
199
204
  `)}function ho(e,t){if(t)return e;let o=e.split(`
200
205
  `);if(o.length<=20)return e;let s=o.slice(0,5),n=o.slice(-5),r=o.length-10;return[...s,`${St}... (${r} lines omitted, use --full-output to see all) ...${_e}`,...n].join(`
201
- `)}function qr(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 ho(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]${_e} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),ho(n.join(`
206
+ `)}function Yr(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function us(e,t){if(!e)return"(no result)";if(typeof e!="object")return ho(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(`${ds}[stderr]${_e} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),ho(n.join(`
202
207
  `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
203
- `);return ho(n||JSON.stringify(e,null,2),t)}return ho(JSON.stringify(e,null,2),t)}async function ds(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){ke(ee)}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),r=oe.getDefaultModel(),i=e.message;!i&&!process.stdin.isTTY&&(i=await Kr());let a=new G;async function l(){if(!r)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),r=Q}catch{}}let d,x,C,b;if(e.continue){let ee=await zr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,x=ee.chat.title??void 0,C=ee.chat.agentId??void 0,b=ee.modelId;let Q=e.agentId||e.model||C||b||r;!Q&&!e.interactive&&(await l(),Q=e.agentId||e.model||C||b||r),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
208
+ `);return ho(n||JSON.stringify(e,null,2),t)}return ho(JSON.stringify(e,null,2),t)}async function fs(e){let t,o;try{let ee=await fe();t=ee.accessToken,o=ee.workspaceId}catch(ee){ke(ee)}let s=e.output===ls;e.output&&!s&&(console.error(`Invalid --output value. Supported: ${ls}`),process.exit(1));let n=!s&&(e.plain||!process.stdout.isTTY),r=oe.getDefaultModel(),i=e.message;!i&&!process.stdin.isTTY&&(i=await zr());let a=new G;async function l(){if(!r)try{let{models:ee}=await a.getModels(t,o),Q=ee[0]?.id;if(!Q)return;oe.setDefaultModel(Q),r=Q}catch{}}let d,b,C,x;if(e.continue){let ee=await qr(a,t,o,e.continue);ee||process.exit(1),d=ee.chat.id,b=ee.chat.title??void 0,C=ee.chat.agentId??void 0,x=ee.modelId;let Q=e.agentId||e.model||C||x||r;!Q&&!e.interactive&&(await l(),Q=e.agentId||e.model||C||x||r),!Q&&!e.interactive&&(n||console.log(`Continuing chat: ${ee.chat.title||"Untitled"}`),console.error(`
204
209
  Could not determine model for this chat. Please specify --model or -a.`),console.error('Example: entrydesk chat -c 1 -m "message" --model gemini-2.5-flash-lite'),process.exit(1)),!n&&!e.interactive&&console.log(`Continuing chat: ${ee.chat.title||"Untitled"}
205
- `)}let T=e.agentId||C,h=e.model||b||r||void 0;!T&&!h&&(await l(),h=e.model||b||r||void 0),ls(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),ls(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let y=oe.getCapabilities(),v=e.noSandbox?!1:e.sandbox?!0:y?.sandbox??!0,j=e.webSearch??y?.webSearch??!1,z=e.imageGen??y?.imageGeneration??!1,X=e.chart??y?.chart??!1,ie=oe.getDefaultConnectorIds(),q=e.connectors??ie??void 0,Ce=oe.getLocalTools(),U=e.noFileSystem?!1:e.fileSystem?!0:Ce?.fileSystem??!0;if(e.interactive){Hr(Yr(is,{agentId:T,model:h,message:e.message,chatId:d,chatTitle:x??void 0,connectorIds:q,enableSandbox:v,enableWebSearch:j,enableImageGeneration:z,enableChart:X,enableFileSystem:U}),{exitOnCtrlC:!1});return}let A=!e.continue&&!h&&!T;(!i||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,L=d||po(),W=U?Qt():void 0,E=U?eo():void 0,ge=[],_=po(),p=(ee,Q,pe)=>{let le={id:L};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),T?le.agentId=T:(h&&(le.model=h),le.connectorIds=q??[],le.enableSandbox=v,le.enableWebSearch=j,le.enableImageGeneration=z,le.enableChart=X),W&&(le.clientTools=W),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},re=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",B=new Map,Z=[],K=[];for(;;){let{done:de,value:Se}=await Q.read();if(de)break;le+=pe.decode(Se,{stream:!0});let F=le.split(`
210
+ `)}let T=e.agentId||C,h=e.model||x||r||void 0;!T&&!h&&(await l(),h=e.model||x||r||void 0),cs(e.sandbox,e.noSandbox,"--sandbox","--no-sandbox"),cs(e.fileSystem,e.noFileSystem,"--file-system","--no-file-system");let y=oe.getCapabilities(),v=e.noSandbox?!1:e.sandbox?!0:y?.sandbox??!0,j=e.webSearch??y?.webSearch??!1,z=e.imageGen??y?.imageGeneration??!1,X=e.chart??y?.chart??!1,ie=oe.getDefaultConnectorIds(),q=e.connectors??ie??void 0,Ce=oe.getLocalTools(),U=e.noFileSystem?!1:e.fileSystem?!0:Ce?.fileSystem??!0;if(e.interactive){Kr(Xr(as,{agentId:T,model:h,message:e.message,chatId:d,chatTitle:b??void 0,connectorIds:q,enableSandbox:v,enableWebSearch:j,enableImageGeneration:z,enableChart:X,enableFileSystem:U}),{exitOnCtrlC:!1});return}let A=!e.continue&&!h&&!T;(!i||A)&&(console.error("Usage: entrydesk chat -m <message> --model <model>"),console.error(" entrydesk chat -m <message> -a <agent>"),console.error(" entrydesk chat -c <number> -m <message>"),console.error(' echo "message" | entrydesk chat --model <model>'),console.error(" entrydesk chat -i (interactive mode)"),console.error(""),console.error("Options:"),console.error(" -m, --message Message to send (or pipe via stdin)"),console.error(" --model Model ID to use (required if no agent and no default)"),console.error(" -a, --agent Agent ID to use (required if no model)"),console.error(" -c, --continue Continue recent chat by number (1 = most recent)"),console.error(" -i Interactive mode"),console.error(" --plain Plain text output (no colors/formatting)"),console.error(" --output stream-json Stream JSON events (for scripting)"),console.error(" --full-output Show full tool results without truncation"),console.error(""),console.error("List available models: entrydesk models"),console.error("List available agents: entrydesk agents"),console.error("List recent chats: entrydesk chats"),process.exit(1));let N=e.fullOutput??!1,L=d||po(),M=U?Qt():void 0,E=U?eo():void 0,ge=[],_=po(),p=(ee,Q,pe)=>{let le={id:L};return ee&&(le.message={id:ee.id,createdAt:new Date,role:"user",parts:[{type:"text",text:ee.text}]}),T?le.agentId=T:(h&&(le.model=h),le.connectorIds=q??[],le.enableSandbox=v,le.enableWebSearch=j,le.enableImageGeneration=z,le.enableChart=X),M&&(le.clientTools=M),E&&(le.clientToolSystemPrompt=E),Q&&Q.length>0&&(le.clientToolResults=Q),pe&&pe.length>0&&(le.previousMessages=pe),le},re=async ee=>{if(!ee.body)throw new Error("No response body");let Q=ee.body.getReader(),pe=new TextDecoder,le="",W=new Map,Z=[],K=[];for(;;){let{done:de,value:Se}=await Q.read();if(de)break;le+=pe.decode(Se,{stream:!0});let F=le.split(`
206
211
  `);le=F.pop()||"";for(let ne of F){let O=ne.trimEnd();if(O==="data: [DONE]"){s&&go("done");continue}if(O.startsWith("data: "))try{let f=JSON.parse(O.slice(6));if(f.type&&K.push(f),s){f.type==="text-delta"&&f.delta!==void 0?go("text-delta",f.delta):f.type==="reasoning-delta"&&f.delta!==void 0?go("reasoning-delta",f.delta):go(f.type||"event",f);continue}if(n){if(f.type==="text-delta"&&f.delta&&process.stdout.write(f.delta),U&&(f.type==="tool-input-available"||f.type==="tool-call")&&f.toolCallId&&f.toolName&&Ze(f.toolName)){let w=f.args||f.input||{};Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w})}continue}switch(f.type){case"reasoning-delta":f.delta&&process.stdout.write(`${St}${f.delta}${_e}`);break;case"reasoning-end":process.stdout.write(`
207
212
 
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){B.set(f.toolCallId,{toolName:f.toolName});let $=U&&Ze(f.toolName)?`${mo}[LOCAL]${_e} `:"";console.log(`
209
- ${Vo}\u250C\u2500 ${$}Tool Call: ${f.toolName}${_e}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},$=qr(w);console.log(`${us}\u2502 Arguments:${_e}`);for(let te of $.split(`
210
- `))console.log(`${St}\u2502 ${te}${_e}`);U&&Ze(f.toolName)&&(B.set(f.toolCallId,{toolName:f.toolName,args:w}),Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=B.get(f.toolCallId),$=cs(f.result,N);console.log(`${mo}\u2502 Result:${_e}`);for(let te of $.split(`
213
+ `);break;case"text-delta":f.delta&&process.stdout.write(f.delta);break;case"tool-call-streaming-start":case"tool-input-start":if(f.toolCallId&&f.toolName){W.set(f.toolCallId,{toolName:f.toolName});let $=U&&Ze(f.toolName)?`${mo}[LOCAL]${_e} `:"";console.log(`
214
+ ${Vo}\u250C\u2500 ${$}Tool Call: ${f.toolName}${_e}`)}break;case"tool-call":case"tool-input-available":if(f.toolCallId&&f.toolName){let w=f.args||f.input||{},$=Yr(w);console.log(`${ds}\u2502 Arguments:${_e}`);for(let te of $.split(`
215
+ `))console.log(`${St}\u2502 ${te}${_e}`);U&&Ze(f.toolName)&&(W.set(f.toolCallId,{toolName:f.toolName,args:w}),Z.push({toolCallId:f.toolCallId,toolName:f.toolName,args:w}))}break;case"tool-result":if(f.toolCallId){let w=W.get(f.toolCallId),$=us(f.result,N);console.log(`${mo}\u2502 Result:${_e}`);for(let te of $.split(`
211
216
  `))console.log(`${St}\u2502 ${te}${_e}`);console.log(`${Vo}\u2514\u2500 ${w?.toolName||"Tool"} completed${_e}
212
- `),B.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${St}Error: ${f.errorText}${_e}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:K}},we=p({id:po(),text:i}),H=await a.chat(t,o,we),P=await re(H);for(ge=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let B of P.pendingClientTools){!n&&!s&&console.log(`${mo}\u2502 Executing locally...${_e}`);let Z=await to(B.toolName,B.args),K=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:B.toolCallId,toolName:B.toolName,content:[{type:"text",text:K}],isError:!Z.success}),!n&&!s){let de=cs(Z.success?Z.result:{error:Z.error},N);console.log(`${mo}\u2502 Result:${_e}`);for(let Se of de.split(`
213
- `))console.log(`${St}\u2502 ${Se}${_e}`);console.log(`${Vo}\u2514\u2500 ${B.toolName} completed${_e}
214
- `)}}let Q=ge.map(B=>{if(B.type==="tool-call"){let Z=ee.find(de=>de.toolCallId===B.toolCallId),K=Z?.content.filter(de=>de.type==="text").map(de=>de.text).join(`
215
- `);return{type:"tool-invocation",toolCallId:B.toolCallId,toolName:B.toolName,args:B.args,state:Z?.isError?"output-error":"output-available",output:K}}return B}),pe=[{id:_,role:"assistant",parts:Q}];_=po();let le=p(void 0,ee,pe);H=await a.chat(t,o,le),P=await re(H),ge=P.messageParts}s||console.log("")}var Bt="\x1B[2m",Ae="\x1B[0m",ut="\x1B[36m",Ko="\x1B[33m",fs="\x1B[32m",ps="stream-json";function Ve(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
217
+ `),W.delete(f.toolCallId)}break;case"error":f.errorText&&console.error(`${St}Error: ${f.errorText}${_e}`);break}}catch{}}}return{pendingClientTools:Z,messageParts:K}},we=p({id:po(),text:i}),H=await a.chat(t,o,we),P=await re(H);for(ge=P.messageParts;P.pendingClientTools.length>0;){let ee=[];for(let W of P.pendingClientTools){!n&&!s&&console.log(`${mo}\u2502 Executing locally...${_e}`);let Z=await to(W.toolName,W.args),K=Z.success?JSON.stringify(Z.result):Z.error||"Unknown error";if(ee.push({toolCallId:W.toolCallId,toolName:W.toolName,content:[{type:"text",text:K}],isError:!Z.success}),!n&&!s){let de=us(Z.success?Z.result:{error:Z.error},N);console.log(`${mo}\u2502 Result:${_e}`);for(let Se of de.split(`
218
+ `))console.log(`${St}\u2502 ${Se}${_e}`);console.log(`${Vo}\u2514\u2500 ${W.toolName} completed${_e}
219
+ `)}}let Q=ge.map(W=>{if(W.type==="tool-call"){let Z=ee.find(de=>de.toolCallId===W.toolCallId),K=Z?.content.filter(de=>de.type==="text").map(de=>de.text).join(`
220
+ `);return{type:"tool-invocation",toolCallId:W.toolCallId,toolName:W.toolName,args:W.args,state:Z?.isError?"output-error":"output-available",output:K}}return W}),pe=[{id:_,role:"assistant",parts:Q}];_=po();let le=p(void 0,ee,pe);H=await a.chat(t,o,le),P=await re(H),ge=P.messageParts}s||console.log("")}var Wt="\x1B[2m",Ae="\x1B[0m",ut="\x1B[36m",Ko="\x1B[33m",ps="\x1B[32m",ms="stream-json";function Ve(e,t){let o=t===void 0?{event:e}:{event:e,data:t};process.stdout.write(`${JSON.stringify(o)}
216
221
  `)}function Ho(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 yo(e,t){if(t)return e;let o=e.split(`
217
222
  `);if(o.length<=15)return e;let s=o.slice(0,6),n=o.slice(-4),r=o.length-10;return[...s,`... (${r} lines omitted, use --full-output to see all) ...`,...n].join(`
218
- `)}function zo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(zo);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]=zo(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 yo(String(e),t);let o=t?e:zo(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(`${Ko}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),yo(n.join(`
223
+ `)}function zo(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(zo);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]=zo(s):t[o]=s;return t}function gs(e){if(!e||typeof e!="object")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function hs(e,t){if(!e)return"(no result)";if(typeof e!="object")return yo(String(e),t);let o=t?e:zo(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(`${Ko}[stderr]${Ae} ${s.stderr.trim()}`),s.urls&&Array.isArray(s.urls)){let r=s.urls;for(let i of r)i.path&&i.url&&n.push(`${i.path}: ${i.url}`)}return n.length===0&&n.push(JSON.stringify(s,null,2)),yo(n.join(`
219
224
  `),t)}if("content"in o&&Array.isArray(o.content)){let n=o.content.filter(r=>r.type==="text"&&r.text).map(r=>r.text).join(`
220
- `);return yo(n||JSON.stringify(e,null,2),t)}return yo(JSON.stringify(e,null,2),t)}function Xr(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(`${Bt}${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(`${ut}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Ko}\u2502 Arguments:${Ae}`);let r=ms(s.args);for(let i of r.split(`
221
- `))n.push(`${Bt}\u2502 ${i}${Ae}`)}if(s.result!==void 0){n.push(`${fs}\u2502 Result:${Ae}`);let r=gs(s.result,t);for(let i of r.split(`
222
- `))n.push(`${Bt}\u2502 ${i}${Ae}`);n.push(`${ut}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${ut}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${ut}\u2514\u2500${Ae}`);o.push(n.join(`
223
- `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Xr(s),r=[];if(r.push(`${ut}\u250C\u2500 Tool: ${n}${Ae}`),s.input){r.push(`${Ko}\u2502 Input:${Ae}`);let i=ms(s.input);for(let a of i.split(`
224
- `))r.push(`${Bt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){r.push(`${fs}\u2502 Output:${Ae}`);let i=gs(s.output,t);for(let a of i.split(`
225
- `))r.push(`${Bt}\u2502 ${a}${Ae}`);r.push(`${ut}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?r.push(`${ut}\u2514\u2500 (in progress)${Ae}`):r.push(`${ut}\u2514\u2500${Ae}`);o.push(r.join(`
225
+ `);return yo(n||JSON.stringify(e,null,2),t)}return yo(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 ys(e,t){let o=[];for(let s of e)if(s.type==="reasoning"&&s.text)o.push(`${Wt}${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(`${ut}\u250C\u2500 Tool Call: ${s.toolName}${Ae}`),s.args){n.push(`${Ko}\u2502 Arguments:${Ae}`);let r=gs(s.args);for(let i of r.split(`
226
+ `))n.push(`${Wt}\u2502 ${i}${Ae}`)}if(s.result!==void 0){n.push(`${ps}\u2502 Result:${Ae}`);let r=hs(s.result,t);for(let i of r.split(`
227
+ `))n.push(`${Wt}\u2502 ${i}${Ae}`);n.push(`${ut}\u2514\u2500 ${s.toolName} completed${Ae}`)}else s.state==="call"?n.push(`${ut}\u2514\u2500 (awaiting result)${Ae}`):n.push(`${ut}\u2514\u2500${Ae}`);o.push(n.join(`
228
+ `))}else if(s.type.startsWith("tool-")&&s.type!=="tool-call"){let n=Zr(s),r=[];if(r.push(`${ut}\u250C\u2500 Tool: ${n}${Ae}`),s.input){r.push(`${Ko}\u2502 Input:${Ae}`);let i=gs(s.input);for(let a of i.split(`
229
+ `))r.push(`${Wt}\u2502 ${a}${Ae}`)}if(s.output!==void 0&&s.state==="output-available"){r.push(`${ps}\u2502 Output:${Ae}`);let i=hs(s.output,t);for(let a of i.split(`
230
+ `))r.push(`${Wt}\u2502 ${a}${Ae}`);r.push(`${ut}\u2514\u2500 completed${Ae}`)}else s.state==="call"||s.state==="partial-call"?r.push(`${ut}\u2514\u2500 (in progress)${Ae}`):r.push(`${ut}\u2514\u2500${Ae}`);o.push(r.join(`
226
231
  `))}return o.join(`
227
232
 
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 G;if(e.shareId){let i;try{i=await lt()}catch{}try{let a=await o.getSharedChat(e.shareId,i),{messages:l}=await o.getSharedMessages(e.shareId,50,i);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(Ve("chat",a),l.length===0)Ve("info","No messages in this shared chat.");else for(let C of l.toReversed())Ve("message",C);Ve("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(),x=e.fullOutput??!1;for(let C of d){let b=hs(C.parts,x);if(!b)continue;let T=C.role==="user"?"You":"Assistant";console.log(`[${T}] ${Ho(C.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 i=await fe();s=i.accessToken,n=i.workspaceId}catch(i){ke(i)}if(e.chatId){let i=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let h=d===0?1:d,{chats:y}=await o.getChats(s,n,20);h>y.length&&(console.error(`Chat number ${h} not found. You have ${y.length} recent chats.`),process.exit(1));let v=y[h-1];i=v.id,a=!0,l=v,t||console.log(`Chat: ${v.title||"Untitled"}
230
- `)}let{messages:C}=await o.getMessages(s,n,i,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(l&&Ve("chat",l),C.length===0)Ve("info","No messages in this chat.");else for(let h of C.toReversed())Ve("message",h);Ve("done");return}if(C.length===0){console.log("No messages in this chat.");return}let b=C.toReversed(),T=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
231
- `);for(let h of b){let y=hs(h.parts,T);if(!y)continue;let v=h.role==="user"?"You":"Assistant";console.log(`[${v}] ${Ho(h.createdAt)}`),console.log(y),console.log("")}return}let{chats:r}=await o.getChats(s,n,20);if(t){for(let i of r)Ve("chat",i);Ve("done");return}if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${r.length}):
232
- `),r.forEach((i,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${Ho(i.createdAt).padEnd(12)} ${i.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Zr,Text as Pe}from"ink";import{jsx as Le,jsxs as Tt}from"react/jsx-runtime";var It=["apiUrl","hubUrl"];function qo(e){return It.includes(e)}async function ws(e){let t=e.action||"list",o=e.configKey,s=e.value,n=J.getEffectiveProfileName();if(t==="list"){let r=oe.getAll(),i=Object.entries(r);if(e.json){console.log(JSON.stringify(r));return}if(console.log(`Profile: ${n}`),i.length===0){console.log("No configuration set."),console.log(`Available keys: ${It.join(", ")}`);return}console.log(`Configuration:
233
+ `).trim()}async function ws(e){let t=e.output===ms;e.output&&!t&&(console.error(`Invalid --output value. Supported: ${ms}`),process.exit(1));let o=new G;if(e.shareId){let i;try{i=await lt()}catch{}try{let a=await o.getSharedChat(e.shareId,i),{messages:l}=await o.getSharedMessages(e.shareId,50,i);if(e.json){console.log(JSON.stringify({chat:a,messages:l}));return}if(t){if(Ve("chat",a),l.length===0)Ve("info","No messages in this shared chat.");else for(let C of l.toReversed())Ve("message",C);Ve("done");return}if(console.log(`Shared Chat: ${a.title||"Untitled"}`),console.log(`Visibility: ${a.visibility}`),a.agent&&console.log(`Agent: ${a.agent.name}`),console.log(`${l.length} messages
234
+ `),l.length===0){console.log("No messages in this shared chat.");return}let d=l.toReversed(),b=e.fullOutput??!1;for(let C of d){let x=ys(C.parts,b);if(!x)continue;let T=C.role==="user"?"You":"Assistant";console.log(`[${T}] ${Ho(C.createdAt)}`),console.log(x),console.log("")}return}catch(a){if(a instanceof Error){let l=a.message.toLowerCase();l.includes("401")||l.includes("unauthorized")?console.error("Access denied. This shared chat requires authentication or is not accessible to you."):l.includes("404")||l.includes("not found")?console.error("Shared chat not found. The share ID may be invalid or the chat was deleted."):console.error(`Failed to fetch shared chat: ${a.message}`)}else console.error("Failed to fetch shared chat");process.exit(1)}}let s,n;try{let i=await fe();s=i.accessToken,n=i.workspaceId}catch(i){ke(i)}if(e.chatId){let i=e.chatId,a=!1,l=null,d=parseInt(e.chatId,10);if(!isNaN(d)&&d>=0&&/^\d+$/.test(e.chatId)){let h=d===0?1:d,{chats:y}=await o.getChats(s,n,20);h>y.length&&(console.error(`Chat number ${h} not found. You have ${y.length} recent chats.`),process.exit(1));let v=y[h-1];i=v.id,a=!0,l=v,t||console.log(`Chat: ${v.title||"Untitled"}
235
+ `)}let{messages:C}=await o.getMessages(s,n,i,50);if(e.json){console.log(JSON.stringify(C));return}if(t){if(l&&Ve("chat",l),C.length===0)Ve("info","No messages in this chat.");else for(let h of C.toReversed())Ve("message",h);Ve("done");return}if(C.length===0){console.log("No messages in this chat.");return}let x=C.toReversed(),T=e.fullOutput??!1;a||console.log(`Chat: ${e.chatId.slice(0,8)}...`),console.log(`${C.length} messages
236
+ `);for(let h of x){let y=ys(h.parts,T);if(!y)continue;let v=h.role==="user"?"You":"Assistant";console.log(`[${v}] ${Ho(h.createdAt)}`),console.log(y),console.log("")}return}let{chats:r}=await o.getChats(s,n,20);if(t){for(let i of r)Ve("chat",i);Ve("done");return}if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No chats found.");return}console.log(`Recent Chats (${r.length}):
237
+ `),r.forEach((i,a)=>{let l=(a+1).toString().padStart(2," ");console.log(` ${l}. ${Ho(i.createdAt).padEnd(12)} ${i.title||"Untitled"}`)}),console.log(""),console.log("Use `entrydesk chats 1` to view the most recent chat"),console.log('Use `entrydesk chat -c 1 -m "message"` to continue it')}import{Box as Qr,Text as Pe}from"ink";import{jsx as Le,jsxs as Tt}from"react/jsx-runtime";var It=["apiUrl","hubUrl"];function qo(e){return It.includes(e)}async function ks(e){let t=e.action||"list",o=e.configKey,s=e.value,n=J.getEffectiveProfileName();if(t==="list"){let r=oe.getAll(),i=Object.entries(r);if(e.json){console.log(JSON.stringify(r));return}if(console.log(`Profile: ${n}`),i.length===0){console.log("No configuration set."),console.log(`Available keys: ${It.join(", ")}`);return}console.log(`Configuration:
233
238
  `);for(let[a,l]of i)console.log(` ${a}=${l}`);console.log(`
234
- Available keys: ${It.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1));let r=oe.get(o);e.json?console.log(JSON.stringify({[o]:r??null})):console.log(r||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function ks(){let e=Ye();return Tt(Zr,{flexDirection:"column",children:[Le(Pe,{bold:!0,children:"entrydesk config"}),Le(Pe,{children:" "}),Le(Pe,{children:"Manage CLI configuration"}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Usage:"}),Le(Pe,{children:" entrydesk config List all configuration"}),Tt(Pe,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Available keys:"}),Tt(Pe,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Tt(Pe,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Examples:"}),Le(Pe,{children:" entrydesk config set apiUrl http://localhost:3200"}),Le(Pe,{children:" entrydesk config get apiUrl"}),Le(Pe,{children:" entrydesk config unset apiUrl"})]})}async function bs(e){try{let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new G,{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}):
239
+ Available keys: ${It.join(", ")}`);return}if(t==="get"){o||(console.error("Error: key is required for get action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1));let r=oe.get(o);e.json?console.log(JSON.stringify({[o]:r??null})):console.log(r||"Not set");return}if(t==="set"){o||(console.error("Error: key is required for set action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),s||(console.error("Error: value is required for set action"),process.exit(1)),oe.set(o,s),console.log(`Set ${o}=${s}`);return}if(t==="unset"){o||(console.error("Error: key is required for unset action"),process.exit(1)),qo(o)||(console.error(`Error: Invalid key '${o}'. Valid keys: ${It.join(", ")}`),process.exit(1)),oe.unset(o),console.log(`Unset ${o}`);return}console.error(`Unknown action: ${t}`),process.exit(1)}function xs(){let e=Ye();return Tt(Qr,{flexDirection:"column",children:[Le(Pe,{bold:!0,children:"entrydesk config"}),Le(Pe,{children:" "}),Le(Pe,{children:"Manage CLI configuration"}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Usage:"}),Le(Pe,{children:" entrydesk config List all configuration"}),Tt(Pe,{children:[" entrydesk config get ","<key>"," Get a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config set ","<key>"," ","<value>"," Set a configuration value"]}),Tt(Pe,{children:[" ","entrydesk config unset ","<key>"," Remove a configuration value"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Available keys:"}),Tt(Pe,{children:[" apiUrl API server URL (default: ",e.apiUrl,")"]}),Tt(Pe,{children:[" hubUrl Hub server URL (default: ",e.hubUrl,")"]}),Le(Pe,{children:" "}),Le(Pe,{bold:!0,children:"Examples:"}),Le(Pe,{children:" entrydesk config set apiUrl http://localhost:3200"}),Le(Pe,{children:" entrydesk config get apiUrl"}),Le(Pe,{children:" entrydesk config unset apiUrl"})]})}async function bs(e){try{let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new G,{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
240
  `);for(let r of n){let i=r.connected?"connected":"disconnected";console.log(` ${r.name} (${i})`),console.log(` Provider: ${r.provider}`),console.log(` ID: ${r.id}`),console.log("")}}catch(t){ke(t)}}function wo(){console.log(`
236
241
  EntryDesk CLI - Interact with EntryDesk from your terminal
237
242
 
@@ -397,10 +402,10 @@ Local Development:
397
402
  $ entrydesk config set hubUrl http://localhost:3000
398
403
 
399
404
  For more information, visit https://entrydesk.com/docs/cli
400
- `)}async function xs(e){if(process.env.DEBUG){let{getApiUrl:r,getHubUrl:i}=await import("./config-7DULLCA6.js");console.log(`[DEBUG] Hub URL: ${i()}`),console.log(`[DEBUG] API URL: ${r()}`)}let t=await on({onDeviceCodeReceived:(r,i)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${i}`),console.log(` 2. Enter code: ${r}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),o=new G,{workspaces:s}=await o.getWorkspaces(t.accessToken),n=s[0];await $e.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:n?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:n?.id,workspaceName:n?.name})):(console.log(`Logged in as ${t.email}`),n&&console.log(`Workspace: ${n.name}`))}async function Cs(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new G().revokeOAuthToken({token:t.refreshToken,clientId:tn})}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import Qr from"http";import{stderr as ei}from"process";import{Client as ti}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as oi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as ni}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as si}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ri}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ii,ListToolsRequestSchema as ai}from"@modelcontextprotocol/sdk/types.js";function We(e){ei.write(`${e}
401
- `)}async function $s(e,t,o){let s=new ti({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),r=new oi(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(r),s}function Ss(e){let t=new ni({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(ai,async()=>({tools:(await(await e()).listTools()).tools})),t.setRequestHandler(ii,async o=>{let{name:s,arguments:n}=o.params,i=await(await e()).callTool({name:s,arguments:n}),a=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&a.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:a,structuredContent:i.structuredContent,isError:i.isError}}),t}async function li(e,t,o){let s=Qr.createServer(async(n,r)=>{if(n.method==="OPTIONS"){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),r.writeHead(204),r.end();return}if(n.url!=="/mcp"){r.writeHead(404,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Not found"}));return}let i=Ss(e),a=new ri({sessionIdGenerator:void 0});if(r.setHeader("Access-Control-Allow-Origin","*"),r.on("close",()=>{a.close(),i.close()}),await i.connect(a),n.method==="POST"){let l="";n.on("data",d=>{l+=d.toString()}),n.on("end",async()=>{try{let d=JSON.parse(l);await a.handleRequest(n,r,d)}catch{r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Invalid JSON"}))}})}else await a.handleRequest(n,r)});s.listen(o,()=>{We(`EntryDesk MCP server running at http://localhost:${o}/mcp`),We("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{We(`
402
- Shutting down...`),s.close(),await t(),process.exit(0)}),process.on("SIGTERM",async()=>{s.close(),await t(),process.exit(0)})}async function ci(e,t){let o=Ss(e),s=new si;s.onclose=async()=>{await t()},await o.connect(s)}async function Ts(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{We("[entrydesk-mcp] Starting MCP server...");let t,o;try{let d=await fe();t=d.accessToken,o=d.workspaceId}catch(d){let x=d instanceof Error?d.message:"Authentication failed";console.error(x),process.exit(1)}let{apiUrl:s,mcp:n}=Ye();We(`[entrydesk-mcp] Connecting to ${s}...`),We(`[entrydesk-mcp] Workspace: ${o}`);let r=await $s(s,t,o);We("[entrydesk-mcp] Connected to EntryDesk API");let i=null,a=async()=>nn(t)?i||(i=(async()=>{We("[entrydesk-mcp] Token expiring soon, refreshing...");let d=await $e.getAll();if(!d?.accessToken)throw new Error("Not logged in. Please run `entrydesk login` again.");let x=await sn(d);if(x!==t){t=x;try{await r.close()}catch{}r=await $s(s,t,o),We("[entrydesk-mcp] Token refreshed, reconnected")}return r})().finally(()=>{i=null}),i):r,l=async()=>{try{await r.close()}catch{}};if(e.mode==="http"){let d=e.port??n.httpPort;await li(a,l,d)}else We("[entrydesk-mcp] Starting stdio server..."),await ci(a,l),We("[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 r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new G,{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}):
403
- `);for(let r of n)console.log(` ${r.name}`),r.description&&console.log(` ${r.description.slice(0,80)}`),console.log(` ID: ${r.id}`),console.log("")}catch(t){ke(t)}}function ui(){console.log(`
405
+ `)}async function Cs(e){if(process.env.DEBUG){let{getApiUrl:r,getHubUrl:i}=await import("./config-TBDWOB2B.js");console.log(`[DEBUG] Hub URL: ${i()}`),console.log(`[DEBUG] API URL: ${r()}`)}let t=await on({onDeviceCodeReceived:(r,i)=>{e.json||(console.log(""),console.log("To authenticate, please:"),console.log(""),console.log(` 1. Visit: ${i}`),console.log(` 2. Enter code: ${r}`),console.log(""))},onBrowserOpening:()=>{e.json||console.log("Opening browser...")},onWaitingForAuthorization:()=>{e.json||console.log("Waiting for authorization...")},onAuthorized:()=>{e.json||console.log("Authorization successful!")}}),o=new G,{workspaces:s}=await o.getWorkspaces(t.accessToken),n=s[0];await $e.saveAll({accessToken:t.accessToken,refreshToken:t.refreshToken,email:t.email,workspaceId:n?.id}),e.json?console.log(JSON.stringify({email:t.email,workspaceId:n?.id,workspaceName:n?.name})):(console.log(`Logged in as ${t.email}`),n&&console.log(`Workspace: ${n.name}`))}async function $s(e){try{let t=await $e.getAll();if(!t){console.log("Not logged in");return}try{t.refreshToken&&await new G().revokeOAuthToken({token:t.refreshToken,clientId:tn})}catch{}await $e.clear(),console.log("Logged out successfully")}catch(t){ke(t)}}import ei from"http";import{stderr as ti}from"process";import{Client as oi}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as ni}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{Server as si}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ri}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ii}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ai,ListToolsRequestSchema as li}from"@modelcontextprotocol/sdk/types.js";function Me(e){ti.write(`${e}
406
+ `)}async function Ss(e,t,o){let s=new oi({name:"entrydesk-cli-proxy",version:"1.0.0"}),n=new URL(`${e}/v1/workspaces/${o}/mcp`),r=new ni(n,{requestInit:{headers:{Authorization:`Bearer ${t}`}}});return await s.connect(r),s}function Ts(e){let t=new si({name:"entrydesk-cli",version:"1.0.0"},{capabilities:{tools:{}}});return t.setRequestHandler(li,async()=>({tools:(await(await e()).listTools()).tools})),t.setRequestHandler(ai,async o=>{let{name:s,arguments:n}=o.params,i=await(await e()).callTool({name:s,arguments:n}),a=Array.isArray(i.content)?[...i.content]:[];return i.structuredContent&&a.push({type:"text",text:JSON.stringify(i.structuredContent,null,2)}),{content:a,structuredContent:i.structuredContent,isError:i.isError}}),t}async function ci(e,t,o){let s=ei.createServer(async(n,r)=>{if(n.method==="OPTIONS"){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Accept"),r.writeHead(204),r.end();return}if(n.url!=="/mcp"){r.writeHead(404,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Not found"}));return}let i=Ts(e),a=new ii({sessionIdGenerator:void 0});if(r.setHeader("Access-Control-Allow-Origin","*"),r.on("close",()=>{a.close(),i.close()}),await i.connect(a),n.method==="POST"){let l="";n.on("data",d=>{l+=d.toString()}),n.on("end",async()=>{try{let d=JSON.parse(l);await a.handleRequest(n,r,d)}catch{r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Invalid JSON"}))}})}else await a.handleRequest(n,r)});s.listen(o,()=>{Me(`EntryDesk MCP server running at http://localhost:${o}/mcp`),Me("Press Ctrl+C to stop")}),process.on("SIGINT",async()=>{Me(`
407
+ Shutting down...`),s.close(),await t(),process.exit(0)}),process.on("SIGTERM",async()=>{s.close(),await t(),process.exit(0)})}async function ui(e,t){let o=Ts(e),s=new ri;s.onclose=async()=>{await t()},await o.connect(s)}async function Is(e={mode:"stdio"}){process.on("unhandledRejection",t=>{console.error("[entrydesk-mcp] Unhandled rejection:",t)}),process.on("uncaughtException",t=>{console.error("[entrydesk-mcp] Uncaught exception:",t)});try{Me("[entrydesk-mcp] Starting MCP server...");let t,o;try{let d=await fe();t=d.accessToken,o=d.workspaceId}catch(d){let b=d instanceof Error?d.message:"Authentication failed";console.error(b),process.exit(1)}let{apiUrl:s,mcp:n}=Ye();Me(`[entrydesk-mcp] Connecting to ${s}...`),Me(`[entrydesk-mcp] Workspace: ${o}`);let r=await Ss(s,t,o);Me("[entrydesk-mcp] Connected to EntryDesk API");let i=null,a=async()=>nn(t)?i||(i=(async()=>{Me("[entrydesk-mcp] Token expiring soon, refreshing...");let d=await $e.getAll();if(!d?.accessToken)throw new Error("Not logged in. Please run `entrydesk login` again.");let b=await sn(d);if(b!==t){t=b;try{await r.close()}catch{}r=await Ss(s,t,o),Me("[entrydesk-mcp] Token refreshed, reconnected")}return r})().finally(()=>{i=null}),i):r,l=async()=>{try{await r.close()}catch{}};if(e.mode==="http"){let d=e.port??n.httpPort;await ci(a,l,d)}else Me("[entrydesk-mcp] Starting stdio server..."),await ui(a,l),Me("[entrydesk-mcp] Stdio server started")}catch(t){console.error("[entrydesk-mcp] Fatal error:",t),process.exit(1)}}async function vs(e){try{let t,o;try{let r=await fe();t=r.accessToken,o=r.workspaceId}catch(r){let i=r instanceof Error?r.message:"Authentication failed";console.error(i),process.exit(1)}let s=new G,{models:n}=await s.getModels(t,o);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No models available in this workspace.");return}console.log(`Available Models (${n.length}):
408
+ `);for(let r of n)console.log(` ${r.name}`),r.description&&console.log(` ${r.description.slice(0,80)}`),console.log(` ID: ${r.id}`),console.log("")}catch(t){ke(t)}}function di(){console.log(`
404
409
  Usage: entrydesk profile [list|show|current|create|use|delete|rename|clone] [args]
405
410
 
406
411
  Commands:
@@ -415,7 +420,7 @@ Commands:
415
420
 
416
421
  Flags:
417
422
  --json Output JSON
418
- `)}function Mt(e,t){if(e)return e;if(t&&J.getProfileCount()===1)return J.getProfileNames()[0];throw new Et("Profile name is required when multiple profiles exist.")}function di(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function vs(e){try{let t=e.action||"list",o=J.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){ui();return}if(t==="list"){let r=J.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:r.map(i=>({name:i,isCurrent:i===o}))}));return}console.log(`Profiles (${r.length}):`);for(let i of r)console.log(` ${i}${i===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let r=Mt(s,!0),i=oe.getAll(r),a=await $e.getAll(r),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:r,isCurrent:r===o,config:i,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${r}${r===o?" (current)":""}`),console.log(` API URL: ${i.apiUrl??"default"}`),console.log(` Hub URL: ${i.hubUrl??"default"}`),console.log(` Model: ${i.model?.default??"unset"}`);let d=i.connectors?.defaults&&i.connectors.defaults.length>0?i.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${di(i.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let r=s||J.DEFAULT_PROFILE;if(J.createProfile(r),e.json){console.log(JSON.stringify({name:r,created:!0}));return}console.log(`Profile created: ${r}`);return}if(t==="use"||t==="switch"){let r=Mt(s,!0);if(J.setCurrentProfile(r),e.json){console.log(JSON.stringify({name:r,current:!0}));return}console.log(`Switched to profile: ${r}`);return}if(t==="delete"||t==="remove"||t==="rm"){let r=Mt(s,!0),i=J.deleteProfile(r);if(e.json){console.log(JSON.stringify({deleted:r,currentProfile:i.currentProfile}));return}console.log(`Profile deleted: ${r}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let r=Mt(s,!0);if(!n)throw new Et("New profile name is required.");let i=J.renameProfile(r,n);if(e.json){console.log(JSON.stringify({renamed:r,name:n,currentProfile:i.currentProfile}));return}console.log(`Profile renamed: ${r} -> ${n}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="clone"||t==="copy"){let r=Mt(s,!0);if(!n)throw new Et("Target profile name is required.");let i=oe.getAll(r);if(J.createProfile(n),oe.setAll(i,n),await $e.clear(n),e.json){console.log(JSON.stringify({source:r,name:n,cloned:!0}));return}console.log(`Profile cloned: ${r} -> ${n}`);return}throw new Et(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Jt(){console.log(`
423
+ `)}function Bt(e,t){if(e)return e;if(t&&J.getProfileCount()===1)return J.getProfileNames()[0];throw new Et("Profile name is required when multiple profiles exist.")}function fi(e){if(!e)return"none";let t=[];return e.sandbox&&t.push("sandbox"),e.webSearch&&t.push("webSearch"),e.imageGeneration&&t.push("imageGeneration"),e.chart&&t.push("chart"),t.length>0?t.join(", "):"none"}async function As(e){try{let t=e.action||"list",o=J.getCurrentProfileName(),s=e.name??e.profile,n=e.value;if(e.help||t==="help"){di();return}if(t==="list"){let r=J.getProfileNames();if(e.json){console.log(JSON.stringify({currentProfile:o,profiles:r.map(i=>({name:i,isCurrent:i===o}))}));return}console.log(`Profiles (${r.length}):`);for(let i of r)console.log(` ${i}${i===o?" (current)":""}`);return}if(t==="current"){if(e.json){console.log(JSON.stringify({name:o,isCurrent:!0}));return}console.log(`Current profile: ${o}`);return}if(t==="show"){let r=Bt(s,!0),i=oe.getAll(r),a=await $e.getAll(r),l=!!a?.accessToken;if(e.json){console.log(JSON.stringify({name:r,isCurrent:r===o,config:i,auth:l?{loggedIn:!0,email:a?.email??null,workspaceId:a?.workspaceId??null}:{loggedIn:!1}}));return}console.log(`Profile: ${r}${r===o?" (current)":""}`),console.log(` API URL: ${i.apiUrl??"default"}`),console.log(` Hub URL: ${i.hubUrl??"default"}`),console.log(` Model: ${i.model?.default??"unset"}`);let d=i.connectors?.defaults&&i.connectors.defaults.length>0?i.connectors.defaults.join(", "):"unset";console.log(` Connectors: ${d}`),console.log(` Capabilities: ${fi(i.capabilities)}`),console.log(l?` Logged in as: ${a?.email??"unknown"}`:" Not logged in"),l&&a?.workspaceId&&console.log(` Workspace ID: ${a.workspaceId}`);return}if(t==="create"){let r=s||J.DEFAULT_PROFILE;if(J.createProfile(r),e.json){console.log(JSON.stringify({name:r,created:!0}));return}console.log(`Profile created: ${r}`);return}if(t==="use"||t==="switch"){let r=Bt(s,!0);if(J.setCurrentProfile(r),e.json){console.log(JSON.stringify({name:r,current:!0}));return}console.log(`Switched to profile: ${r}`);return}if(t==="delete"||t==="remove"||t==="rm"){let r=Bt(s,!0),i=J.deleteProfile(r);if(e.json){console.log(JSON.stringify({deleted:r,currentProfile:i.currentProfile}));return}console.log(`Profile deleted: ${r}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="rename"||t==="move"||t==="mv"){let r=Bt(s,!0);if(!n)throw new Et("New profile name is required.");let i=J.renameProfile(r,n);if(e.json){console.log(JSON.stringify({renamed:r,name:n,currentProfile:i.currentProfile}));return}console.log(`Profile renamed: ${r} -> ${n}`),console.log(`Current profile: ${i.currentProfile}`);return}if(t==="clone"||t==="copy"){let r=Bt(s,!0);if(!n)throw new Et("Target profile name is required.");let i=oe.getAll(r);if(J.createProfile(n),oe.setAll(i,n),await $e.clear(n),e.json){console.log(JSON.stringify({source:r,name:n,cloned:!0}));return}console.log(`Profile cloned: ${r} -> ${n}`);return}throw new Et(`Unknown profile command: ${t}`)}catch(t){ke(t)}}function Jt(){console.log(`
419
424
  Usage: entrydesk schedules [list|get|create|delete] [options]
420
425
 
421
426
  Commands:
@@ -441,7 +446,7 @@ Create Options:
441
446
 
442
447
  Flags:
443
448
  --json Output JSON
444
- `)}function As(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Gt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,r=parseInt(s[2],10),i=parseInt(s[3],10),a=n*(r*60+i)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function fi(e){console.log(`
449
+ `)}function Ps(e){if(e.type==="no-repeat")return"No repeat";let{interval:t}=e;switch(t.unit){case"minutes":return`Every ${t.every} minute${t.every>1?"s":""}`;case"hours":return`Every ${t.every} hour${t.every>1?"s":""} at :${String(t.minute).padStart(2,"0")}`;case"days":return`Every ${t.every} day${t.every>1?"s":""} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`;case"weeks":{let o=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=t.daysOfWeek.map(n=>o[n]).join(", ");return`Every ${t.every} week${t.every>1?"s":""} on ${s} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}case"months":{let o=t.lastDayOfMonth?t.daysOfMonth.length>0?`${t.daysOfMonth.join(", ")} and last day`:"last day":t.daysOfMonth.join(", ");return`Every ${t.every} month${t.every>1?"s":""} on day ${o} at ${String(t.time.hour).padStart(2,"0")}:${String(t.time.minute).padStart(2,"0")}`}default:return"Unknown"}}function Gt(e,t){let o=new Date(e),s=t.match(/^([+-])(\d{2}):(\d{2})$/);if(!s)return o.toISOString();let n=s[1]==="+"?1:-1,r=parseInt(s[2],10),i=parseInt(s[3],10),a=n*(r*60+i)*60*1e3;return`${new Date(o.getTime()+a).toISOString().replace("T"," ").slice(0,19)} (${t})`}function pi(e){console.log(`
445
450
  Schedule: ${e.name}
446
451
  ${"\u2501".repeat(50)}
447
452
  ID: ${e.id}
@@ -453,13 +458,13 @@ Prompt:
453
458
  ${e.prompt.slice(0,200)}${e.prompt.length>200?"...":""}
454
459
 
455
460
  Schedule:
456
- ${As(e.config)}
461
+ ${Ps(e.config)}
457
462
 
458
463
  Next Run: ${e.nextRunAt?Gt(e.nextRunAt,e.utcOffset):"-"}
459
464
  Created: ${Gt(e.createdAt,e.utcOffset)}
460
465
  Updated: ${Gt(e.updatedAt,e.utcOffset)}
461
- `)}function pi(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,r]=s.split(":"),i={hour:parseInt(n,10),minute:parseInt(r,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:i.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:i}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:i}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:i}};default:return{type:"no-repeat"}}}async function Ps(e){try{if(e.help){Jt();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new G;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Jt(),process.exit(1));let d=await r.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}fi(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"),Jt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:pi(e),utcOffset:e.utcOffset||"+00:00"},d=await r.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Gt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Jt(),process.exit(1)),await r.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Jt(),process.exit(1));let i=[],a;do{let l=await r.getSchedules(o,s,{nextKey:a,limit:100});i.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${i.length}):
462
- `);for(let l of i){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${As(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?Gt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){ke(t)}}import mi from"fs";import vt from"fs/promises";import Ns from"os";import tt from"path";import gi from"archiver";function ko(){console.log(`
466
+ `)}function mi(e){let t=e.repeatType||"no-repeat";if(t==="no-repeat")return{type:"no-repeat"};let o=e.every||1,s=e.time||"09:00",[n,r]=s.split(":"),i={hour:parseInt(n,10),minute:parseInt(r,10)};switch(t){case"minutes":return{type:"repeat",interval:{unit:"minutes",every:o}};case"hours":return{type:"repeat",interval:{unit:"hours",every:o,minute:i.minute}};case"days":return{type:"repeat",interval:{unit:"days",every:o,time:i}};case"weeks":return{type:"repeat",interval:{unit:"weeks",every:o,daysOfWeek:e.daysOfWeek||[1],time:i}};case"months":return{type:"repeat",interval:{unit:"months",every:o,daysOfMonth:e.daysOfMonth||[1],lastDayOfMonth:e.lastDayOfMonth||!1,time:i}};default:return{type:"no-repeat"}}}async function Ns(e){try{if(e.help){Jt();return}let t=await fe(),{accessToken:o,workspaceId:s}=t,n=e.action||"list",r=new G;if(n==="get"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Jt(),process.exit(1));let d=await r.getSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}pi(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"),Jt(),process.exit(1));let l={name:e.name,prompt:e.prompt,agentId:e.agentId,startsAt:e.startsAt,config:mi(e),utcOffset:e.utcOffset||"+00:00"},d=await r.createSchedule(o,s,l);if(e.json){console.log(JSON.stringify(d));return}console.log(`Created schedule: ${d.name}`),console.log(` ID: ${d.id}`),console.log(` Next Run: ${d.nextRunAt?Gt(d.nextRunAt,d.utcOffset):"-"}`);return}if(n==="delete"){let l=e.scheduleId;l||(console.error("Missing schedule ID."),Jt(),process.exit(1)),await r.deleteSchedule(o,s,l),console.log(`Deleted schedule: ${l}`);return}n!=="list"&&(console.error(`Unknown schedules command: ${n}`),Jt(),process.exit(1));let i=[],a;do{let l=await r.getSchedules(o,s,{nextKey:a,limit:100});i.push(...l.schedules),a=l.nextKey}while(a);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No schedules found in this workspace.");return}console.log(`Schedules (${i.length}):
467
+ `);for(let l of i){let d=l.isActive?"\x1B[32mActive\x1B[0m":"\x1B[33mPaused\x1B[0m";console.log(` ${l.name}`),console.log(` Agent: ${l.agent.name}`),console.log(` Repeat: ${Ps(l.config)}`),console.log(` Status: ${d}`),console.log(` Next Run: ${l.nextRunAt?Gt(l.nextRunAt,l.utcOffset):"-"}`),console.log(` ID: ${l.id}`),console.log("")}}catch(t){ke(t)}}import gi from"fs";import vt from"fs/promises";import Es from"os";import tt from"path";import hi from"archiver";function ko(){console.log(`
463
468
  Usage: entrydesk skills [list|upload|delete|versions] [options]
464
469
 
465
470
  Commands:
@@ -473,17 +478,17 @@ Options:
473
478
  --me Only list skills created by me
474
479
  --force Overwrite an existing skill with the same name
475
480
  --json Output JSON (for list/upload/versions)
476
- `)}function hi(e,t){let o=tt.relative(e,t);return o===""||!o.startsWith("..")&&!tt.isAbsolute(o)}async function yi(e){let t=await vt.realpath(e),o=[process.cwd(),Ns.homedir()];if(!(await Promise.all(o.map(async r=>{try{return await vt.realpath(r)}catch{return tt.resolve(r)}}))).some(r=>hi(r,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function wi(e){let t=await vt.mkdtemp(tt.join(Ns.tmpdir(),"entrydesk-skill-")),o=tt.join(t,`${tt.basename(e)}.zip`);return await new Promise((s,n)=>{let r=mi.createWriteStream(o),i=gi("zip",{zlib:{level:9}});r.on("close",()=>s()),r.on("error",n),i.on("error",n),i.pipe(r),i.directory(e,!1),i.finalize()}),{zipPath:o,cleanupDir:t}}async function Es(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){ke(a)}let s=e.action||"list",n=new G;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),ko(),process.exit(1));let l=tt.resolve(a),d;try{d=await vt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let x=l,C=null;try{try{await yi(l)}catch(y){let v=y instanceof Error?y.message:"Invalid upload path.";console.error(v),process.exit(1)}if(d.isDirectory()){let y=await wi(l);x=y.zipPath,C=y.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));tt.extname(x).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let b=await vt.readFile(x),T=new FormData;T.append("file",new Blob([b],{type:"application/zip"}),tt.basename(x)),e.force&&T.append("force","true");let h;try{h=await n.uploadSkill(t,o,T)}catch(y){if(y instanceof Error&&y.name==="HTTPError"){let v=y;if(v.response&&v.response.status===409){try{(await v.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 y}if(e.json){console.log(JSON.stringify(h));return}console.log(`Uploaded skill: ${h.name}`),console.log(` ID: ${h.id}`),console.log(` Version ID: ${h.versionId}`),console.log(` Description: ${h.description}`);return}finally{C&&await vt.rm(C,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),ko(),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."),ko(),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 x=l.find(b=>b.name===a);x||(console.error(`Skill not found: ${a}`),process.exit(1));let C=await n.listSkillVersions(t,o,x.id);if(e.json){console.log(JSON.stringify(C));return}if(console.log(`Versions for skill "${C.skillName}":
477
- `),C.versions.length===0){console.log(" No versions found.");return}for(let b of C.versions){let T=new Date(b.createdAt);console.log(` ${T.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}`),ko(),process.exit(1));let r=[],i;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:i,limit:100});r.push(...a.skills),i=a.nextKey}while(i);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${r.length}):
478
- `);for(let a of r)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function _s(e){try{let t=J.getEffectiveProfileName(),o=await $e.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let r=new G,i=await lt(),{workspaces:a}=await r.getWorkspaces(i);n=a.find(d=>d.id===o.workspaceId)?.name}catch(r){if(r 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){ke(t)}}import Ni from"fs";import{Client as ki}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as bi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function xi(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Ye().apiUrl);let n=new ki({name:"entrydesk-cli",version:"1.0.0"}),r=new URL(`${t}/v1/workspaces/${s}/mcp`),i=new bi(r,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(i),n}async function bo(){return xi()}import Xo from"fs/promises";import Ci from"os";import Vt from"path";var Yo=!process.env.NO_COLOR&&!!process.stdout.isTTY,At={green:Yo?"\x1B[32m":"",yellow:Yo?"\x1B[33m":"",reset:Yo?"\x1B[0m":""},$i=10*1024,Ds=8*1024,Os=2*1024,Si=100,Ti=100;function Ii(){return Vt.join(Ci.homedir(),".entrydesk","tool-results")}function vi(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Si);return!t||t==="."||t===".."?"unnamed_tool":t}function Ai(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 Pi(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=vi(e);return`${o}_${s}.json`}async function Ls(e,t){try{return await Xo.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 Rs(e,t){try{let o=Ii();await Xo.mkdir(o,{recursive:!0});let s=Pi(e),n=Vt.extname(s),r=s.slice(0,-n.length),i=Ai(t),a=Vt.join(o,s);if(await Ls(a,i))return a;for(let x=1;x<=Ti;x++){let C=Vt.join(o,`${r}-${x}${n}`);if(await Ls(C,i))return C}let l=Math.random().toString(36).slice(2,10),d=Vt.join(o,`${r}-${l}${n}`);return await Xo.writeFile(d,i,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${At.yellow}Warning: Could not save result to file: ${s}${At.reset}`),null}}function Us(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=$i)return e;let s=e.slice(0,Ds),n=e.slice(-Os),i=((o-Ds-Os)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${i}KB of ${a}KB) ...`;return t&&(l+=`
481
+ `)}function yi(e,t){let o=tt.relative(e,t);return o===""||!o.startsWith("..")&&!tt.isAbsolute(o)}async function wi(e){let t=await vt.realpath(e),o=[process.cwd(),Es.homedir()];if(!(await Promise.all(o.map(async r=>{try{return await vt.realpath(r)}catch{return tt.resolve(r)}}))).some(r=>yi(r,t)))throw new Error("Invalid upload path: must be within the current directory or your home directory.")}async function ki(e){let t=await vt.mkdtemp(tt.join(Es.tmpdir(),"entrydesk-skill-")),o=tt.join(t,`${tt.basename(e)}.zip`);return await new Promise((s,n)=>{let r=gi.createWriteStream(o),i=hi("zip",{zlib:{level:9}});r.on("close",()=>s()),r.on("error",n),i.on("error",n),i.pipe(r),i.directory(e,!1),i.finalize()}),{zipPath:o,cleanupDir:t}}async function _s(e){let t,o;try{let a=await fe();t=a.accessToken,o=a.workspaceId}catch(a){ke(a)}let s=e.action||"list",n=new G;if(s==="upload"){let a=e.configKey;a||(console.error("Missing file path."),ko(),process.exit(1));let l=tt.resolve(a),d;try{d=await vt.stat(l)}catch{console.error(`File not found: ${l}`),process.exit(1)}let b=l,C=null;try{try{await wi(l)}catch(y){let v=y instanceof Error?y.message:"Invalid upload path.";console.error(v),process.exit(1)}if(d.isDirectory()){let y=await ki(l);b=y.zipPath,C=y.cleanupDir}else d.isFile()||(console.error(`Not a file or directory: ${l}`),process.exit(1));tt.extname(b).toLowerCase()!==".zip"&&(console.error("Only .zip files are supported for upload."),process.exit(1));let x=await vt.readFile(b),T=new FormData;T.append("file",new Blob([x],{type:"application/zip"}),tt.basename(b)),e.force&&T.append("force","true");let h;try{h=await n.uploadSkill(t,o,T)}catch(y){if(y instanceof Error&&y.name==="HTTPError"){let v=y;if(v.response&&v.response.status===409){try{(await v.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 y}if(e.json){console.log(JSON.stringify(h));return}console.log(`Uploaded skill: ${h.name}`),console.log(` ID: ${h.id}`),console.log(` Version ID: ${h.versionId}`),console.log(` Description: ${h.description}`);return}finally{C&&await vt.rm(C,{recursive:!0,force:!0})}}if(s==="delete"){let a=e.configKey;a||(console.error("Missing skill ID."),ko(),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."),ko(),process.exit(1));let l=[],d;do{let x=await n.listAvailableSkills(t,o,{nextKey:d,limit:100});l.push(...x.skills),d=x.nextKey}while(d);let b=l.find(x=>x.name===a);b||(console.error(`Skill not found: ${a}`),process.exit(1));let C=await n.listSkillVersions(t,o,b.id);if(e.json){console.log(JSON.stringify(C));return}if(console.log(`Versions for skill "${C.skillName}":
482
+ `),C.versions.length===0){console.log(" No versions found.");return}for(let x of C.versions){let T=new Date(x.createdAt);console.log(` ${T.toLocaleString()}`),console.log(` ID: ${x.id}`),console.log(` Description: ${x.description.slice(0,80)}`),console.log(` Created by: ${x.createdBy.name}`),console.log("")}return}s!=="list"&&(console.error(`Unknown skills command: ${s}`),ko(),process.exit(1));let r=[],i;do{let a=await n.listAvailableSkills(t,o,{createdBy:e.createdBy,nextKey:i,limit:100});r.push(...a.skills),i=a.nextKey}while(i);if(e.json){console.log(JSON.stringify(r));return}if(r.length===0){console.log("No skills found in this workspace.");return}console.log(`Available Skills (${r.length}):
483
+ `);for(let a of r)console.log(` ${a.name} (${a.provider})`),console.log(` ${a.description.slice(0,120)}`),console.log(` ID: ${a.id}`),console.log(` Author: ${a.author.name}`),console.log("")}async function Ds(e){try{let t=J.getEffectiveProfileName(),o=await $e.getAll(),s={model:oe.getDefaultModel(),connectors:oe.getDefaultConnectorIds(),capabilities:oe.getCapabilities()};if(!o){e.json?console.log(JSON.stringify({loggedIn:!1,profile:t,defaults:s})):(console.log(`Profile: ${t}`),console.log("Not logged in"),console.log("Run `entrydesk login` to authenticate"));return}let n;if(o.workspaceId)try{let r=new G,i=await lt(),{workspaces:a}=await r.getWorkspaces(i);n=a.find(d=>d.id===o.workspaceId)?.name}catch(r){if(r 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){ke(t)}}import Ei from"fs";import{Client as xi}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as bi}from"@modelcontextprotocol/sdk/client/streamableHttp.js";async function Ci(e={}){let t=e.apiUrl,o=e.accessToken,s=e.workspaceId;if(!o||!s){let a=await fe();o=o||a.accessToken,s=s||a.workspaceId}t||(t=Ye().apiUrl);let n=new xi({name:"entrydesk-cli",version:"1.0.0"}),r=new URL(`${t}/v1/workspaces/${s}/mcp`),i=new bi(r,{requestInit:{headers:{Authorization:`Bearer ${o}`}}});return await n.connect(i),n}async function xo(){return Ci()}import Xo from"fs/promises";import $i from"os";import Vt from"path";var Yo=!process.env.NO_COLOR&&!!process.stdout.isTTY,At={green:Yo?"\x1B[32m":"",yellow:Yo?"\x1B[33m":"",reset:Yo?"\x1B[0m":""},Si=10*1024,Os=8*1024,Ls=2*1024,Ti=100,Ii=100;function vi(){return Vt.join($i.homedir(),".entrydesk","tool-results")}function Ai(e){let t=e.trim().replace(/[/\\:*?"<>|\s]/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,"").slice(0,Ti);return!t||t==="."||t===".."?"unnamed_tool":t}function Pi(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 Ni(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=Ai(e);return`${o}_${s}.json`}async function Rs(e,t){try{return await Xo.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=vi();await Xo.mkdir(o,{recursive:!0});let s=Ni(e),n=Vt.extname(s),r=s.slice(0,-n.length),i=Pi(t),a=Vt.join(o,s);if(await Rs(a,i))return a;for(let b=1;b<=Ii;b++){let C=Vt.join(o,`${r}-${b}${n}`);if(await Rs(C,i))return C}let l=Math.random().toString(36).slice(2,10),d=Vt.join(o,`${r}-${l}${n}`);return await Xo.writeFile(d,i,{encoding:"utf8",flag:"wx"}),d}catch(o){let s=o instanceof Error?o.message:"unknown error";return console.error(`${At.yellow}Warning: Could not save result to file: ${s}${At.reset}`),null}}function js(e,t){let o=Buffer.byteLength(e,"utf8");if(o<=Si)return e;let s=e.slice(0,Os),n=e.slice(-Ls),i=((o-Os-Ls)/1024).toFixed(1),a=(o/1024).toFixed(1),l=` ... (skipped ${i}KB of ${a}KB) ...`;return t&&(l+=`
479
484
  Tip: jq -r '.structuredContent.field' <file> | grep/head/tail`),`${s}
480
485
 
481
486
  ${l}
482
487
 
483
- ${n}`}function js(e){console.log(`${At.green}Tool execution result saved to: ${e}${At.reset}`),console.log()}function Fs(){console.log(`${At.green}Tool execution result:${At.reset}`)}function Ei(e){return e.split("__")[0]??e}function mt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Pt(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?mt("AUTH_MISSING",s,t):mt(o,s,t)}async function _i(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(i),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},r=x=>{s||(s=!0,n(),e(x))},i=setTimeout(()=>{o||r(null)},100),a=x=>{o=!0,clearTimeout(i),t.push(x)},l=()=>{t.length===0?r(null):r(Buffer.concat(t).toString("utf-8").trim())},d=()=>{r(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Ht=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Di(e,t){if(e)return e;if(t)try{return Ni.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Ht(`Failed to read input file: ${n}`)}let o=await _i();if(o)return o;throw new Ht("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Oi(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
484
- `)}function Li(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(`
485
- `)}async function Ri(e,t){let o=await bo().catch(s=>{Pt(s,e)});try{let n=(await o.listTools()).tools;if(t){let r=t.toLowerCase();n=n.filter(i=>Ei(i.name).toLowerCase().startsWith(r))}if(e)console.log(JSON.stringify(n,null,2));else{let r=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${r}:
486
- `);for(let i of n)console.log(Oi(i)),console.log()}}catch(s){Pt(s,e)}finally{await o.close().catch(()=>{})}}async function Ui(e,t){let o=await bo().catch(s=>{Pt(s,t)});try{let n=(await o.listTools()).tools.find(r=>r.name===e);n||mt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Li(n))}catch(s){Pt(s,t)}finally{await o.close().catch(()=>{})}}async function ji(e,t,o){let s;try{s=JSON.parse(t)}catch(i){let a=i instanceof Error?`Invalid JSON input: ${i.message}`:"Invalid JSON input";mt("INVALID_INPUT",a,o)}let n=await bo().catch(i=>{Pt(i,o,"TOOL_CALL_FAILED")}),r=!1;try{let i=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(i,null,2));else{let a=await Rs(e,i);a&&js(a),Fs();let l=i.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(i.structuredContent){let d=JSON.stringify(i.structuredContent,null,2),x=Us(d,a);console.log(x)}}i.isError&&(r=!0)}catch(i){Pt(i,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}r&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ri(t,e.prefix);break;case"get":e.name||mt("INVALID_INPUT","Tool name is required",t),await Ui(e.name,t);break;case"call":{e.name||mt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Di(e.input,e.inputFile)}catch(s){throw s instanceof Ht&&mt("INVALID_INPUT",s.message,t),s}await ji(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
488
+ ${n}`}function Fs(e){console.log(`${At.green}Tool execution result saved to: ${e}${At.reset}`),console.log()}function Ms(){console.log(`${At.green}Tool execution result:${At.reset}`)}function _i(e){return e.split("__")[0]??e}function mt(e,t,o){console.error(o?JSON.stringify({error:{code:e,message:t}}):`Error [${e}]: ${t}`),process.exit(1)}function Pt(e,t,o="CONNECTION_FAILED"){let s=e instanceof Error?e.message:"Unknown error";s.includes("Not logged in")||s.includes("not-logged-in")?mt("AUTH_MISSING",s,t):mt(o,s,t)}async function Di(){return process.stdin.isTTY?null:new Promise(e=>{let t=[],o=!1,s=!1,n=()=>{clearTimeout(i),process.stdin.removeListener("data",a),process.stdin.removeListener("end",l),process.stdin.removeListener("error",d)},r=b=>{s||(s=!0,n(),e(b))},i=setTimeout(()=>{o||r(null)},100),a=b=>{o=!0,clearTimeout(i),t.push(b)},l=()=>{t.length===0?r(null):r(Buffer.concat(t).toString("utf-8").trim())},d=()=>{r(null)};process.stdin.on("data",a),process.stdin.on("end",l),process.stdin.on("error",d),process.stdin.resume()})}var Ht=class extends Error{constructor(t){super(t),this.name="InputError"}};async function Oi(e,t){if(e)return e;if(t)try{return Ei.readFileSync(t,"utf-8").trim()}catch(s){let n=s instanceof Error?s.message:"Failed to read input file";throw new Ht(`Failed to read input file: ${n}`)}let o=await Di();if(o)return o;throw new Ht("Input JSON is required. Use --input, --input-file, or pipe via stdin")}function Li(e){let t=[];return t.push(`Tool: ${e.name}`),e.description&&t.push(` Description: ${e.description}`),t.join(`
489
+ `)}function Ri(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(`
490
+ `)}async function Ui(e,t){let o=await xo().catch(s=>{Pt(s,e)});try{let n=(await o.listTools()).tools;if(t){let r=t.toLowerCase();n=n.filter(i=>_i(i.name).toLowerCase().startsWith(r))}if(e)console.log(JSON.stringify(n,null,2));else{let r=t?` (prefix: ${t})`:"";console.log(`Available Tools (${n.length})${r}:
491
+ `);for(let i of n)console.log(Li(i)),console.log()}}catch(s){Pt(s,e)}finally{await o.close().catch(()=>{})}}async function ji(e,t){let o=await xo().catch(s=>{Pt(s,t)});try{let n=(await o.listTools()).tools.find(r=>r.name===e);n||mt("TOOL_NOT_FOUND",`Tool not found: ${e}`,t),console.log(t?JSON.stringify(n,null,2):Ri(n))}catch(s){Pt(s,t)}finally{await o.close().catch(()=>{})}}async function Fi(e,t,o){let s;try{s=JSON.parse(t)}catch(i){let a=i instanceof Error?`Invalid JSON input: ${i.message}`:"Invalid JSON input";mt("INVALID_INPUT",a,o)}let n=await xo().catch(i=>{Pt(i,o,"TOOL_CALL_FAILED")}),r=!1;try{let i=await n.callTool({name:e,arguments:s});if(o)console.log(JSON.stringify(i,null,2));else{let a=await Us(e,i);a&&Fs(a),Ms();let l=i.content;for(let d of l)d.type==="text"?console.log(d.text):d.type==="image"?console.log(`[Image: ${d.mimeType}]`):d.type==="resource"?console.log(`[Resource: ${d.resource?.uri??"unknown"}]`):console.log(JSON.stringify(d,null,2));if(i.structuredContent){let d=JSON.stringify(i.structuredContent,null,2),b=js(d,a);console.log(b)}}i.isError&&(r=!0)}catch(i){Pt(i,o,"TOOL_CALL_FAILED")}finally{await n.close().catch(()=>{})}r&&process.exit(1)}async function Ws(e){let t=e.json??!1;switch(e.action){case"list":await Ui(t,e.prefix);break;case"get":e.name||mt("INVALID_INPUT","Tool name is required",t),await ji(e.name,t);break;case"call":{e.name||mt("INVALID_INPUT","Tool name is required",t);let o;try{o=await Oi(e.input,e.inputFile)}catch(s){throw s instanceof Ht&&mt("INVALID_INPUT",s.message,t),s}await Fi(e.name,o,t);break}default:console.log(`Usage: entrydesk tool <action> [options]
487
492
 
488
493
  Actions:
489
494
  list List all available tools
@@ -508,7 +513,7 @@ Examples:
508
513
  entrydesk tool call agent__search_agents --input '{"limit": 5}'
509
514
  entrydesk tool call agent__search_agents --input-file input.json
510
515
  echo '{"limit": 5}' | entrydesk tool call agent__search_agents
511
- `);break}}function Fi(){console.log(`
516
+ `);break}}function Mi(){console.log(`
512
517
  Usage: entrydesk usage [options]
513
518
 
514
519
  Options:
@@ -521,10 +526,10 @@ Examples:
521
526
  entrydesk usage --limit 10 # Show top 10 users
522
527
  entrydesk usage --sort-by operations # Sort by operation count
523
528
  entrydesk usage --json # JSON output
524
- `)}async function Bs(e){if(e.help){Fi();return}let t,o;try{let h=await fe();t=h.accessToken,o=h.workspaceId}catch(h){let y=h instanceof Error?h.message:"Authentication failed";console.error(y),process.exit(1)}let s=new G,n=[],r,i=0,a=100;do{let h=await s.getMonthlyUsages(t,o,{nextKey:r,limit:100});if(n.push(...h.monthlyUsages),r=h.nextKey,i++,i>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(r);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
529
+ `)}async function Bs(e){if(e.help){Mi();return}let t,o;try{let h=await fe();t=h.accessToken,o=h.workspaceId}catch(h){let y=h instanceof Error?h.message:"Authentication failed";console.error(y),process.exit(1)}let s=new G,n=[],r,i=0,a=100;do{let h=await s.getMonthlyUsages(t,o,{nextKey:r,limit:100});if(n.push(...h.monthlyUsages),r=h.nextKey,i++,i>=a){console.error(`Warning: Showing first ${n.length} entries (pagination limit reached)`);break}}while(r);if(e.json){console.log(JSON.stringify(n));return}if(n.length===0){console.log("No usage data found for this workspace.");return}console.log(`Current Month Usage:
525
530
  `);let l=0,d=0;for(let h of n)l+=parseFloat(h.totalCost),d+=h.operationCount;console.log(`Total Cost: $${l.toFixed(2)}`),console.log(`Total Operations: ${d.toLocaleString()}`),console.log(`Users: ${n.length}
526
- `);let x=e.sortBy||"cost",C=[...n].toSorted((h,y)=>x==="cost"?parseFloat(y.totalCost)-parseFloat(h.totalCost):y.operationCount-h.operationCount),b=e.limit&&e.limit>0?e.limit:C.length,T=C.slice(0,b);console.log(`Usage by User (sorted by ${x}, showing ${T.length} of ${n.length}):
527
- `);for(let h of T){let y=parseFloat(h.totalCost);console.log(` ${h.user.name} (${h.user.email})`),console.log(` Cost: $${y.toFixed(2)}`),console.log(` Operations: ${h.operationCount.toLocaleString()}`),console.log("")}T.length<n.length&&console.log(`... and ${n.length-T.length} more users`)}function Zo(){console.log("entrydesk 1.9.2")}function Qo(){console.log(`
531
+ `);let b=e.sortBy||"cost",C=[...n].toSorted((h,y)=>b==="cost"?parseFloat(y.totalCost)-parseFloat(h.totalCost):y.operationCount-h.operationCount),x=e.limit&&e.limit>0?e.limit:C.length,T=C.slice(0,x);console.log(`Usage by User (sorted by ${b}, showing ${T.length} of ${n.length}):
532
+ `);for(let h of T){let y=parseFloat(h.totalCost);console.log(` ${h.user.name} (${h.user.email})`),console.log(` Cost: $${y.toFixed(2)}`),console.log(` Operations: ${h.operationCount.toLocaleString()}`),console.log("")}T.length<n.length&&console.log(`... and ${n.length-T.length} more users`)}function Zo(){console.log("entrydesk 1.10.0")}function Qo(){console.log(`
528
533
  Usage: entrydesk workspaces [list|switch|use] [options]
529
534
 
530
535
  Commands:
@@ -534,6 +539,6 @@ Commands:
534
539
 
535
540
  Flags:
536
541
  --json Output JSON
537
- `)}async function Ms(e){if(e.help){Qo();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await lt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",r=new G;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),Qo(),process.exit(1));let{workspaces:l}=await r.getWorkspaces(t),d=l.find(x=>x.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
538
- Available workspaces:`);for(let x of l)console.error(` ${x.name}: ${x.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}`),Qo(),process.exit(1));let{workspaces:i}=await r.getWorkspaces(t);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${i.length}):
539
- `);for(let a of i){let l=a.id===s?" (current)":"";console.log(` ${a.name}${l}`),console.log(` ID: ${a.id}`),console.log("")}}function Js(e,t,o=!1){let s={},n={};for(let r=o?0:1;r<e.length;r++){let i=e[r];if(i==="--json")s.json=!0;else if(i==="--help"||i==="-h")s.help=!0;else if(i==="--profile")s.profile=e[++r];else switch(t){case"login":break;case"chat":if(i==="-m"||i==="--message")n.message=e[++r];else if(i==="-a"||i==="--agent")n.agentId=e[++r];else if(i==="--model")n.model=e[++r];else if(i==="--connectors"){let a=e[++r];n.connectors=a?.split(",").map(l=>l.trim())}else i==="-i"||i==="--interactive"?n.interactive=!0:i==="--full-output"?n.fullOutput=!0:i==="-c"||i==="--continue"?n.continue=parseInt(e[++r],10):i==="--plain"?n.plain=!0:i==="--output"?n.output=e[++r]:i==="--sandbox"?n.sandbox=!0:i==="--no-sandbox"?n.noSandbox=!0:i==="--web-search"?n.webSearch=!0:i==="--image-gen"?n.imageGen=!0:i==="--chart"?n.chart=!0:i==="--file-system"?n.fileSystem=!0:i==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(i==="--name")n.name=e[++r];else if(i==="--description")n.description=e[++r];else if(i==="--system-prompt")n.systemPrompt=e[++r];else if(i==="--model-id")n.modelId=e[++r];else if(i==="--connector-ids"){let a=e[++r];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--capabilities"){let a=e[++r];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--conversation-starters"){let a=e[++r];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--tools"){let a=e[++r];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else i==="--icon-id"?n.iconId=e[++r]:i.startsWith("-")||(n.action?n.agentId=i:n.action=i);break;case"skills":i==="--force"?n.force=!0:i==="--me"||i==="--mine"?n.createdBy="me":i.startsWith("-")||(n.action?n.configKey=i:n.action=i);break;case"schedules":if(i==="--name")n.name=e[++r];else if(i==="--prompt")n.prompt=e[++r];else if(i==="--agent-id")n.agentId=e[++r];else if(i==="--starts-at")n.startsAt=e[++r];else if(i==="--utc-offset")n.utcOffset=e[++r];else if(i==="--repeat-type")n.repeatType=e[++r];else if(i==="--every")n.every=parseInt(e[++r],10);else if(i==="--time")n.time=e[++r];else if(i==="--days-of-week"){let a=e[++r];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(i==="--days-of-month"){let a=e[++r];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else i==="--last-day-of-month"?n.lastDayOfMonth=!0:i.startsWith("-")||(n.action?n.scheduleId=i:n.action=i);break;case"config":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")?n.configKey=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"profile":!n.action&&!i.startsWith("-")?n.action=i:!n.name&&!i.startsWith("-")?n.name=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"chats":i==="--share"||i==="-s"?n.shareId=e[++r]:i==="--full-output"?n.fullOutput=!0:i==="--output"?n.output=e[++r]:!n.chatId&&!i.startsWith("-")&&(n.chatId=i);break;case"budget":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")&&(n.configKey=i);break;case"usage":if(i==="--limit")n.limit=parseInt(e[++r],10);else if(i==="--sort-by"){let a=e[++r];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":i==="--http"?n.http=!0:(i==="-p"||i==="--port")&&(n.port=parseInt(e[++r],10));break;case"tool":i==="-i"||i==="--input"?n.input=e[++r]:i==="-f"||i==="--input-file"?n.inputFile=e[++r]:i==="-p"||i==="--prefix"?n.prefix=e[++r]:i.startsWith("-")||(n.action?n.name||(n.name=i):n.action=i);break;case"workspaces":!n.action&&!i.startsWith("-")&&(n.action=i);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as Ji}from"react/jsx-runtime";var Be=process.argv.slice(2);(Be[0]==="--help"||Be[0]==="-h")&&(wo(),process.exit(0));(Be[0]==="--version"||Be[0]==="-v")&&(Zo(),process.exit(0));var en=!Be[0]||Be[0].startsWith("-"),Bi=en?"chat":Be[0],be=Js(Be,Bi,en);en&&be.command==="chat"&&(be.interactive=!0);async function Mi(){try{if(be.command!=="profile"){let e=be.profile||J.getCurrentProfileName();J.ensureProfileExists(e),J.setOverrideProfile(e)}switch(be.command){case"login":await xs(be);break;case"logout":await Cs(be);break;case"status":await _s(be);break;case"workspaces":await Ms(be);break;case"agents":await an(be);break;case"models":await Is(be);break;case"connectors":await bs(be);break;case"skills":await Es(be);break;case"schedules":await Ps(be);break;case"chats":await ys(be);break;case"budget":await ln(be);break;case"usage":await Bs(be);break;case"config":be.action==="help"||Be[1]==="--help"?Wi(Ji(ks,{})):await ws(be);break;case"profile":await vs(be);break;case"chat":Be[1]==="--help"||Be[1]==="-h"?wo():await ds(be);break;case"mcp-server":await Ts({mode:be.http?"http":"stdio",port:be.port});break;case"tool":await Ws(be);break;case"version":Zo();break;default:wo();break}}catch(e){ke(e)}}Mi();
542
+ `)}async function Js(e){if(e.help){Qo();return}let t,s=(await $e.getAll())?.workspaceId;try{t=await lt()}catch(a){let l=a instanceof Error?a.message:"Authentication failed";console.error(l),process.exit(1)}let n=e.action||"list",r=new G;if(n==="switch"||n==="use"){let a=e.configKey;a||(console.error("Missing workspaceId for switch."),Qo(),process.exit(1));let{workspaces:l}=await r.getWorkspaces(t),d=l.find(b=>b.id===a);if(!d){console.error(`Workspace not found: ${a}`),console.error(`
543
+ Available workspaces:`);for(let b of l)console.error(` ${b.name}: ${b.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}`),Qo(),process.exit(1));let{workspaces:i}=await r.getWorkspaces(t);if(e.json){console.log(JSON.stringify(i));return}if(i.length===0){console.log("No workspaces found.");return}console.log(`Workspaces (${i.length}):
544
+ `);for(let a of i){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 r=o?0:1;r<e.length;r++){let i=e[r];if(i==="--json")s.json=!0;else if(i==="--help"||i==="-h")s.help=!0;else if(i==="--profile")s.profile=e[++r];else switch(t){case"login":break;case"chat":if(i==="-m"||i==="--message")n.message=e[++r];else if(i==="-a"||i==="--agent")n.agentId=e[++r];else if(i==="--model")n.model=e[++r];else if(i==="--connectors"){let a=e[++r];n.connectors=a?.split(",").map(l=>l.trim())}else i==="-i"||i==="--interactive"?n.interactive=!0:i==="--full-output"?n.fullOutput=!0:i==="-c"||i==="--continue"?n.continue=parseInt(e[++r],10):i==="--plain"?n.plain=!0:i==="--output"?n.output=e[++r]:i==="--sandbox"?n.sandbox=!0:i==="--no-sandbox"?n.noSandbox=!0:i==="--web-search"?n.webSearch=!0:i==="--image-gen"?n.imageGen=!0:i==="--chart"?n.chart=!0:i==="--file-system"?n.fileSystem=!0:i==="--no-file-system"&&(n.noFileSystem=!0);break;case"agents":if(i==="--name")n.name=e[++r];else if(i==="--description")n.description=e[++r];else if(i==="--system-prompt")n.systemPrompt=e[++r];else if(i==="--model-id")n.modelId=e[++r];else if(i==="--connector-ids"){let a=e[++r];n.connectorIds=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--capabilities"){let a=e[++r];n.capabilities=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--conversation-starters"){let a=e[++r];n.conversationStarters=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--tools"){let a=e[++r];n.tools=a?.split(",").map(l=>l.trim()).filter(Boolean)}else if(i==="--icon-id")n.iconId=e[++r];else if(i==="--limit"){let a=parseInt(e[++r],10);(isNaN(a)||a<1||a>100)&&(console.error("--limit must be an integer between 1 and 100"),process.exit(1)),n.limit=a}else if(i==="--next-key"){let a=e[++r];a||(console.error("--next-key requires a value"),process.exit(1)),n.nextKey=a}else i==="--all"?n.all=!0:i.startsWith("-")||(n.action?n.agentId=i:n.action=i);break;case"skills":i==="--force"?n.force=!0:i==="--me"||i==="--mine"?n.createdBy="me":i.startsWith("-")||(n.action?n.configKey=i:n.action=i);break;case"schedules":if(i==="--name")n.name=e[++r];else if(i==="--prompt")n.prompt=e[++r];else if(i==="--agent-id")n.agentId=e[++r];else if(i==="--starts-at")n.startsAt=e[++r];else if(i==="--utc-offset")n.utcOffset=e[++r];else if(i==="--repeat-type")n.repeatType=e[++r];else if(i==="--every")n.every=parseInt(e[++r],10);else if(i==="--time")n.time=e[++r];else if(i==="--days-of-week"){let a=e[++r];n.daysOfWeek=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else if(i==="--days-of-month"){let a=e[++r];n.daysOfMonth=a?.split(",").map(l=>parseInt(l.trim(),10)).filter(l=>!isNaN(l))}else i==="--last-day-of-month"?n.lastDayOfMonth=!0:i.startsWith("-")||(n.action?n.scheduleId=i:n.action=i);break;case"config":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")?n.configKey=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"profile":!n.action&&!i.startsWith("-")?n.action=i:!n.name&&!i.startsWith("-")?n.name=i:!n.value&&!i.startsWith("-")&&(n.value=i);break;case"chats":i==="--share"||i==="-s"?n.shareId=e[++r]:i==="--full-output"?n.fullOutput=!0:i==="--output"?n.output=e[++r]:!n.chatId&&!i.startsWith("-")&&(n.chatId=i);break;case"budget":!n.action&&!i.startsWith("-")?n.action=i:!n.configKey&&!i.startsWith("-")&&(n.configKey=i);break;case"usage":if(i==="--limit")n.limit=parseInt(e[++r],10);else if(i==="--sort-by"){let a=e[++r];(a==="cost"||a==="operations")&&(n.sortBy=a)}break;case"mcp-server":i==="--http"?n.http=!0:(i==="-p"||i==="--port")&&(n.port=parseInt(e[++r],10));break;case"tool":i==="-i"||i==="--input"?n.input=e[++r]:i==="-f"||i==="--input-file"?n.inputFile=e[++r]:i==="-p"||i==="--prefix"?n.prefix=e[++r]:i.startsWith("-")||(n.action?n.name||(n.name=i):n.action=i);break;case"workspaces":!n.action&&!i.startsWith("-")&&(n.action=i);break;default:break}}switch(t){case"login":return{command:"login",...s,...n};case"logout":return{command:"logout",...s,...n};case"status":return{command:"status",...s,...n};case"workspaces":return{command:"workspaces",...s,...n};case"agents":return{command:"agents",...s,...n};case"models":return{command:"models",...s,...n};case"connectors":return{command:"connectors",...s,...n};case"skills":return{command:"skills",...s,...n};case"schedules":return{command:"schedules",...s,...n};case"config":return{command:"config",...s,...n};case"profile":return{command:"profile",...s,...n};case"chat":return{command:"chat",...s,...n};case"chats":return{command:"chats",...s,...n};case"budget":return{command:"budget",...s,...n};case"usage":return{command:"usage",...s,...n};case"mcp-server":return{command:"mcp-server",...s,...n};case"tool":return{command:"tool",...s,...n};case"version":return{command:"version",...s,...n};default:return{command:"help",...s,...n}}}import{jsx as Gi}from"react/jsx-runtime";var We=process.argv.slice(2);(We[0]==="--help"||We[0]==="-h")&&(wo(),process.exit(0));(We[0]==="--version"||We[0]==="-v")&&(Zo(),process.exit(0));var en=!We[0]||We[0].startsWith("-"),Bi=en?"chat":We[0],xe=Gs(We,Bi,en);en&&xe.command==="chat"&&(xe.interactive=!0);async function Ji(){try{if(xe.command!=="profile"){let e=xe.profile||J.getCurrentProfileName();J.ensureProfileExists(e),J.setOverrideProfile(e)}switch(xe.command){case"login":await Cs(xe);break;case"logout":await $s(xe);break;case"status":await Ds(xe);break;case"workspaces":await Js(xe);break;case"agents":await ln(xe);break;case"models":await vs(xe);break;case"connectors":await bs(xe);break;case"skills":await _s(xe);break;case"schedules":await Ns(xe);break;case"chats":await ws(xe);break;case"budget":await cn(xe);break;case"usage":await Bs(xe);break;case"config":xe.action==="help"||We[1]==="--help"?Wi(Gi(xs,{})):await ks(xe);break;case"profile":await As(xe);break;case"chat":We[1]==="--help"||We[1]==="-h"?wo():await fs(xe);break;case"mcp-server":await Is({mode:xe.http?"http":"stdio",port:xe.port});break;case"tool":await Ws(xe);break;case"version":Zo();break;default:wo();break}}catch(e){ke(e)}}Ji();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entrydesk/cli",
3
- "version": "1.9.2",
3
+ "version": "1.10.0",
4
4
  "description": "EntryDesk CLI - Interact with EntryDesk from your terminal",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import F from"fs";import p from"fs";import Te from"os";import E from"path";import{HTTPError as Re,TimeoutError as xe}from"ky";import he,{TimeoutError as ye}from"ky";import x from"crypto";import u from"fs";import le from"path";var ge="ENTRYDESK_FORCE_FILE_STORAGE",A="EntryDesk CLI",de="__entrydesk_keychain_test__",ue="profile:",fe=".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 pe(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 N=class{getKeyFilePath(e){return le.join(o.getProfileDir(e),fe)}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],P=x.createDecipheriv("aes-256-gcm",t,n,{authTagLength:16});P.setAuthTag(i);let d=P.update(c,"hex","utf8");return d+=P.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{}}},M=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=pe(s)?s:null}catch{this.keytarModule=null}return this.keytarModule}getAccount(e){return`${ue}${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=`${de}${x.randomBytes(8).toString("hex")}`,s="test";await e.setPassword(A,t,s);let n=await e.getPassword(A,t),i=await e.deletePassword(A,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(A,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(A,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(A,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 N;keychainAvailable=null;initPromise=null;shouldForceFileStorage(){return process.env[ge]?.toLowerCase()==="true"}async initializeStorage(){if(this.shouldForceFileStorage()){this.keychainAvailable=!1,this.keychainStorage=null;return}try{let e=new M,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 I=class r{client;baseUrl;constructor(e,t){this.baseUrl=e||U(t),D().ignoreSslErrors&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0",process.env.DEBUG&&console.log("[DEBUG] ApiClient: SSL certificate validation disabled")),this.client=he.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 ye?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}};function me(){return process.env.ENTRYDESK_SANDBOX==="true"}function z(){if(!me())return null;let r=process.env.ENTRYDESK_SANDBOX_ACCESS_TOKEN?.trim(),e=process.env.ENTRYDESK_SANDBOX_WORKSPACE_ID?.trim();if(!r||!e){let t=[];throw r||t.push("ENTRYDESK_SANDBOX_ACCESS_TOKEN"),e||t.push("ENTRYDESK_SANDBOX_WORKSPACE_ID"),new Error(`Sandbox mode enabled but missing credentials: ${t.join(", ")}`)}return{accessToken:r,workspaceId:e}}function ee(){let r=process.env.ENTRYDESK_TOKEN?.trim();if(!r)return null;let e=process.env.ENTRYDESK_WORKSPACE_ID?.trim();if(!e)throw new Error("ENTRYDESK_TOKEN is set but ENTRYDESK_WORKSPACE_ID is missing. Both are required for PAT authentication.");return{accessToken:r,workspaceId:e}}import{execFile as we}from"child_process";import{setTimeout as ke}from"timers/promises";import{decodeJwt as ve}from"jose";import Se,{HTTPError as Pe}from"ky";var K="entrydesk-cli",Ce="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 Ae(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}we(n,i,c=>{c?t(new Error(`Failed to open browser. Please manually visit: ${r}`,{cause:c})):e()})})}async function tt(r){let e=U(),t=te(),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=Se.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:K,scope:Ce}}).json()}catch(a){let w=a instanceof Error?a:new Error("Failed to request device code");throw r?.onError?.(w),w}let{device_code:P,user_code:d,expires_in:oe,interval:ae}=c,J=new URL("/oauth/device",t);J.searchParams.set("user_code",d);let V=J.toString();r?.onDeviceCodeReceived?.(d,V),r?.onBrowserOpening?.();try{await Ae(V)}catch(a){process.env.DEBUG&&console.error("[DEBUG] Failed to open browser:",a)}r?.onWaitingForAuthorization?.();let q=Math.max(ae,5)*1e3,ce=Date.now()+oe*1e3;for(;Date.now()<ce;){await ke(q);try{let a=await i.post("v1/oauth/token",{json:{grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:P,client_id:K}}).json();r?.onAuthorized?.();let w={};try{w=ve(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 Pe){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}}var m=class extends Error{code;constructor(e,t){super(t),this.code=e}};function be(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 Ee(r,e=300){let s=be(r)?.exp;if(typeof s!="number")return!1;let n=Math.floor(Date.now()/1e3);return s-n<=e}async function re(r){let e=r.accessToken;if(!Ee(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 I().refreshOAuthToken({refreshToken:r.refreshToken,clientId:K});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 at(){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 re(e)}async function ct(){let r=z();if(r)return{accessToken:r.accessToken,workspaceId:r.workspaceId};let e=ee();if(e)return e;let t=await y.getAll();if(!t?.accessToken)throw new m("not-logged-in","Not logged in. Run `entrydesk login` first.");if(!t.workspaceId)throw new m("no-workspace","No workspace selected. Run `entrydesk workspaces` first.");return{accessToken:await re(t),workspaceId:t.workspaceId}}var f=class extends Error{constructor(t,s=1,n){super(t);this.exitCode=s;this.cause=n;this.name="CLIError"}};function ut(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 xe&&(console.error("Request timed out. Please check your connection and try again."),e&&r.stack&&console.error(r.stack),process.exit(1)),r instanceof Re&&(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 S="default",_e=/^[A-Za-z0-9_-]+$/,L=null;function H(){return E.join(Te.homedir(),".entrydesk")}function ne(){return E.join(H(),"profiles")}function ie(){return E.join(H(),"profiles.json")}function $(r){return E.join(ne(),r)}function G(r){if(!p.existsSync(r))p.mkdirSync(r,{mode:448,recursive:!0});else try{p.chmodSync(r,448)}catch{}}function Ie(){G(H())}function W(){G(ne())}function Ue(){let r=ie();try{if(!p.existsSync(r))return null;let e=p.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function b(r){Ie();let e=ie();p.writeFileSync(e,JSON.stringify(r,null,2),{mode:384});try{p.chmodSync(e,384)}catch{}}function De(r){let e=r.profiles?.length?Array.from(new Set(r.profiles)):[],t=r.currentProfile&&e.includes(r.currentProfile)?r.currentProfile:e[0]||S;return e.length===0&&e.push(S),e.includes(t)||e.unshift(t),{currentProfile:t,profiles:e}}function v(){let r=Ue();if(!r){let t={currentProfile:S,profiles:[S]};return b(t),W(),_(S),t}let e=De(r);return(e.currentProfile!==r.currentProfile||e.profiles.length!==r.profiles.length)&&b(e),W(),e}function C(r){if(!r)throw new f("Profile name is required.");if(!_e.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 se(r,e){if(r.profiles.includes(e))throw new f(`Profile already exists: ${e}`)}function _(r){W(),G($(r))}var o={DEFAULT_PROFILE:S,setOverrideProfile(r){L=r},getOverrideProfile(){return L},getProfileDir(r){return $(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 C(t),T(e,t),t},ensureProfileExists(r){let e=v();C(r),T(e,r)},createProfile(r){C(r);let e=v();se(e,r);let t={currentProfile:e.currentProfile,profiles:[...e.profiles,r]};b(t),_(r)},deleteProfile(r){C(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(S)?S:t[0]),b({currentProfile:s,profiles:t});try{p.rmSync(o.getProfileDir(r),{recursive:!0,force:!0})}catch{}return{currentProfile:s}},renameProfile(r,e){C(r),C(e);let t=v();T(t,r),se(t,e);let s=$(r),n=$(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){C(r);let e=v();T(e,r);let t={currentProfile:r,profiles:e.profiles};b(t),_(r)},ensureProfileDir:_};function Ke(r){let e=o.getEffectiveProfileName(r);return o.getProfileConfigFile(e)}function l(r){let e=Ke(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 Y={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",Fe="https://entrydesk.dcard.io",Be=3100,Oe=300*1e3;function B(r){return{apiUrl:Y.getApiUrl(r)||process.env.ENTRYDESK_API_URL||$e,hubUrl:Y.getHubUrl(r)||process.env.ENTRYDESK_HUB_URL||Fe,mcp:{httpPort:Be},auth:{loginTimeout:Oe,ignoreSslErrors:process.env.ENTRYDESK_IGNORE_SSL_ERRORS==="true"||!1}}}function U(r){return B(r).apiUrl}function te(r){return B(r).hubUrl}function Ct(){return B().mcp}function D(){return B().auth}export{K as a,tt as b,y as c,m as d,Ee as e,re as f,at as g,ct as h,f as i,ut as j,o as k,Y as l,B as m,U as n,te as o,Ct as p,D as q,I as r};