@zinley/orion 1.2.11 → 1.2.12
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.
- package/dist/index.js +176 -154
- package/package.json +12 -14
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Rt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var Tn=Object.getOwnPropertyNames;var Sn=Object.prototype.hasOwnProperty;var Cn=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var N=(c,e)=>()=>(c&&(e=c(c=0)),e);var ae=(c,e)=>{for(var t in e)Rt(c,t,{get:e[t],enumerable:!0})},xn=(c,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Tn(e))!Sn.call(c,n)&&n!==t&&Rt(c,n,{get:()=>e[n],enumerable:!(s=wn(e,n))||s.enumerable});return c};var kn=c=>xn(Rt({},"__esModule",{value:!0}),c);var hs={};ae(hs,{AccountStatus:()=>gs,SNOWX_MODELS:()=>X,SignUpMethod:()=>ms,SnowXProvider:()=>Ft,TaskStatus:()=>ps,TodoStatus:()=>ds});var Ft,X,ds,ps,ms,gs,Pe=N(()=>{"use strict";Ft=(r=>(r.GPT="GPT",r.BEDROCK="BEDROCK",r.ANTHROPIC="ANTHROPIC",r.OPENAI="OPENAI",r.FOUNDRY="FOUNDRY",r.GOOGLE="google",r))(Ft||{}),X=[{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-5.1",displayName:"GPT-5.1 High",provider:"GPT",apiModelName:"gpt-5.1-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-codex",displayName:"GPT-5.1 Codex",provider:"GPT",apiModelName:"gpt-5.1-codex",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-chat",displayName:"GPT-5.1",provider:"GPT",apiModelName:"gpt-5.1",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-o3-pro",displayName:"GPT o3-pro",provider:"GPT",apiModelName:"o3-pro",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"high"},{name:"snowx-o3",displayName:"GPT o3",provider:"GPT",apiModelName:"o3",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"medium"},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.5-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0}],ds=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s))(ds||{}),ps=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(ps||{}),ms=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(ms||{}),gs=(s=>(s.ACTIVE="active",s.SUSPENDED="suspended",s.PENDING="pending",s))(gs||{})});var $t,i,B=N(()=>{"use strict";$t=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},i=$t.getInstance()});var fe={};ae(fe,{UserDefaults:()=>Te});import Be from"fs";import Ot from"path";import En from"os";var _t,Te,ce=N(()=>{"use strict";B();_t=class c{static instance;preferencesPath;preferences={};constructor(){let e=Ot.join(En.homedir(),".orion");this.preferencesPath=Ot.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Be.existsSync(this.preferencesPath)){let e=Be.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),i.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{i.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=Ot.dirname(this.preferencesPath);Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),Be.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),i.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){i.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),i.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),i.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Te=_t.getInstance()});var ie,Mt=N(()=>{"use strict";Pe();ce();B();ie=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){return["snowx-o4.5","snowx-o3-pro","snowx-5-pro"].includes(e)?1:0}static getCurrentUserTier(){let e=Te.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Te.set("userSubscriptionTier",e),i.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),n=t>=s;return i.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${s} (${this.getDisplayName(s)}), Access=${n}`),n}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return X.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import In from"axios";import{EventEmitter as Pn}from"events";var Ce,Se,tt=N(()=>{"use strict";Ce="firebase_timestamp",Se=class c extends Pn{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=In.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return c.instance||(c.instance=new c),c.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),fe));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ne(),fs));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let s=await this.getAccessToken();s&&(e.Authorization=s)}}async createDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",o,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};t&&(n.limit=t.toString());try{let r=(await this.client.get("/documents",{params:n,headers:s})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async queryDocuments(e,t,s,n,o,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:s,value:String(n)};o&&(u.limit=o.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let f=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(f.success)return Array.isArray(f.doc)?f.doc:f.doc&&typeof f.doc=="object"?[f.doc]:[];{let v=f.error||"Unknown error";throw new Error(v)}}catch(p){throw p}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:n,headers:s})).data;return r.success?r.doc:null}catch(o){throw o}}async updateDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:n,headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,s,n,o){let r=`${e}/${t}/${s}`;return this.createDocument(r,n,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let s=`snowx_conversations/${e}/messages`;try{let n=await this.getDocuments(s);for(let o of n)o.id&&await this.deleteDocument(s,o.id);for(let[o,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${o}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(s,a,l)}catch{}}}catch(n){throw n}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((n,o)=>{if(n.order!==void 0&&o.order!==void 0)return n.order-o.order;let r=new Date(n.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,updates:t};try{let r=(await this.client.put("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let o=(await this.client.get("/realtime",{params:s,headers:t})).data;if(o.success)return o.doc;{let r=o.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let o=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!o.success){let r=o.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=await this.client.get("/realtime",{params:s,headers:t}),o=n.data;if(o.success)return n.data.data;{let r=o.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime/push",n,{headers:s})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var qe={};ae(qe,{DeviceRegistrationService:()=>de});import{EventEmitter as Dn}from"events";import{v4 as vs}from"uuid";import He from"os";import ys from"fs/promises";import An from"path";import{execSync as Ge}from"child_process";import Nn from"crypto";var de,be=N(()=>{"use strict";tt();ne();B();de=class c extends Dn{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Se.getInstance(),this.authService=H.getInstance(),this.configDir=An.join(He.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){i.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{i.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{i.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();i.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(i.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){i.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),i.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(i.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,i.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),i.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw i.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}i.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),i.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){i.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return i.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=He.platform();if(e==="darwin")try{let n=Ge("scutil --get ComputerName",{encoding:"utf8"}).trim();if(n)return i.debug(`[DEVICE REG] macOS ComputerName: ${n}`),n}catch{i.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let n=Ge('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(n&&n[1]){let o=n[1].trim();if(o)return i.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{i.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=He.hostname();return i.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return i.debug(`[DEVICE REG] Error getting computer name: ${e}`),He.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=He.platform();try{let t=null;switch(e){case"darwin":try{let a=Ge("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],i.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=Ge("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],i.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await ys.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await ys.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),i.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{i.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=Ge("wmic csproduct get UUID",{encoding:"utf8"}).split(`
|
|
3
|
-
`).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),i.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:i.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=Nn.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return i.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:s}=await Promise.resolve().then(()=>(ce(),fe)),n="snowx_fallback_device_id",o=s.string(n);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=vs(),s.set(n,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID: ${o}`)),o}catch(t){i.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:s}=await Promise.resolve().then(()=>(ce(),fe)),n="snowx_fallback_device_id",o=s.string(n);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=vs(),s.set(n,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,s){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,s);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,s){try{let n=await this.api.getDocument(this.devicesCollection,e);if(n&&n.devices){let o=n.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(l=>l.deviceId===t?{...l,lastSeenAt:Ce,computerName:s,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:Ce,lastSeenAt:Ce};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let r={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:Ce,lastSeenAt:Ce}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}i.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:s})}catch(n){throw i.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:n.message,code:n.code}),n}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let s=await this.api.getDocument(this.devicesCollection,e);if(!s||!s.devices||!Array.isArray(s.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let n=s.devices;if(!n.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=n.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var fs={};ae(fs,{AuthService:()=>H});import{EventEmitter as Rn}from"events";import{signInAnonymously as Fn,signInWithEmailAndPassword as $n,createUserWithEmailAndPassword as On,signOut as _n,onAuthStateChanged as bs,updateProfile as Mn,signInWithCustomToken as Un}from"firebase/auth";import xe from"axios";import Ut from"fs/promises";import ws from"path";import Ln from"os";var H,ne=N(()=>{"use strict";Mt();B();H=class c extends Rn{static instance;auth=null;currentUser=null;authToken=null;userProfile=null;tokenFilePath;snowxAuthEndpoint="https://snowx.ai/api/auth";snowxApiEndpoint="https://snowx.ai/api-beta/api";constructor(){super(),this.tokenFilePath=ws.join(Ln.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=ws.dirname(this.tokenFilePath);await Ut.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),fe)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let n=await Ut.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(n);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,s=o.token,await Ut.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&s){let n={token:s,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=n,i.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(n)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(n)}this.emit("authenticated",n)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),fe));t.set("snowx_auth_token",e.userId),t.set("snowx_access_token",e.token),this.authToken=e,this.emit("authenticated",e)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),fe));e.remove("snowx_auth_token"),e.remove("snowx_access_token"),this.authToken=null}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,bs(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}ie.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(ce(),fe));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),i.debug(`User tier updated: ${ie.getDisplayName(t)} (${e.tier})`),i.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await Fn(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await $n(this.auth,e,t);return this.currentUser=s.user,!0}catch(s){return console.error("❌ Failed to sign in with email:",s.message),!1}}async signUpWithEmail(e,t,s){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await On(this.auth,e,t);return this.currentUser=n.user,s&&await Mn(n.user,{displayName:s}),!0}catch(n){return console.error("❌ Failed to sign up with email:",n.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(be(),qe));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await _n(this.auth)}catch(t){console.warn("⚠️ [AUTH] Firebase sign out error:",t)}return this.currentUser=null,this.authToken=null,await this.clearStoredToken(),await this.clearAllSnowXUserDefaults(e),this.emit("signed_out"),!0}catch(e){return console.error("❌ [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(be(),qe));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),fe)),s=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of s)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let o=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of o)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await xe.post(`${this.snowxAuthEndpoint}/login`,e):t=await xe.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let s={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(s),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await xe.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),fe));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let s=await new Promise(n=>{let o=!1,r,a=bs(this.auth,async l=>{if(!o)if(o=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);n(u)}catch{n(null)}else n(null)});r=setTimeout(()=>{o||(o=!0,a(),n(null))},2e3)});if(s)return s}let e=await this.getAccessTokenFromStorage();return e?(i.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){i.debug("Using existing authentication token"),i.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let s=this.parseFirebaseIdToken(t);return s&&Date.now()<=s.exp*1e3?(i.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(i.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(s){return i.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.response?.status===404?(i.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):i.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),i.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),i.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),i.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),i.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),i.debug("Signing into Firebase with custom token...");let t=await Un(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),i.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),i.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let s=4-t;console.log(`📡 [AUTH-API] Attempt ${s}/3: Getting custom token for user: ${e}`),i.debug(`Getting custom token from API for user: ${e} (attempt ${s}/3)`);let n="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${n}`);try{let l=await xe.post(n,o,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let p=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${p}`),new Error(`Custom token API failed: ${p}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),i.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${s}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),i.error("Failed to get custom token:",{attempt:s,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let p=Math.pow(2,s)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${p}ms... (${t-1} attempts remaining)`),i.debug(`Retrying in ${p}ms...`),await new Promise(f=>setTimeout(f,p)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let s=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:s.user_id||s.sub,email:s.email,name:s.name,exp:s.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let s={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(s);try{let n=await this.getUserProfileWithIdToken(e,t.userId);n&&(this.authToken.tier=n.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let s=await xe.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(s.data?.success&&s.data?.doc){let n=s.data.doc,o=n.subscription?.tier??0;return{id:t,email:n.email,tier:o}}return null}catch(s){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${s.response?.status||s.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await xe.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let s=t.data.data,n=s.id||s.uid||s.user_id||s.userId||s.email;if(!n)throw new Error("No user ID found in API response");let o={token:e,userId:n,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=s,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(i.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):i.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",o),this.emit("AuthenticationComplete",n),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await xe.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),s=t===1?1:t===2?2:0;return ie.isModelAccessible(e,s)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await xe.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,s=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=s,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:s}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var Ts={};ae(Ts,{MessageQueueManager:()=>pe});import{EventEmitter as Wn}from"events";var pe,Ne=N(()=>{"use strict";B();pe=class c extends Wn{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),i.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),i.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});var st,Ss=N(()=>{"use strict";B();st=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),i.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let s=e.toLowerCase();for(let[n,o]of this.tools.entries())if(n.toLowerCase()===s)return o}async executeTool(e,t,s,n){let o=this.getTool(e);if(!o)return i.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{i.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await o.execute(t,e,s,n),l=Date.now()-r;i.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(p=>p.text||"").join(`
|
|
4
|
-
`);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(r){return i.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),
|
|
5
|
-
${
|
|
2
|
+
var Rt=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var ks=Object.prototype.hasOwnProperty;var Es=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var R=(c,e)=>()=>(c&&(e=c(c=0)),e);var ae=(c,e)=>{for(var t in e)Rt(c,t,{get:e[t],enumerable:!0})},Is=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xs(e))!ks.call(c,s)&&s!==t&&Rt(c,s,{get:()=>e[s],enumerable:!(n=Cs(e,s))||n.enumerable});return c};var Ps=c=>Is(Rt({},"__esModule",{value:!0}),c);var fn={};ae(fn,{AccountStatus:()=>hn,SNOWX_MODELS:()=>X,SignUpMethod:()=>gn,SnowXProvider:()=>Ft,TaskStatus:()=>mn,TodoStatus:()=>pn});var Ft,X,pn,mn,gn,hn,De=R(()=>{"use strict";Ft=(r=>(r.GPT="GPT",r.BEDROCK="BEDROCK",r.ANTHROPIC="ANTHROPIC",r.OPENAI="OPENAI",r.FOUNDRY="FOUNDRY",r.GOOGLE="google",r))(Ft||{}),X=[{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-5.1",displayName:"GPT-5.1 High",provider:"GPT",apiModelName:"gpt-5.1-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-codex",displayName:"GPT-5.1 Codex",provider:"GPT",apiModelName:"gpt-5.1-codex",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-chat",displayName:"GPT-5.1",provider:"GPT",apiModelName:"gpt-5.1",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-o3-pro",displayName:"GPT o3-pro",provider:"GPT",apiModelName:"o3-pro",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"high"},{name:"snowx-o3",displayName:"GPT o3",provider:"GPT",apiModelName:"o3",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"medium"},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.5-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0}],pn=(n=>(n.PENDING="pending",n.IN_PROGRESS="in_progress",n.COMPLETED="completed",n))(pn||{}),mn=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(mn||{}),gn=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(gn||{}),hn=(n=>(n.ACTIVE="active",n.SUSPENDED="suspended",n.PENDING="pending",n))(hn||{})});var $t,i,B=R(()=>{"use strict";$t=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},i=$t.getInstance()});var ve={};ae(ve,{UserDefaults:()=>Se});import Be from"fs";import Ot from"path";import Ds from"os";var _t,Se,ce=R(()=>{"use strict";B();_t=class c{static instance;preferencesPath;preferences={};constructor(){let e=Ot.join(Ds.homedir(),".orion");this.preferencesPath=Ot.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Be.existsSync(this.preferencesPath)){let e=Be.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),i.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{i.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=Ot.dirname(this.preferencesPath);Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),Be.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),i.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){i.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),i.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),i.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Se=_t.getInstance()});var ie,Mt=R(()=>{"use strict";De();ce();B();ie=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){return["snowx-o4.5","snowx-o3-pro","snowx-5-pro"].includes(e)?1:0}static getCurrentUserTier(){let e=Se.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Se.set("userSubscriptionTier",e),i.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let n=this.getRequiredTier(e),s=t>=n;return i.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${n} (${this.getDisplayName(n)}), Access=${s}`),s}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return X.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import As from"axios";import{EventEmitter as Ns}from"events";var xe,Ce,tt=R(()=>{"use strict";xe="firebase_timestamp",Ce=class c extends Ns{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=As.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return c.instance||(c.instance=new c),c.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(se(),vn));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let r=(await this.client.get("/documents",{params:s,headers:n})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async queryDocuments(e,t,n,s,o,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:n,value:String(s)};o&&(u.limit=o.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let f=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(f.success)return Array.isArray(f.doc)?f.doc:f.doc&&typeof f.doc=="object"?[f.doc]:[];{let y=f.error||"Unknown error";throw new Error(y)}}catch(p){throw p}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return r.success?r.doc:null}catch(o){throw o}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,n,s,o){let r=`${e}/${t}/${n}`;return this.createDocument(r,s,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let o of s)o.id&&await this.deleteDocument(n,o.id);for(let[o,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${o}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(n,a,l)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,o)=>{if(s.order!==void 0&&o.order!==void 0)return s.order-o.order;let r=new Date(s.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let r=(await this.client.put("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.get("/realtime",{params:n,headers:t})).data;if(o.success)return o.doc;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!o.success){let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),o=s.data;if(o.success)return s.data.data;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime/push",s,{headers:n})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var Ge={};ae(Ge,{DeviceRegistrationService:()=>de});import{EventEmitter as Rs}from"events";import{v4 as yn}from"uuid";import He from"os";import bn from"fs/promises";import Fs from"path";import{execSync as qe}from"child_process";import $s from"crypto";var de,we=R(()=>{"use strict";tt();se();B();de=class c extends Rs{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Ce.getInstance(),this.authService=H.getInstance(),this.configDir=Fs.join(He.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){i.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{i.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{i.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();i.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(i.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){i.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),i.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(i.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,i.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),i.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw i.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}i.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),i.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){i.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return i.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=He.platform();if(e==="darwin")try{let s=qe("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return i.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{i.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=qe('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let o=s[1].trim();if(o)return i.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{i.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=He.hostname();return i.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return i.debug(`[DEVICE REG] Error getting computer name: ${e}`),He.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=He.platform();try{let t=null;switch(e){case"darwin":try{let a=qe("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],i.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=qe("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],i.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await bn.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await bn.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),i.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{i.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=qe("wmic csproduct get UUID",{encoding:"utf8"}).split(`
|
|
3
|
+
`).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),i.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:i.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=$s.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return i.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=yn(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID: ${o}`)),o}catch(t){i.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=yn(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let o=s.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(l=>l.deviceId===t?{...l,lastSeenAt:xe,computerName:n,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:xe,lastSeenAt:xe};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let r={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:xe,lastSeenAt:xe}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}i.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw i.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=s.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var vn={};ae(vn,{AuthService:()=>H});import{EventEmitter as Os}from"events";import{signInAnonymously as _s,signInWithEmailAndPassword as Ms,createUserWithEmailAndPassword as Us,signOut as Ls,onAuthStateChanged as wn,updateProfile as Ws,signInWithCustomToken as Bs}from"firebase/auth";import ke from"axios";import Ut from"fs/promises";import Tn from"path";import Hs from"os";var H,se=R(()=>{"use strict";Mt();B();H=class c extends Os{static instance;auth=null;currentUser=null;authToken=null;userProfile=null;tokenFilePath;snowxAuthEndpoint="https://snowx.ai/api/auth";snowxApiEndpoint="https://snowx.ai/api-beta/api";constructor(){super(),this.tokenFilePath=Tn.join(Hs.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=Tn.dirname(this.tokenFilePath);await Ut.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve)),t=e.string("snowx_auth_token"),n=e.string("snowx_access_token");if(!t||!n)try{let s=await Ut.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(s);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,n=o.token,await Ut.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&n){let s={token:n,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=s,i.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(s)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(s)}this.emit("authenticated",s)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),ve));t.set("snowx_auth_token",e.userId),t.set("snowx_access_token",e.token),this.authToken=e,this.emit("authenticated",e)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));e.remove("snowx_auth_token"),e.remove("snowx_access_token"),this.authToken=null}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,wn(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}ie.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),i.debug(`User tier updated: ${ie.getDisplayName(t)} (${e.tier})`),i.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await _s(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Ms(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await Us(this.auth,e,t);return this.currentUser=s.user,n&&await Ws(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(we(),Ge));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ls(this.auth)}catch(t){console.warn("⚠️ [AUTH] Firebase sign out error:",t)}return this.currentUser=null,this.authToken=null,await this.clearStoredToken(),await this.clearAllSnowXUserDefaults(e),this.emit("signed_out"),!0}catch(e){return console.error("❌ [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(we(),Ge));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),ve)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of n)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let o=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of o)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await ke.post(`${this.snowxAuthEndpoint}/login`,e):t=await ke.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await ke.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let o=!1,r,a=wn(this.auth,async l=>{if(!o)if(o=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);s(u)}catch{s(null)}else s(null)});r=setTimeout(()=>{o||(o=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(i.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){i.debug("Using existing authentication token"),i.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(i.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(i.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return i.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(i.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):i.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),i.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),i.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),i.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),i.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),i.debug("Signing into Firebase with custom token...");let t=await Bs(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),i.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),i.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),i.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let l=await ke.post(s,o,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let p=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${p}`),new Error(`Custom token API failed: ${p}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),i.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),i.error("Failed to get custom token:",{attempt:n,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let p=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${p}ms... (${t-1} attempts remaining)`),i.debug(`Retrying in ${p}ms...`),await new Promise(f=>setTimeout(f,p)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await ke.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,o=s.subscription?.tier??0;return{id:t,email:s.email,tier:o}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await ke.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let o={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=n,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(i.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):i.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",o),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await ke.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return ie.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await ke.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var Sn={};ae(Sn,{MessageQueueManager:()=>pe});import{EventEmitter as qs}from"events";var pe,Ne=R(()=>{"use strict";B();pe=class c extends qs{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),i.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),i.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});var nt,Cn=R(()=>{"use strict";B();nt=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),i.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,o]of this.tools.entries())if(s.toLowerCase()===n)return o}async executeTool(e,t,n,s){let o=this.getTool(e);if(!o)return i.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{i.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await o.execute(t,e,n,s),l=Date.now()-r;i.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(p=>p.text||"").join(`
|
|
4
|
+
`);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(r){return i.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);i.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),i.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var xn={};ae(xn,{ToolDisplay:()=>_});import z from"chalk";var _,me=R(()=>{"use strict";_=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,n){if(c.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(z.cyan(`
|
|
5
|
+
${s} ${z.bold(e)}`)),t&&console.log(z.gray(` ${t}`)),n){let o=n.length>120?n.substring(0,120)+z.gray("..."):n;console.log(z.white(` ${o}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(c.customUIMode)return;let{toolName:t,output:n,success:s,executionTime:o,truncateLines:r=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,r):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,r):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,r):a=this.formatGenericOutput(n,r)),a&&a.trim()&&console.log(a);let l=s?z.green("✓"):z.red("✗"),u=s?z.green("SUCCESS"):z.red("FAILED"),p=o?z.gray(` (${o}ms)`):"";console.log(`${l} ${u}${p}
|
|
6
6
|
`)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
|
|
7
|
-
`),u=a.slice(0,20).map(p=>
|
|
7
|
+
`),u=a.slice(0,20).map(p=>z.gray(" ")+p).join(`
|
|
8
8
|
`);return a.length>20&&(u+=`
|
|
9
|
-
`+
|
|
10
|
-
`),
|
|
11
|
-
`);let r=
|
|
9
|
+
`+z.gray(` ... (${a.length-20} more lines)`)),u}let n=e.split(`
|
|
10
|
+
`),s=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";s&&(o+=z.gray(" ")+z.dim(s[1])+`
|
|
11
|
+
`);let r=n.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(o+=r.slice(0,10).map(a=>z.gray(" ")+z.dim(a)).join(`
|
|
12
12
|
`),r.length>10&&(o+=`
|
|
13
|
-
`+
|
|
14
|
-
`).filter(r=>r.trim());if(
|
|
15
|
-
`);let o=
|
|
13
|
+
`+z.gray(` ... (${r.length-10} more changes)`)),o):this.truncateOutput(e,Math.min(15,t))}static formatWriteOutput(e,t){return this.truncateOutput(e,Math.min(15,t))}static formatBashOutput(e,t){return this.truncateOutput(e,Math.min(30,t))}static formatGenericOutput(e,t){return this.truncateOutput(e,Math.min(20,t))}static truncateOutput(e,t){let n=e.split(`
|
|
14
|
+
`).filter(r=>r.trim());if(n.length===0)return"";if(n.length<=t)return n.map(r=>z.gray(" ")+z.dim(r)).join(`
|
|
15
|
+
`);let o=n.slice(0,t).map(r=>z.gray(" ")+z.dim(r)).join(`
|
|
16
16
|
`);return o+=`
|
|
17
|
-
`+
|
|
18
|
-
${
|
|
17
|
+
`+z.gray(` ... (${n.length-t} more lines)`),o}static error(e,t){c.customUIMode||(console.log(`
|
|
18
|
+
${z.red("✗")} ${z.red.bold(e)} ${z.red("ERROR")}`),console.log(z.gray(" ")+z.white(t)),console.log(""))}}});import kn from"os";import Lt from"path";function st(){return process.platform==="win32"}function Ae(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,kn.homedir())),st()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,kn.homedir())),!st()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),st()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Re(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=Ae(c);if(st()){let n=Lt.basename(e).split(".")[0].toUpperCase();if(Gs.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return Lt.isAbsolute(e)?Lt.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
|
|
19
19
|
|
|
20
20
|
Path must be absolute (start with / on Unix or C:\\ on Windows)
|
|
21
21
|
|
|
22
22
|
Wrong: Downloads/file.pdf
|
|
23
|
-
Correct: /Users/username/Downloads/file.pdf`}}var
|
|
24
|
-
`),g=d.length,m=Math.max(r??0,0),
|
|
23
|
+
Correct: /Users/username/Downloads/file.pdf`}}var Gs,ot=R(()=>{"use strict";Gs=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});var it,En=R(()=>{"use strict";B();me();ot();it=class{toolNames=["read","Read"];async execute(e,t,n,s){let o=n.file_path||n.path,r=n.offset,a=n.limit;if(!o)throw new Error("Missing file_path or path argument");let l=Ae(o),u=Re(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];i.debug(`[ReadFileTool] Reading file: ${l}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let p=Date.now();_.start("Read",n.description,l);try{let f=await import("fs/promises");try{await f.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let y=await f.stat(l);if(y.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let T=await f.readFile(l,"utf-8"),b=T.length,d=T.split(`
|
|
24
|
+
`),g=d.length,m=Math.max(r??0,0),C=87500;if(b>C&&r===void 0&&a===void 0){let M=y.size/1024,q=M/1024,P=q>=1?`${q.toFixed(2)} MB`:`${M.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
|
|
25
25
|
|
|
26
26
|
File Information:
|
|
27
27
|
- Path: ${l}
|
|
28
|
-
- Size: ${P} (${
|
|
28
|
+
- Size: ${P} (${b} characters)
|
|
29
29
|
- Total Lines: ${g}
|
|
30
|
-
- Character Limit: ${
|
|
30
|
+
- Character Limit: ${C.toLocaleString()}
|
|
31
31
|
|
|
32
32
|
Suggested Solutions:
|
|
33
33
|
1. Read specific lines using offset and limit:
|
|
@@ -41,19 +41,19 @@ Suggested Solutions:
|
|
|
41
41
|
- Lines 2000-4000: Read(path: "${l}", offset: 2000, limit: 2000)
|
|
42
42
|
- And so on...
|
|
43
43
|
|
|
44
|
-
The file has ${g.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(g===0||
|
|
45
|
-
`),
|
|
44
|
+
The file has ${g.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(g===0||T.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(m>=g)return[{type:"text",text:`Error: Offset ${m} is beyond file length. File has ${g} total lines. Try a smaller offset (0 to ${g-1}).`}];let S=a!==void 0?Math.min(m+a,g):g,k=d.slice(m,S),v=k.map((M,q)=>`${(m+q+1).toString().padStart(6," ")} ${M}`).join(`
|
|
45
|
+
`),x=v;if(r!==void 0||a!==void 0){let M=`
|
|
46
46
|
|
|
47
|
-
[Read ${
|
|
47
|
+
[Read ${k.length} lines (${m+1}-${S}) of ${g} total lines]`;x=v+M}let A=Date.now()-p;return _.result({toolName:"Read",filePath:l,output:x,success:!0,executionTime:A}),[{type:"text",text:x}]}catch(f){i.debug(`[ReadFileTool] Failed to read file: ${f.message}`);let y;f.code==="ENOENT"?y=`Error: File does not exist at path: ${l}`:f.code==="EACCES"?y=`Error: Permission denied. Cannot read file: ${l}`:f.code==="EISDIR"?y=`Error: Path is a directory, not a file: ${l}`:y=`Error reading file: ${f.message}`;let T=Date.now()-p;return _.result({toolName:"Read",filePath:l,output:y,success:!1,executionTime:T}),[{type:"text",text:y}]}}}});import rt from"fs/promises";import zs from"form-data";import Wt from"axios";import Bt from"path";var at,In=R(()=>{"use strict";B();me();se();at=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let o=n.path;if(!o)throw new Error("Missing path argument");i.debug(`[ReadSpecialFileTool] Converting file: ${o}`);let r=Date.now();_.start("ReadSpecialFile",n.description,o);try{try{await rt.access(o)}catch{return[{type:"text",text:`Error: File does not exist at path: ${o}`}]}let a=Bt.extname(o).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let S=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
|
|
48
48
|
|
|
49
|
-
Supported file types: ${
|
|
49
|
+
Supported file types: ${S}`}]}let l=await rt.stat(o),u=Bt.basename(o);if(i.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){i.debug(`[ReadSpecialFileTool] Image file detected: ${o}`);let k=(await rt.readFile(o)).toString("base64"),v=this.imageMimeTypes[a]||"application/octet-stream";i.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${k.length} chars)`);let x=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:x}),[{type:"image_url",image_url:{url:`data:${v};base64,${k}`}}]}let p=await this.uploadToBatchAPI(o,u);i.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${p}`);let f=await this.pollBatchStatus(p);i.debug("[ReadSpecialFileTool] Conversion completed");let y=f.files[0];if(!y||y.status==="failed"){let S=y?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${S}`}]}let T=await this.fetchFileContent(y.file_id);if(!T.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let b=l.size/1024,d=b/1024,g=d>=1?`${d.toFixed(2)} MB`:`${b.toFixed(2)} KB`,m=`# File: ${u}
|
|
50
50
|
**Type:** ${a.toUpperCase()}
|
|
51
51
|
**Size:** ${g}
|
|
52
52
|
**Conversion:** ✅ Successful
|
|
53
53
|
|
|
54
54
|
---
|
|
55
55
|
|
|
56
|
-
${
|
|
56
|
+
${T.markdown_content}`,C=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${g})`,success:!0,executionTime:C}),[{type:"text",text:m}]}catch(a){i.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
|
|
57
57
|
|
|
58
58
|
This could be due to:
|
|
59
59
|
• File corruption or invalid format
|
|
@@ -61,37 +61,37 @@ This could be due to:
|
|
|
61
61
|
• Unsupported document structure
|
|
62
62
|
• File is password-protected or encrypted
|
|
63
63
|
|
|
64
|
-
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let
|
|
64
|
+
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let n=await rt.readFile(e),s=Bt.extname(t).substring(1).toLowerCase(),r=await H.getInstance().getFirebaseIdToken(),a=new zs;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await Wt.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let n=await H.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let o=1;o<=this.maxPollAttempts;o++)try{let a=(await Wt.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(i.debug(`[ReadSpecialFileTool] Poll ${o} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(r){throw r.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${r.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await H.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let o=await Wt.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(o.data.status==="failed")throw new Error(o.data.error||"Unknown conversion error");return o.data}catch(o){throw o.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${o.message}`)}}getMimeType(e){switch(e.toLowerCase()){case"pdf":return"application/pdf";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"doc":return"application/msword";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xls":return"application/vnd.ms-excel";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"ppt":return"application/vnd.ms-powerpoint";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var ct,Pn=R(()=>{"use strict";B();me();ot();ct=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let o=n.file_path,r=n.content,a=n.edits;if(!o)throw new Error("Missing file_path argument");let l=Ae(o),u=Re(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let p=Date.now();return _.start("Write",n.description,l),r!=null?await this.executeSimpleWrite(l,r,p):await this.executeEditsMode(l,a,p)}async executeSimpleWrite(e,t,n){i.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),r=(await import("path")).dirname(e);await s.mkdir(r,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
|
|
65
65
|
`),l="";for(let f=0;f<Math.min(a.length,8);f++)l+=`+ ${a[f]}
|
|
66
66
|
`;a.length>8&&(l+=`+ ...
|
|
67
67
|
|
|
68
|
-
(${a.length-8} more lines)`);let u=l.trim();i.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let p=Date.now()-
|
|
69
|
-
`),d="";for(let g=0;g<Math.min(
|
|
70
|
-
`;return
|
|
68
|
+
(${a.length-8} more lines)`);let u=l.trim();i.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let p=Date.now()-n;return _.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:p}),[{type:"text",text:u}]}catch(s){i.debug(`[WriteFileTool] Failed to write file: ${s.message}`);let o=`Error writing file: ${s.message}`,r=Date.now()-n;return _.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:r}),[{type:"text",text:o}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");i.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let s=await import("fs/promises"),o=await import("path");for(let T=0;T<t.length;T++){let b=t[T];if(!b||typeof b!="object")throw new Error(`Edit operation ${T+1} must be an object with 'search' and 'replace' fields`);if(!b.hasOwnProperty("search")||typeof b.search!="string")throw new Error(`Edit operation ${T+1} missing required 'search' field (must be string)`);if(!b.hasOwnProperty("replace")||typeof b.replace!="string")throw new Error(`Edit operation ${T+1} missing required 'replace' field (must be string)`)}let r=t[0].search==="",a;if(r)if(i.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let T=o.dirname(e);await s.mkdir(T,{recursive:!0}),await s.writeFile(e,a,"utf-8");let b=a.split(`
|
|
69
|
+
`),d="";for(let g=0;g<Math.min(b.length,8);g++)d+=`+ ${b[g]}
|
|
70
|
+
`;return b.length>8&&(d+=`+ ...
|
|
71
71
|
|
|
72
|
-
(${
|
|
73
|
-
`),
|
|
74
|
-
`;return f.length>8&&(
|
|
72
|
+
(${b.length-8} more lines)`),i.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:d.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{i.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),i.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(T){throw T.code==="ENOENT"?new Error(`File does not exist at path: ${e}. Use empty search string to create new file.`):new Error(`Failed to read existing file: ${T.message}`)}}let l=0,u=a,p=[];for(let T=0;T<t.length;T++){let b=t[T];if(i.debug(`[WriteFileTool] Applying edit ${T+1}/${t.length}`),b.search==="")if(r){p.push({index:T+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{i.debug("[WriteFileTool] Rewriting entire existing file"),u=b.replace,p.push({index:T+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let d=u.indexOf(b.search);if(d!==-1)u=u.substring(0,d)+b.replace+u.substring(d+b.search.length),i.debug("[WriteFileTool] Replaced first occurrence"),p.push({index:T+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let g=`Search string not found: '${b.search}'`;return p.push({index:T+1,success:!1,message:g,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${T+1}: '${b.search}'\\n\\nEdit Summary:\\n- Total edits: ${p.length}\\n- Successful: ${p.filter(C=>C.success).length}\\n- Failed: ${p.filter(C=>!C.success).length}\\n\\nIndividual Edit Results:\\n`+p.map(C=>`${C.success?"✅":"❌"} Edit ${C.index}: ${C.message}`).join("\\n")}]}}await s.writeFile(e,u,"utf-8"),i.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let f=u.split(`
|
|
73
|
+
`),y="";for(let T=0;T<Math.min(f.length,8);T++)y+=`+ ${f[T]}
|
|
74
|
+
`;return f.length>8&&(y+=`+ ...
|
|
75
75
|
|
|
76
|
-
(${f.length-8} more lines)`),[{type:"text",text:
|
|
76
|
+
(${f.length-8} more lines)`),[{type:"text",text:y.trim()}]}catch(s){return i.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var lt,Dn=R(()=>{"use strict";B();me();ot();lt=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let o=n.file_path,r=n.old_string,a=n.new_string,l=n.replace_all===!0;if(!o)throw new Error("Missing file_path argument");if(r==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let u=Ae(o),p=Re(u);if(!p.valid)return[{type:"text",text:`Error: ${p.error}`}];i.debug(`[EditFileTool] Editing file: ${u}`);let f=Date.now();_.start("Edit",n.description,u);try{let y=await import("fs/promises"),T=await y.readFile(u,"utf-8"),b,d=0;if(l)for(b=T;b.includes(r);)b=b.replace(r,a),d++;else T.includes(r)?(b=T.replace(r,a),d=1):b=T;if(d===0){let k=`No matches found for the specified old_string in file: ${u}`,v=Date.now()-f;return _.result({toolName:"Edit",filePath:u,output:k,success:!1,executionTime:v}),[{type:"text",text:k}]}await y.writeFile(u,b,"utf-8");let g=`Successfully edited file: Replaced ${d} occurrence(s)`;i.debug(`[EditFileTool] ${g}`);let m=Date.now()-f,C=(await import("chalk")).default,S=`${C.red("- "+r.split(`
|
|
77
77
|
`).slice(0,5).join(`
|
|
78
78
|
- `))}
|
|
79
|
-
${
|
|
79
|
+
${C.green("+ "+a.split(`
|
|
80
80
|
`).slice(0,5).join(`
|
|
81
81
|
+ `))}
|
|
82
82
|
|
|
83
|
-
Replaced ${d} occurrence(s)`;return _.result({toolName:"Edit",filePath:u,output:
|
|
83
|
+
Replaced ${d} occurrence(s)`;return _.result({toolName:"Edit",filePath:u,output:S,success:!0,executionTime:m}),[{type:"text",text:g}]}catch(y){i.debug(`[EditFileTool] Failed to edit file: ${y.message}`);let T=`Error editing file: ${y.message}`,b=Date.now()-f;return _.result({toolName:"Edit",filePath:u,output:T,success:!1,executionTime:b}),[{type:"text",text:T}]}}}});var ut,An=R(()=>{"use strict";B();ut=class{toolNames=["upload_file"];async execute(e,t,n,s){let o=n.file_path;if(!o)throw new Error("Missing file_path argument");return i.debug(`[UploadFileTool] Upload file not implemented for CLI: ${o}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${o}`}]}}});import Ht from"fs/promises";import Xs from"path";import js from"form-data";import Vs from"axios";var dt,Nn=R(()=>{"use strict";B();me();se();dt=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();_.start("DeployZipHTML",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let A=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${A} seconds.`)}i.debug(`[DeployZipHTML] Deploying HTML project: ${o}`);try{await Ht.access(o)}catch{throw new Error(`ZIP file not found at path: ${o}`)}if(!o.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${o}`);let l=await Ht.stat(o),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let p=await Ht.readFile(o),f=Xs.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipHTML] File: ${f}, Size: ${l.size} bytes`);let T=await H.getInstance().getFirebaseIdToken();if(!T)throw new Error("User must be authenticated to deploy projects");let b=new js;b.append("zipFile",p,{filename:f,contentType:"application/zip"});let d="https://api.snowx.io/api/v2/deploy-zip";i.debug(`[DeployZipHTML] Uploading to ${d}`);let g=await Vs.post(d,b,{headers:{...b.getHeaders(),Authorization:`Bearer ${T}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(g.status!==200&&g.status!==201)throw new Error(`Deployment failed with status ${g.status}: ${JSON.stringify(g.data)}`);let m=g.data;i.debug("[DeployZipHTML] Deployed successfully"),i.debug(`[DeployZipHTML] Response: ${JSON.stringify(m,null,2)}`);let C=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,S=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,k=m.data?.siteId||m.siteId;this.deployCount++;let v=`# HTML Project Deployed Successfully!
|
|
84
84
|
|
|
85
|
-
**Deployment URL**: ${
|
|
85
|
+
**Deployment URL**: ${C}
|
|
86
86
|
|
|
87
87
|
**Project**: ${f}
|
|
88
88
|
**Type**: Static HTML
|
|
89
|
-
${
|
|
90
|
-
`:""}${
|
|
89
|
+
${S?`**Deploy ID**: ${S}
|
|
90
|
+
`:""}${k?`**Site ID**: ${k}
|
|
91
91
|
`:""}
|
|
92
92
|
Your site is now live and accessible!
|
|
93
93
|
|
|
94
|
-
${m.message||""}`,
|
|
94
|
+
${m.message||""}`,x=Date.now()-r;return _.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${C}`,success:!0,executionTime:x}),[{type:"text",text:v}]}catch(a){i.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let l=`HTML deployment failed
|
|
95
95
|
|
|
96
96
|
${a.message}
|
|
97
97
|
|
|
@@ -102,18 +102,18 @@ Troubleshooting:
|
|
|
102
102
|
4. Check network connectivity
|
|
103
103
|
5. Ensure ZIP file is under 100MB
|
|
104
104
|
|
|
105
|
-
If the issue persists, contact support.`,u=Date.now()-r;return _.result({toolName:"DeployZipHTML",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import
|
|
105
|
+
If the issue persists, contact support.`,u=Date.now()-r;return _.result({toolName:"DeployZipHTML",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import qt from"fs/promises";import Ks from"path";import Qs from"form-data";import Js from"axios";var pt,Rn=R(()=>{"use strict";B();me();se();pt=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();_.start("DeployZipReact",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let A=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${A} seconds.`)}i.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await qt.access(o)}catch{throw new Error(`ZIP file not found at path: ${o}`)}if(!o.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${o}`);let l=await qt.stat(o),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let p=await qt.readFile(o),f=Ks.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipReact] File: ${f}, Size: ${l.size} bytes`);let T=await H.getInstance().getFirebaseIdToken();if(!T)throw new Error("User must be authenticated to deploy projects");let b=new Qs;b.append("zipFile",p,{filename:f,contentType:"application/zip"});let d="https://api.snowx.io/api/v2/deploy-zip-react";i.debug(`[DeployZipReact] Uploading to ${d}`);let g=await Js.post(d,b,{headers:{...b.getHeaders(),Authorization:`Bearer ${T}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(g.status!==200&&g.status!==201)throw new Error(`Deployment failed with status ${g.status}: ${JSON.stringify(g.data)}`);let m=g.data;i.debug("[DeployZipReact] Deployed successfully"),i.debug(`[DeployZipReact] Response: ${JSON.stringify(m,null,2)}`);let C=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,S=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,k=m.data?.siteId||m.siteId;this.deployCount++;let v=`# React Project Deployed Successfully!
|
|
106
106
|
|
|
107
|
-
**Deployment URL**: ${
|
|
107
|
+
**Deployment URL**: ${C}
|
|
108
108
|
|
|
109
109
|
**Project**: ${f}
|
|
110
110
|
**Type**: React / SPA
|
|
111
|
-
${
|
|
112
|
-
`:""}${
|
|
111
|
+
${S?`**Deploy ID**: ${S}
|
|
112
|
+
`:""}${k?`**Site ID**: ${k}
|
|
113
113
|
`:""}
|
|
114
114
|
Your React app is now live and accessible!
|
|
115
115
|
|
|
116
|
-
${m.message||""}`,
|
|
116
|
+
${m.message||""}`,x=Date.now()-r;return _.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${C}`,success:!0,executionTime:x}),[{type:"text",text:v}]}catch(a){i.error(`[DeployZipReact] Deployment failed: ${a.message}`);let l=`React deployment failed
|
|
117
117
|
|
|
118
118
|
${a.message}
|
|
119
119
|
|
|
@@ -124,7 +124,9 @@ Troubleshooting:
|
|
|
124
124
|
4. Check network connectivity
|
|
125
125
|
5. Ensure ZIP file is under 100MB
|
|
126
126
|
|
|
127
|
-
If the issue persists, contact support.`,u=Date.now()-r;return _.result({toolName:"DeployZipReact",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var
|
|
127
|
+
If the issue persists, contact support.`,u=Date.now()-r;return _.result({toolName:"DeployZipReact",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Fn=R(()=>{"use strict"});function ze(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("'END'")||c.includes('"END"')))return ge.extended;let n=["python","python3","python2","node ","nodejs","ruby","perl","php","java ","kotlin","scala","Rscript","julia"];for(let l of n)if(e.includes(l))return ge.extended;let s=["pandas","numpy","scipy","matplotlib","import ","from ","require(","import(","DataFrame","Series"];for(let l of s)if(c.includes(l))return ge.extended;if(c.includes(`
|
|
128
|
+
`)&&c.split(`
|
|
129
|
+
`).length>2)return ge.extended;let o=new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","yes","printf"]),r=new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","basename","dirname","stat","file","du","df","free","uptime","ps"]),a=new Set(["make","cmake","npm","yarn","pip","cargo","mvn","gradle","docker","git","rsync","scp","ssh","curl","wget","find","locate","tar","zip","unzip","brew","apt","yum"]);return o.has(t)||r.has(t)&&c.length<100?ge.fast:a.has(t)?ge.extended:c.length<20?ge.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?ge.default:ge.extended:ge.default}var ge,Gt=R(()=>{"use strict";Fn();ge={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as Ys,exec as Zs}from"child_process";import{promisify as eo}from"util";function zt(){return process.platform}function Xe(){return process.platform==="win32"}function no(){return process.platform==="darwin"}function $n(c){let e=c.trim().toLowerCase();if(e.startsWith("sudo "))return{isPrivileged:!0,reason:"Direct sudo usage"};if(/(\||&&|;)\s*sudo\s+/.test(e))return{isPrivileged:!0,reason:"Sudo in command chain"};if(Xe()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let s=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(s)return{isPrivileged:!0,reason:`Privileged command: ${s.trim()}`};let r=[{pattern:/>\s*\/etc\//,desc:"Writing to /etc/"},{pattern:/>\s*\/usr\//,desc:"Writing to /usr/"},{pattern:/>\s*\/var\//,desc:"Writing to /var/"},{pattern:/>\s*\/opt\//,desc:"Writing to /opt/"},{pattern:/>\s*\/System\//,desc:"Writing to /System/ (macOS)"},{pattern:/tee\s+\/etc\//,desc:"Tee to /etc/"},{pattern:/tee\s+\/usr\//,desc:"Tee to /usr/"},{pattern:/tee\s+\/var\//,desc:"Tee to /var/"}].find(({pattern:a})=>a.test(e));return r?{isPrivileged:!0,reason:r.desc}:{isPrivileged:!1}}function On(){return Xe()?"PowerShell or Command Prompt":(no(),"Terminal")}function _n(c,e){let t=On();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
|
|
128
130
|
|
|
129
131
|
Reason: ${e}
|
|
130
132
|
|
|
@@ -138,16 +140,36 @@ To run this command:
|
|
|
138
140
|
2. Run the command manually: ${c}
|
|
139
141
|
3. Enter your password when prompted
|
|
140
142
|
|
|
141
|
-
Alternative: Break down the task into non-privileged commands if possible.`}
|
|
143
|
+
Alternative: Break down the task into non-privileged commands if possible.`}function Mn(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:u,reason:p}of n)if(e.startsWith(u)||e.includes(`&& ${u}`)||e.includes(`; ${u}`))return{isInteractive:!0,reason:p};let s=[{cmd:"npm init",except:["npm init -y","npm init --yes"],reason:"npm init requires interactive prompts (use npm init -y for non-interactive)"},{cmd:"yarn init",except:["yarn init -y","yarn init --yes"],reason:"yarn init requires interactive prompts (use yarn init -y for non-interactive)"},{cmd:"pnpm init",except:["pnpm init -y","pnpm init --yes"],reason:"pnpm init requires interactive prompts"}];for(let{cmd:u,except:p,reason:f}of s)if(e.startsWith(u)&&!p?.some(T=>e.startsWith(T)))return{isInteractive:!0,reason:f};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let u of a)if(e.startsWith(u))return{isInteractive:!0,reason:`${u} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let l=["git push","git pull","git fetch","git clone"];for(let u of l)e.startsWith(u);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function Un(c,e){let t=On();return`This command requires interactive input and cannot run in the Bash tool.
|
|
142
144
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
+
Reason: ${e}
|
|
146
|
+
|
|
147
|
+
The Bash tool runs in a non-interactive shell without a TTY, so:
|
|
148
|
+
- It cannot display interactive prompts
|
|
149
|
+
- It cannot receive keyboard input during execution
|
|
150
|
+
- Commands that wait for input will hang until timeout
|
|
151
|
+
|
|
152
|
+
To run this command:
|
|
153
|
+
1. Open ${t}
|
|
154
|
+
2. Run the command manually: ${c}
|
|
155
|
+
3. Follow the interactive prompts
|
|
156
|
+
|
|
157
|
+
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}var to,je,Xt=R(()=>{"use strict";Gt();to=eo(Zs);je=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,n,s,o="new",r){let a=r||ze(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Xe())await to(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let s=Date.now(),o=zt(),r,a;Xe()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=Ys(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Xe()}),u="",p="",f=!1,y=!1,T=!1,b=null,d=null,g=null,m=S=>{y||(y=!0,clearTimeout(C),d&&clearTimeout(d),g&&clearTimeout(g),n(S))},C=setTimeout(async()=>{y||(f=!0,l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),d=setTimeout(async()=>{y||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),this.cleanupStreams(l),setTimeout(()=>{if(!y){let S=Date.now()-s;m({output:u+p+`
|
|
158
|
+
|
|
159
|
+
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:S,platform:o})}},1e3))},1500))},t.maxTimeout);l.stdout?.on("data",S=>{u+=S.toString()}),l.stderr?.on("data",S=>{p+=S.toString()}),l.on("exit",(S,k)=>{T=!0,b=S,g=setTimeout(()=>{if(y)return;clearTimeout(C),d&&clearTimeout(d),this.cleanupStreams(l);let v=Date.now()-s,x=(u+p).trim(),A=3e4;if(x.length>A){let M=x.substring(0,A),q=M.split(`
|
|
160
|
+
`);x=M+`
|
|
161
|
+
|
|
162
|
+
[Output truncated at `+A+` characters]
|
|
163
|
+
[Showing first `+q.length+" lines of output]"}m(f?{output:x+`
|
|
145
164
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
[Total output was `+k+" characters]"}s(f?{output:m+`
|
|
165
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:v,platform:o}:{output:x,exitCode:S||0,isSuccess:(S||0)===0,duration:v,platform:o})},1500)}),l.on("close",S=>{if(y)return;g&&clearTimeout(g),clearTimeout(C),d&&clearTimeout(d);let k=Date.now()-s,v=(u+p).trim(),x=3e4;if(v.length>x){let A=v.substring(0,x),q=A.split(`
|
|
166
|
+
`).length,P=v.length;v=A+`
|
|
149
167
|
|
|
150
|
-
|
|
168
|
+
[Output truncated at `+x+` characters]
|
|
169
|
+
[Showing first `+q+` lines of output]
|
|
170
|
+
[Total output was `+P+" characters]"}m(f?{output:v+`
|
|
171
|
+
|
|
172
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:k,platform:o}:{output:v,exitCode:S||0,isSuccess:(S||0)===0,duration:k,platform:o})}),l.on("error",S=>{if(y)return;let k=Date.now()-s;m({output:"Process execution failed: "+S.message,exitCode:-1,isSuccess:!1,duration:k,platform:o})})})}formatExitCodeInfo(e){let t;switch(e){case 0:t="Success";break;case 1:t="General error";break;case 2:t="Misuse of shell command";break;case 126:t="Command cannot execute (permission denied)";break;case 127:t="Command not found";break;case 128:t="Invalid exit argument";break;case 130:t="Terminated by Ctrl+C (SIGINT)";break;case 137:t="Killed by SIGKILL";break;case 143:t="Terminated by SIGTERM";break;default:e>128?t=`Terminated by signal ${e-128}`:e<0?t="Terminated by timeout or force kill":t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}}});var jt={};ae(jt,{ToolCallingService:()=>Ve});import{EventEmitter as so}from"events";import Ln from"axios";import{exec as oo,spawn as Wn}from"child_process";import{promisify as io}from"util";import Y from"fs/promises";import ye from"fs";import Fe from"path";import ro from"os";var da,Ve,mt=R(()=>{"use strict";Xt();Gt();da=io(oo),Ve=class _ToolCallingService extends so{static instance;tools=new Map;executionHistory=[];maxResponseCharacters=87500;shellSessionManager=je.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;backgroundProcesses=new Map;backgroundProcessCounter=0;constructor(){super(),this.initializeDefaultTools()}static getInstance(){return _ToolCallingService.instance||(_ToolCallingService.instance=new _ToolCallingService),_ToolCallingService.instance}initializeDefaultTools(){this.registerTool({name:"web_search",description:"Search the web for information on a given topic",parameters:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 5)",default:5}},required:["query"]},handler:this.webSearch.bind(this),category:"web",enabled:!0}),this.registerTool({name:"read_file",description:"Read the contents of a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to read"}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: write or append",enum:["write","append"],default:"write"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"list_directory",description:"List the contents of a directory",parameters:{type:"object",properties:{directory_path:{type:"string",description:"Path to the directory to list"},include_hidden:{type:"boolean",description:"Include hidden files and directories",default:!1}},required:["directory_path"]},handler:this.listDirectory.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Bash",description:"Execute shell commands with support for background execution, timeouts, and output truncation",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},description:{type:"string",description:"Human-readable description of what the command does"},timeout:{type:"number",description:"Timeout in milliseconds (default: auto-detected based on command)"},run_in_background:{type:"boolean",description:"Run command in background and return immediately",default:!1}},required:["command"]},handler:this.bashCommand.bind(this),category:"system",enabled:!0}),this.registerTool({name:"execute_command",description:`Execute shell commands with persistent session support and interactive prompt handling. Supports both single-shot and persistent execution modes for multi-step workflows.
|
|
151
173
|
|
|
152
174
|
🔧 SESSION MODE SELECTION (REQUIRED):
|
|
153
175
|
• Use session: "existing" for workflows that need persistent state:
|
|
@@ -181,38 +203,38 @@ Alternative: Break down the task into non-privileged commands if possible.`}var
|
|
|
181
203
|
4. LLM receives prompt details and makes decision
|
|
182
204
|
5. LLM uses provide_input to send appropriate response
|
|
183
205
|
6. Command execution continues with provided input
|
|
184
|
-
7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content shows matching lines, files_with_matches shows file paths (default), count shows match counts",default:"files_with_matches"},case_insensitive:{type:"boolean",description:"Case insensitive search",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let s={};try{s=JSON.parse(c.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${t}': ${o}`)}let{ToolDisplay:n}=await Promise.resolve().then(()=>(me(),Cs));n.start(t,s.description,s.command||s.file_path);try{let o=this.tools.get(t);if(!o)throw new Error(`Tool '${t}' not found`);if(!o.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await o.handler(s),a=Date.now()-e,l=this.handleLargeResponse(r,t);return this.executionHistory.push({toolName:t,args:s,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),n.result({toolName:t,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(o){let r=Date.now()-e,a={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:t,error:o,executionTime:r}),n.error(t,o.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(c){return c.success?c.result?typeof c.result=="string"?c.result:typeof c.result=="object"&&"stdout"in c.result?c.result.stdout||c.result.stderr||"":typeof c.result=="object"&&"content"in c.result?c.result.content||"":JSON.stringify(c.result,null,2):"":c.error||"Unknown error"}async captureFrontendToolResult(c,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ye(),$e)),s=t.getInstance(),n=this.extractOutputForDisplay(e);s.captureFrontendToolResult(c,n,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,s=(await Os.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,n=[];if(s.AbstractText&&n.push({title:s.Heading||"Instant Answer",content:s.AbstractText,url:s.AbstractURL||"",type:"instant_answer"}),s.RelatedTopics&&s.RelatedTopics.length>0)for(let o of s.RelatedTopics.slice(0,c.num_results||5))o.Text&&n.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:n,total_results:n.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await Y.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:s="write"}=c;if(e.endsWith(".ipynb")&&ve.existsSync(e)){let o=await Y.readFile(e,"utf-8"),r=JSON.parse(o);if(r.cells.length>0&&r.cells[0].id){let a=r.cells.findIndex(l=>l.id===r.cells[0].id);if(a!==-1)return r.cells[a].source=t,await Y.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}ve.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let n=Fe.dirname(e);return await Y.mkdir(n,{recursive:!0}),s==="append"?await Y.appendFile(e,t):await Y.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:s}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await Y.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let n=await Y.stat(Fe.join(c.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:n.size,modified:n.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=je.parseSessionMode(c.session),t=ze(c.command),s={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},n=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,s);return{success:n.isSuccess,result:{command:c.command,stdout:n.output,stderr:"",exit_code:n.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await Os({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:s=!1}=c;if(s){this.backgroundProcessCounter++;let r=`bg-${this.backgroundProcessCounter}`,a=_s("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),l={process:a,command:e,startTime:new Date,stdout:"",stderr:""};a.stdout.on("data",p=>{let f=p.toString();if(f){let v=this.backgroundProcesses.get(r);v&&(v.stdout+=f,this.backgroundProcesses.set(r,v))}}),a.stderr.on("data",p=>{let f=p.toString();if(f){let v=this.backgroundProcesses.get(r);v&&(v.stderr+=f,this.backgroundProcesses.set(r,v))}}),a.on("close",p=>{let f=this.backgroundProcesses.get(r);f&&(f.exitCode=p||0,this.backgroundProcesses.set(r,f))}),this.backgroundProcesses.set(r,l);let u=`Command started in background with ID: ${r}
|
|
206
|
+
7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content shows matching lines, files_with_matches shows file paths (default), count shows match counts",default:"files_with_matches"},case_insensitive:{type:"boolean",description:"Case insensitive search",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let n={};try{n=JSON.parse(c.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${t}': ${o}`)}let{ToolDisplay:s}=await Promise.resolve().then(()=>(me(),xn));s.start(t,n.description,n.command||n.file_path);try{let o=this.tools.get(t);if(!o)throw new Error(`Tool '${t}' not found`);if(!o.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await o.handler(n),a=Date.now()-e,l=this.handleLargeResponse(r,t);return this.executionHistory.push({toolName:t,args:n,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),s.result({toolName:t,command:n.command,filePath:n.file_path,description:n.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(o){let r=Date.now()-e,a={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:t,error:o,executionTime:r}),s.error(t,o.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(c){return c.success?c.result?typeof c.result=="string"?c.result:typeof c.result=="object"&&"stdout"in c.result?c.result.stdout||c.result.stderr||"":typeof c.result=="object"&&"content"in c.result?c.result.content||"":JSON.stringify(c.result,null,2):"":c.error||"Unknown error"}async captureFrontendToolResult(c,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(be(),$e)),n=t.getInstance(),s=this.extractOutputForDisplay(e);n.captureFrontendToolResult(c,s,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,n=(await Ln.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,s=[];if(n.AbstractText&&s.push({title:n.Heading||"Instant Answer",content:n.AbstractText,url:n.AbstractURL||"",type:"instant_answer"}),n.RelatedTopics&&n.RelatedTopics.length>0)for(let o of n.RelatedTopics.slice(0,c.num_results||5))o.Text&&s.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:s,total_results:s.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await Y.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:n="write"}=c;if(e.endsWith(".ipynb")&&ye.existsSync(e)){let o=await Y.readFile(e,"utf-8"),r=JSON.parse(o);if(r.cells.length>0&&r.cells[0].id){let a=r.cells.findIndex(l=>l.id===r.cells[0].id);if(a!==-1)return r.cells[a].source=t,await Y.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}ye.existsSync(e)&&n!=="append"&&await this.validateFileNotModified(e);let s=Fe.dirname(e);return await Y.mkdir(s,{recursive:!0}),n==="append"?await Y.appendFile(e,t):await Y.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:n}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await Y.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let n of e){if(!c.include_hidden&&n.name.startsWith("."))continue;let s=await Y.stat(Fe.join(c.directory_path,n.name));t.push({name:n.name,type:n.isDirectory()?"directory":"file",size:s.size,modified:s.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=je.parseSessionMode(c.session),t=ze(c.command),n={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},s=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,n);return{success:s.isSuccess,result:{command:c.command,stdout:s.output,stderr:"",exit_code:s.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await Ln({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:n=!1}=c;if(n){this.backgroundProcessCounter++;let r=`bg-${this.backgroundProcessCounter}`,a=Wn("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),l={process:a,command:e,startTime:new Date,stdout:"",stderr:""};a.stdout.on("data",p=>{let f=p.toString();if(f){let y=this.backgroundProcesses.get(r);y&&(y.stdout+=f,this.backgroundProcesses.set(r,y))}}),a.stderr.on("data",p=>{let f=p.toString();if(f){let y=this.backgroundProcesses.get(r);y&&(y.stderr+=f,this.backgroundProcesses.set(r,y))}}),a.on("close",p=>{let f=this.backgroundProcesses.get(r);f&&(f.exitCode=p||0,this.backgroundProcesses.set(r,f))}),this.backgroundProcesses.set(r,l);let u=`Command started in background with ID: ${r}
|
|
185
207
|
PID: ${a.pid}
|
|
186
208
|
Command: ${e}
|
|
187
209
|
|
|
188
210
|
Note: The process will continue running in the background.
|
|
189
|
-
Output will be collected automatically.`;return{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let
|
|
190
|
-
`).filter(
|
|
211
|
+
Output will be collected automatically.`;return{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let s=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:ze(e),o=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",s);return{success:o.isSuccess,result:{command:e,stdout:o.output,stderr:"",exit_code:o.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(c){try{let{file_path:e,old_string:t,new_string:n,replace_all:s=!1}=c;if(t===n)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&ye.existsSync(e)){let a=await Y.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let p=l.cells[u],f=Array.isArray(p.source)?p.source.join(""):p.source;if(f.includes(t)){let y=s?f.replaceAll(t,n):f.replace(t,n);return l.cells[u].source=y,await Y.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:s?f.split(t).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(e);let o=await Y.readFile(e,"utf-8");if(!o.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let r=s?o.replaceAll(t,n):o.replace(t,n);if(r===o)throw new Error("Edit failed: File content unchanged after replacement");return await Y.writeFile(e,r,"utf-8"),this.cacheFileState(e,r),{success:!0,result:{file_path:e,replacements:s?o.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(c){try{let{pattern:e,path:t=process.cwd(),glob:n,output_mode:s="files_with_matches",case_insensitive:o=!1}=c,r=[];return o&&r.push("-i"),s==="files_with_matches"?r.push("-l"):s==="count"&&r.push("-c"),n&&r.push("--glob",n),r.push(e,t),new Promise(a=>{let l=Wn("rg",r,{stdio:["ignore","pipe","pipe"]}),u="",p="";l.stdout.on("data",f=>{u+=f.toString()}),l.stderr.on("data",f=>{p+=f.toString()}),l.on("close",f=>{if(f!==0&&f!==1){a({success:!1,error:`ripgrep failed: ${p||"Unknown error"}`});return}let y=u.trim().split(`
|
|
212
|
+
`).filter(b=>b),T=y.length;a({success:!0,result:{pattern:e,num_files:T,files:y,output:u.trim()}})}),l.on("error",f=>{a({success:!1,error:`Failed to execute ripgrep: ${f.message}. Make sure ripgrep is installed.`})})})}catch(e){return{success:!1,error:`Grep failed: ${e.message}`}}}async globFiles(c){try{let{pattern:e,path:t=process.cwd()}=c,s=(a=>{let l=a;return l=l.replace(/[.+^${}()|[\]\\]/g,"\\$&"),l=l.replace(/\*\*/g,"<DOUBLESTAR>"),l=l.replace(/\*/g,"[^/]*"),l=l.replace(/<DOUBLESTAR>/g,".*"),l=l.replace(/\?/g,"."),new RegExp(`^${l}$`)})(e),o=[],r=async a=>{try{let l=await Y.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let p=Fe.join(a,u.name),f=Fe.relative(t,p);u.isDirectory()?await r(p):(s.test(f)||s.test(u.name))&&o.push(p)}}catch{}};return await r(t),{success:!0,result:{pattern:e,num_files:o.length,files:o}}}catch(e){return{success:!1,error:`Glob failed: ${e.message}`}}}async editNotebook(c){try{let{notebook_path:e,cell_id:t,new_source:n,cell_type:s="code",edit_mode:o="replace"}=c;if(!ye.existsSync(e))throw new Error(`Notebook file does not exist: ${e}`);if(!e.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let r=await Y.readFile(e,"utf-8"),a=JSON.parse(r);switch(o){case"replace":{if(!t)throw new Error("cell_id is required for replace mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells[l].source=n;break}case"insert":{if(!s)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:s,source:n,metadata:{},execution_count:s==="code"?null:void 0,outputs:s==="code"?[]:void 0};if(t){let u=a.cells.findIndex(p=>p.id===t);a.cells.splice(u+1,0,l)}else a.cells.unshift(l);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${o}`)}return await Y.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:o,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=ye.statSync(c);this.fileStateCache.set(c,{content:e,modificationDate:t.mtime,filePath:c})}catch{}}async validateFileNotModified(c){let e=this.fileStateCache.get(c);if(!e){if(ye.existsSync(c)){let n=await Y.readFile(c,"utf-8");this.cacheFileState(c,n)}return}if(ye.statSync(c).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let c=[];for(let[e,t]of this.tools.entries())t.enabled&&c.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return c}getToolsByCategory(c){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===c)}enableTool(c){let e=this.tools.get(c);return e?(e.enabled=!0,!0):!1}disableTool(c){let e=this.tools.get(c);return e?(e.enabled=!1,!0):!1}getExecutionHistory(c=10){return this.executionHistory.slice(-c)}getExecutionStats(){let c=this.executionHistory.length,e=this.executionHistory.filter(r=>r.result.success).length,t=c-e,n=c>0?this.executionHistory.reduce((r,a)=>r+a.executionTime,0)/c:0,s=new Map;this.executionHistory.forEach(r=>{s.set(r.toolName,(s.get(r.toolName)||0)+1)});let o=s.size>0?Array.from(s.entries()).reduce((r,a)=>a[1]>r[1]?a:r)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(n),mostUsed:o}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){}handleLargeResponse(c,e){if(!c.success||!c.result)return c;let t=typeof c.result=="string"?c.result:JSON.stringify(c.result);if(t.length>this.maxResponseCharacters){let n=this.createTempFile(t,e);return n?{success:!0,result:this.generatePreview(t,n)}:{success:!0,result:this.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=ro.tmpdir(),n=Fe.join(t,"orion_tool_responses");ye.existsSync(n)||ye.mkdirSync(n,{recursive:!0});let s=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),r=`${e}_${s}_${o}.txt`,a=Fe.join(n,r);return ye.writeFileSync(a,c,"utf8"),a}catch{return null}}generatePreview(c,e){let t=c.substring(0,1e4),n=`📄 Response too large (${c.length} characters > 87,500 limit), saved to temporary file.
|
|
191
213
|
|
|
192
|
-
`;return
|
|
193
|
-
`,
|
|
214
|
+
`;return n+=`📁 TEMP FILE PATH: ${e}
|
|
215
|
+
`,n+=`🔍 Use read_file, grep, cat, or other tools to access the full content.
|
|
194
216
|
|
|
195
|
-
`,
|
|
196
|
-
`,
|
|
197
|
-
`,
|
|
198
|
-
${"─".repeat(50)}`,
|
|
199
|
-
... (${c.length-1e4} more characters available in temp file)`),
|
|
217
|
+
`,n+=`📝 PREVIEW (first 10,000 characters):
|
|
218
|
+
`,n+=`${"─".repeat(50)}
|
|
219
|
+
`,n+=t,c.length>1e4&&(n+=`
|
|
220
|
+
${"─".repeat(50)}`,n+=`
|
|
221
|
+
... (${c.length-1e4} more characters available in temp file)`),n+=`
|
|
200
222
|
|
|
201
|
-
💡 To read full content: use tools like 'read_file' with path above`,
|
|
223
|
+
💡 To read full content: use tools like 'read_file' with path above`,n}truncateOutput(c){return c.length<=this.maxResponseCharacters?c:c.substring(0,this.maxResponseCharacters)+`
|
|
202
224
|
|
|
203
|
-
... (truncated due to size limit)`}stopAllRunningTools(){}}});var gt,
|
|
204
|
-
`,
|
|
225
|
+
... (truncated due to size limit)`}stopAllRunningTools(){}}});var gt,Bn=R(()=>{"use strict";B();Xt();gt=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let o=n.command;if(o==null)throw new Error("Missing command argument");if(typeof o!="string")throw new Error(`Command must be a string. Received: ${typeof o}`);if(o.trim().length===0)throw new Error("Command cannot be empty");let r=n.session;if(r==null)r="new";else{if(typeof r!="string")throw new Error(`Session must be a string. Received: ${typeof r}`);r=r.toLowerCase()}if(r!=="new"&&r!=="existing")throw new Error(`Invalid session mode '${r}' - must be 'new' or 'existing'`);let a;if(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let b=Number(n.timeout);if(Number.isNaN(b))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=b}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let l=n.description;l!=null&&typeof l!="string"&&i.debug(`[RunCommandTool] Invalid description type: ${typeof l}, ignoring`);let u=n.run_in_background;if(u!=null){if(typeof u!="boolean")throw new Error(`run_in_background must be a boolean. Received: ${typeof u}`);u===!0&&i.debug("[RunCommandTool] run_in_background=true requested but not yet implemented, running in foreground")}let p=$n(o);if(p.isPrivileged)return i.debug(`[RunCommandTool] Blocked privileged command: ${p.reason}`),[{type:"text",text:`Error: ${_n(o,p.reason||"Privileged command detected")}`}];let f=Mn(o);if(f.isInteractive)return i.debug(`[RunCommandTool] Blocked interactive command: ${f.reason}`),[{type:"text",text:`Error: ${Un(o,f.reason||"Interactive command detected")}`}];let y=a||12e4,T=zt();i.debug(`[RunCommandTool] Executing command on platform: ${T}`),i.debug(`[RunCommandTool] Command: ${o.substring(0,50)}${o.length>50?"...":""}`),l&&i.debug(`[RunCommandTool] Description: ${l}`),i.debug(`[RunCommandTool] Session: ${r}, Timeout: ${y}ms, Background: ${u||!1}`);try{let b=(await Promise.resolve().then(()=>(mt(),jt))).ToolCallingService.getInstance(),d={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:r,timeout:y})}},g=await b.executeTool(d),m="";if(g.success){let C=(g.result?.stdout||"").trim(),S=g.result?.exitCode??0;if(m=`Command: ${o}
|
|
226
|
+
`,m+=`Exit Code: ${S}
|
|
205
227
|
|
|
206
|
-
`,
|
|
207
|
-
`),
|
|
208
|
-
`),
|
|
228
|
+
`,C.length>0){let k=C.split(`
|
|
229
|
+
`),v=k.slice(0,15);m+=v.join(`
|
|
230
|
+
`),k.length>15&&(m+=`
|
|
209
231
|
|
|
210
|
-
... (showing first 15 of ${
|
|
211
|
-
`,
|
|
232
|
+
... (showing first 15 of ${k.length} lines)`)}else m+="(no output)";return[{type:"text",text:m}]}else{let C=g.error||"Unknown error",S=g.result?.exitCode??1;return m=`Command: ${o}
|
|
233
|
+
`,m+=`Exit Code: ${S}
|
|
212
234
|
|
|
213
|
-
`,
|
|
214
|
-
${
|
|
215
|
-
Error: ${b.message}`}]}}ensureMeaningfulOutput(e,t,
|
|
235
|
+
`,m+=`Error:
|
|
236
|
+
${C}`,[{type:"text",text:m}]}}catch(b){return i.debug(`[RunCommandTool] Failed to execute bash command: ${b.message}`),[{type:"text",text:`Command: ${o}
|
|
237
|
+
Error: ${b.message}`}]}}ensureMeaningfulOutput(e,t,n){let s=(e||"").trim();return s.length===0?n?`✅ Command '${t}' executed successfully.
|
|
216
238
|
|
|
217
239
|
ℹ️ No output was produced, which may be expected for this operation. This typically means:
|
|
218
240
|
• The command completed without errors
|
|
@@ -229,15 +251,15 @@ If you expected output, the command may need different parameters or the operati
|
|
|
229
251
|
Consider:
|
|
230
252
|
• Checking the command syntax and parameters
|
|
231
253
|
• Verifying file permissions and paths
|
|
232
|
-
• Running the command with verbose flags for more details`:
|
|
254
|
+
• Running the command with verbose flags for more details`:s}}});var ht,Hn=R(()=>{"use strict";B();ht=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let o=n.pattern,r=n.output_mode||"files_with_matches",a=n.path||process.cwd(),l=n.glob,u=n.type,p=n["-i"]===!0,f=n["-n"]===!0,y=n["-A"],T=n["-B"],b=n["-C"],d=n.multiline===!0,g=n.head_limit;if(!o)throw new Error("Missing pattern argument");if(o.trim().length===0)throw new Error("Pattern cannot be empty");i.debug(`[GrepTool] Grep search: pattern="${o}", path="${a}", output_mode="${r}"`);try{let{exec:m}=await import("child_process"),{promisify:C}=await import("util"),S=C(m),k="rg",v=!0;try{await S("which rg")}catch{i.debug("[GrepTool] ripgrep not found, falling back to grep"),k="grep -r",v=!1}if(v){switch(p&&(k+=" -i"),f&&(k+=" -n"),r){case"files_with_matches":k+=" -l";break;case"count":k+=" -c";break;case"content":default:break}b!==void 0?k+=` -C ${b}`:(y!==void 0&&(k+=` -A ${y}`),T!==void 0&&(k+=` -B ${T}`)),d&&(k+=" -U --multiline-dotall"),k+=` "${o.replace(/"/g,'\\"')}"`,l&&(k+=` --glob="${l}"`),u&&(k+=` --type=${u}`),k+=` "${a}"`}else{switch(p&&(k+=" -i"),f&&(k+=" -n"),r){case"files_with_matches":k+=" -l";break;case"count":k+=" -c";break}b!==void 0?k+=` -C ${b}`:(y!==void 0&&(k+=` -A ${y}`),T!==void 0&&(k+=` -B ${T}`)),k+=` "${o.replace(/"/g,'\\"')}"`,l&&(k+=` --include="${l}"`),k+=` "${a}"`}g!==void 0&&g>0&&(k+=` | head -n ${g}`),i.debug(`[GrepTool] Executing: ${k}`);let{stdout:x,stderr:A}=await S(k,{maxBuffer:10*1024*1024});if(!x&&!A)return[{type:"text",text:"No matches found"}];let M=x||A;if(r==="content"&&M){let P=`
|
|
233
255
|
|
|
234
|
-
[Found ${
|
|
235
|
-
`).length} matching line(s)]`;return[{type:"text",text:
|
|
236
|
-
`);return[{type:"text",text:`Found ${
|
|
237
|
-
${
|
|
238
|
-
`)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var vt,
|
|
256
|
+
[Found ${M.trim().split(`
|
|
257
|
+
`).length} matching line(s)]`;return[{type:"text",text:M+P}]}return[{type:"text",text:M}]}catch(m){return m.code===1?[{type:"text",text:"No matches found"}]:(i.debug(`[GrepTool] Grep failed: ${m.message}`),m.message.includes("No such file or directory")?[{type:"text",text:`Error: Search path does not exist: ${a}`}]:[{type:"text",text:"Grep search completed with no results"}])}}}});var ft,qn=R(()=>{"use strict";B();ft=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let o=n.pattern,r=n.path||process.cwd();if(!o)throw new Error("Missing pattern argument");i.debug(`[GlobTool] Glob search: pattern="${o}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),p=o.replace(/\*\*/g,"*"),f=process.platform==="win32"?`dir /s /b "${r}\\${p}"`:`find "${r}" -name "${p}" 2>/dev/null`,{stdout:y}=await u(f);if(!y||y.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let T=y.trim().split(`
|
|
258
|
+
`);return[{type:"text",text:`Found ${T.length} file(s):
|
|
259
|
+
${T.join(`
|
|
260
|
+
`)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var vt,Gn=R(()=>{"use strict";B();vt=class{toolNames=["open_url"];async execute(e,t,n,s){let o=n.url;if(!o)throw new Error("Missing url argument");i.debug(`[OpenUrlTool] Opening URL: ${o}`),s.activeWebViewURLs.includes(o)||(s.activeWebViewURLs.push(o),i.debug(`[OpenUrlTool] Added to active URLs: ${o}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${o}"`,l=>{l?i.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):i.debug(`[OpenUrlTool] URL opened in default browser: ${o}`)}),[{type:"text",text:`✅ URL opened in default browser: ${o}`}]}catch(r){return i.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});import{exec as ao,execSync as Sa}from"child_process";import{promisify as co}from"util";function Oe(){return process.platform==="win32"}function yt(){return process.platform==="darwin"}function bt(){return process.platform==="linux"}function Vt(){return Oe()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var xa,zn=R(()=>{"use strict";xa=co(ao)});import*as U from"fs";import*as Q from"path";import*as W from"os";import{exec as Xn}from"child_process";import{promisify as lo}from"util";var wt,Kt,oe,jn=R(()=>{"use strict";zn();wt=lo(Xn),Kt=class c{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return c.instance||(c.instance=new c),c.instance}get orionDirectory(){return Q.join(W.homedir(),".orion")}getKnowledgeFilePath(){return Q.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!U.existsSync(this.orionDirectory))try{U.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Oe()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{Xn(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return U.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return U.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),U.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
|
|
239
261
|
|
|
240
|
-
`+e;return this.writeDeviceKnowledge(
|
|
262
|
+
`+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return U.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
|
|
241
263
|
|
|
242
264
|
`;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
|
|
243
265
|
|
|
@@ -255,11 +277,11 @@ ${b.join(`
|
|
|
255
277
|
`,e+=`- **Default Shell**: ${t}
|
|
256
278
|
`,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
|
|
257
279
|
`),e+=`
|
|
258
|
-
`;let
|
|
259
|
-
`,e+=
|
|
280
|
+
`;let n=[{command:"python3 --version",name:"Python 3"},{command:"python --version",name:"Python"},{command:"node --version",name:"Node.js"},{command:"npm --version",name:"npm"},{command:"pnpm --version",name:"pnpm"},{command:"yarn --version",name:"Yarn"},{command:"brew --version",name:"Homebrew"},{command:"git --version",name:"Git"},{command:"docker --version",name:"Docker"},{command:"java -version",name:"Java"},{command:"ruby --version",name:"Ruby"},{command:"php --version",name:"PHP"},{command:"go version",name:"Go"},{command:"rustc --version",name:"Rust"},{command:"cargo --version",name:"Cargo"},{command:"apt --version",name:"APT"},{command:"snap --version",name:"Snap"},{command:"flatpak --version",name:"Flatpak"},{command:"dnf --version",name:"DNF"},{command:"yum --version",name:"YUM"},{command:"pacman --version",name:"Pacman"},{command:"kubectl version --client",name:"kubectl"},{command:"podman --version",name:"Podman"},{command:"vagrant --version",name:"Vagrant"}],s=[];for(let u of n){let p=await this.getCommandVersion(u.command);p&&s.push(`- **${u.name}**: ${p}`)}s.length>0&&(e+=`## Development Tools
|
|
281
|
+
`,e+=s.join(`
|
|
260
282
|
`),e+=`
|
|
261
283
|
|
|
262
|
-
`);let o=[];if(yt()){let u=["/Applications/Xcode.app","/Applications/Visual Studio Code.app","/Applications/Sublime Text.app","/Applications/Atom.app","/Applications/IntelliJ IDEA.app","/Applications/PyCharm.app","/Applications/Android Studio.app","/Applications/Docker.app","/Applications/Postman.app","/Applications/Terminal.app","/Applications/iTerm.app"];for(let p of u)if(
|
|
284
|
+
`);let o=[];if(yt()){let u=["/Applications/Xcode.app","/Applications/Visual Studio Code.app","/Applications/Sublime Text.app","/Applications/Atom.app","/Applications/IntelliJ IDEA.app","/Applications/PyCharm.app","/Applications/Android Studio.app","/Applications/Docker.app","/Applications/Postman.app","/Applications/Terminal.app","/Applications/iTerm.app"];for(let p of u)if(U.existsSync(p)){let f=Q.basename(p,".app");o.push(`- ${f}`)}}else if(Oe()){let u=["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe","C:\\Program Files\\Microsoft VS Code\\Code.exe","C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe",Q.join(process.env.LOCALAPPDATA||"","Programs\\Microsoft VS Code\\Code.exe"),"C:\\Program Files\\Sublime Text\\sublime_text.exe","C:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition","C:\\Program Files\\JetBrains\\PyCharm Community Edition","C:\\Program Files\\Android\\Android Studio","C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe","C:\\Program Files\\Postman\\Postman.exe",Q.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let p of u)if(U.existsSync(p)){let f=Q.basename(p).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");o.push(`- ${f}`)}}else if(bt()){let u=[{path:"/snap/bin/code",name:"VS Code (snap)"},{path:"/snap/bin/sublime-text",name:"Sublime Text (snap)"},{path:"/snap/bin/postman",name:"Postman (snap)"},{path:"/snap/bin/intellij-idea-community",name:"IntelliJ IDEA (snap)"},{path:"/snap/bin/pycharm-community",name:"PyCharm (snap)"},{path:"/usr/bin/code",name:"VS Code"},{path:"/usr/share/code/code",name:"VS Code"},{path:"/opt/visual-studio-code/code",name:"VS Code"},{path:"/usr/bin/sublime_text",name:"Sublime Text"},{path:"/opt/sublime_text/sublime_text",name:"Sublime Text"},{path:"/usr/bin/docker",name:"Docker"},{path:"/usr/bin/vim",name:"Vim"},{path:"/usr/bin/nvim",name:"Neovim"},{path:"/usr/bin/emacs",name:"Emacs"},{path:"/usr/bin/nano",name:"Nano"},{path:Q.join(W.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let y of u)U.existsSync(y.path)&&o.push(`- ${y.name}`);let p=["/usr/share/applications",Q.join(W.homedir(),".local/share/applications")],f=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let y of p)if(U.existsSync(y))try{let T=U.readdirSync(y);for(let b of T){let d=b.toLowerCase();for(let g of f)d.includes(g)&&!o.some(m=>m.toLowerCase().includes(g))&&o.push(`- ${b.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
|
|
263
285
|
`,e+=o.join(`
|
|
264
286
|
`),e+=`
|
|
265
287
|
|
|
@@ -279,8 +301,8 @@ ${b.join(`
|
|
|
279
301
|
`,e+=`- **/opt**: /opt
|
|
280
302
|
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||Q.join(W.homedir(),".config")}
|
|
281
303
|
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||Q.join(W.homedir(),".local/share")}
|
|
282
|
-
`,
|
|
283
|
-
`),
|
|
304
|
+
`,U.existsSync("/snap")&&(e+=`- **Snap**: /snap
|
|
305
|
+
`),U.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
|
|
284
306
|
`)),e+=`
|
|
285
307
|
`,e+=`## Network
|
|
286
308
|
`,e+=`- **Hostname**: ${W.hostname()}
|
|
@@ -292,28 +314,28 @@ ${b.join(`
|
|
|
292
314
|
`,e+=`- **Redirect URLs**: Any shortened URL should be resolved to get the actual destination URL.
|
|
293
315
|
`,e+=`- **File Downloads**: Always follow redirects to ensure proper file access and downloads.
|
|
294
316
|
|
|
295
|
-
`,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let
|
|
296
|
-
`),o=[],r=!1,a=!1;for(let u of
|
|
297
|
-
`);return this.writeDeviceKnowledge(l)}addNote(e,t,
|
|
298
|
-
${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${
|
|
299
|
-
`),l=[],u=!1,p=!1;for(let
|
|
300
|
-
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(
|
|
301
|
-
`):null}async getCommandVersion(e){try{let t=Vt(),{stdout:
|
|
302
|
-
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let
|
|
317
|
+
`,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let s=(this.readDeviceKnowledge()||"").split(`
|
|
318
|
+
`),o=[],r=!1,a=!1;for(let u of s)u.startsWith(`## ${e}`)?(r=!0,a=!0,o.push(u),o.push(t)):u.startsWith("## ")&&r?(r=!1,o.push(u)):r||o.push(u);a||(o.push(""),o.push(`## ${e}`),o.push(t));let l=o.join(`
|
|
319
|
+
`);return this.writeDeviceKnowledge(l)}addNote(e,t,n="Notes"){let s=new Date().toLocaleString(),o=`### ${e} (${s})
|
|
320
|
+
${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${n}`)){let a=r.split(`
|
|
321
|
+
`),l=[],u=!1,p=!1;for(let y of a)y.startsWith(`## ${n}`)?(u=!0,l.push(y)):y.startsWith("## ")&&u&&!p?(l.push(""),l.push(o),l.push(""),l.push(y),u=!1,p=!0):l.push(y);u&&!p&&(l.push(""),l.push(o));let f=l.join(`
|
|
322
|
+
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(n,o)}deleteDeviceKnowledge(){try{return U.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return U.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=U.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(bt()){try{let{stdout:n}=await wt("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),s=n.trim();s&&s!=="none"&&e.push(`- **Virtualization**: ${s}`)}catch{}if(U.existsSync("/proc/cpuinfo"))try{U.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(s=>s.includes("Virtualization"))||e.push("- **Virtualization**: VM detected (hypervisor flag)"))}catch{}let t=["/sys/class/dmi/id/product_name","/sys/class/dmi/id/sys_vendor","/sys/class/dmi/id/board_vendor"];for(let n of t)if(U.existsSync(n))try{let s=U.readFileSync(n,"utf8").trim().toLowerCase();if(s.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(s.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(s.includes("kvm")||s.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(s.includes("hyper-v")||s.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(s.includes("xen")){e.push("- **VM Type**: Xen");break}else if(s.includes("amazon")||s.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(s.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(s.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(U.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),U.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),U.existsSync("/proc/version"))try{let n=U.readFileSync("/proc/version","utf8");(n.toLowerCase().includes("microsoft")||n.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(U.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),U.existsSync("/etc/os-release"))try{let s=U.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);s&&e.push(`- **Distribution**: ${s[1]}`)}catch{}}else if(yt())try{let{stdout:t}=await wt('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(Oe())try{let{stdout:t}=await wt('systeminfo | findstr /i "System Model"',{timeout:5e3}),n=t.toLowerCase();(n.includes("virtual")||n.includes("vmware")||n.includes("virtualbox"))&&e.push(`- **Environment**: ${t.split(":")[1]?.trim()||"Virtual Machine"}`)}catch{}(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)&&e.push("- **Access**: SSH Session"),process.env.TMUX&&e.push("- **Terminal Multiplexer**: tmux"),process.env.STY&&e.push("- **Terminal Multiplexer**: screen")}catch{}return e.length>0?e.join(`
|
|
323
|
+
`):null}async getCommandVersion(e){try{let t=Vt(),{stdout:n,stderr:s}=await wt(e,{timeout:5e3,shell:t,windowsHide:!0});return(n+s).trim().split(`
|
|
324
|
+
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}},oe=Kt.shared()});var Tt,Vn=R(()=>{"use strict";B();me();jn();Tt=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let o=n.action,r=Date.now();i.debug(`[ManageDeviceKnowledgeTool] Executing action: ${o}`),_.start("ManageDeviceKnowledge",o);try{let a,l=!0;switch(o){case"read":{let p=oe.readDeviceKnowledge();p?a=p:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await oe.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${oe.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let p=n.content;p?oe.writeDeviceKnowledge(p)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",l=!1):(a='Error: Missing "content" argument for write action.',l=!1);break}case"append":{let p=n.content;p?oe.appendDeviceKnowledge(p)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",l=!1):(a='Error: Missing "content" argument for append action.',l=!1);break}case"update_section":{let p=n.section,f=n.content;!p||!f?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):oe.updateKnowledgeSection(p,f)?a=`Section "${p}" updated successfully.`:(a=`Failed to update section "${p}".`,l=!1);break}case"add_note":{let p=n.title,f=n.content,y=n.category||"Notes";!p||!f?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):oe.addNote(p,f,y)?a=`Note "${p}" added to ${y} successfully.`:(a=`Failed to add note "${p}".`,l=!1);break}case"delete":{oe.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=oe.getKnowledgeFilePath();break}case"exists":{a=oe.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${oe.getKnowledgeFileSize()} bytes`;break}case"export":{let p=n.destination;p?oe.exportDeviceKnowledge(p)?a=`Device knowledge exported to: ${p}`:(a=`Failed to export device knowledge to: ${p}`,l=!1):(a='Error: Missing "destination" argument for export action.',l=!1);break}case"import":{let p=n.source;p?oe.importDeviceKnowledge(p)?a=`Device knowledge imported from: ${p}`:(a=`Failed to import device knowledge from: ${p}`,l=!1):(a='Error: Missing "source" argument for import action.',l=!1);break}default:a=`Unknown action: ${o}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-r;return _.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){i.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-r;return _.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var St,Kn=R(()=>{"use strict";B();St=class{toolNames=["operator_status"];async execute(e,t,n,s){let o=n.taskId,r=n.status,a=n.message;return i.debug(`[OperatorStatusTool] Operator status - Task ${o}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Ct,Qn=R(()=>{"use strict";B();Ct=class{toolNames=["provide_input"];async execute(e,t,n,s){let o=n.input;if(!o)throw new Error("Missing input argument");i.debug(`[ProvideInputTool] Delegating provide_input to backend: ${o.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>(mt(),jt))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:o})}},l=await r.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(r){return i.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});import{exec as uo}from"child_process";import{promisify as po}from"util";import*as xt from"fs/promises";import*as Jn from"path";import*as Yn from"os";var mo,_e,Qt=R(()=>{"use strict";B();mo=po(uo),_e=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=Jn.join(Yn.tmpdir(),`screenshot-${Date.now()}.jpg`),t;if(process.platform==="darwin")t=`screencapture -x -t jpg -q 0.8 "${e}"`;else if(process.platform==="linux")t=`scrot -q 80 "${e}" 2>/dev/null || gnome-screenshot -f "${e}"`;else if(process.platform==="win32")t=`powershell -Command "${`Add-Type -AssemblyName System.Windows.Forms;
|
|
303
325
|
[System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
|
|
304
326
|
Start-Sleep -Milliseconds 100;
|
|
305
327
|
$img = [System.Windows.Forms.Clipboard]::GetImage();
|
|
306
|
-
$img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return i.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await
|
|
328
|
+
$img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return i.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await mo(t);let n=await xt.readFile(e),s=n.toString("base64");return await xt.unlink(e).catch(()=>{}),i.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return i.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
|
|
307
329
|
⚠️ Screenshot tool not found. Please install scrot or gnome-screenshot:`),console.log(" Ubuntu/Debian: sudo apt-get install scrot"),console.log(" Fedora: sudo dnf install scrot"),console.log(` Arch: sudo pacman -S scrot
|
|
308
330
|
`)):process.platform==="darwin"&&(console.log(`
|
|
309
331
|
⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
|
|
310
|
-
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var kt,Ks=N(()=>{"use strict";B();Qt();kt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,s,n){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await _e.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return i.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(o){return i.error(`[TakeScreenshotTool] Failed to capture screenshot: ${o.message}`),[{type:"text",text:`Failed to capture screenshot: ${o.message}`}]}}}});function Qs(c){c.register(new it),c.register(new at),c.register(new ct),c.register(new lt),c.register(new ut),c.register(new dt),c.register(new pt),c.register(new gt),c.register(new ht),c.register(new ft),c.register(new vt),c.register(new Tt),c.register(new St),c.register(new Ct),c.register(new kt)}var Js=N(()=>{"use strict";ks();Es();Is();Ps();Ds();As();Ns();Ms();Us();Ls();Ws();qs();zs();Xs();Ks()});var Et,Ys=N(()=>{"use strict";Et=class{constructor(e,t,s,n,o){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=n;this.activeWebViewURLs=o}}});var en={};ae(en,{FrontendWebSocketService:()=>K});import{EventEmitter as po}from"events";import{io as mo}from"socket.io-client";import Zs from"os";import go from"path";var K,Ke=N(()=>{"use strict";B();be();ne();Ne();Ss();Js();Ys();K=class c extends po{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=3e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=1e4;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;maxResponseCharacters=87500;wsConnectionStartTime=null;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,s="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new st,Qs(this.toolRegistry),i.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?i.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):i.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{i.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return i.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return i.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(i.debug("[FRONTEND WS] connectForConversation called"),i.debug(`[FRONTEND WS] New sessionId: ${t}`),i.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),i.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t&&(i.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1)),this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let s=this.generateUniqueDeviceId(this.userId,"node");if(s&&this.deviceId!==s)i.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${s}`),this.deviceId=s;else if(!s)return i.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(i.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){i.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],i.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){i.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(i.debug("[FRONTEND WS] connect() called"),this.socket?.connected){i.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(i.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),i.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(s){throw new Error(`Failed to get authentication token: ${s}`)}let t=`wss://${this.serverHost}`;i.debug(`[FRONTEND WS] Connecting to ${t}`),i.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),i.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),i.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=mo(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){i.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){i.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,i.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(i.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),i.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,s)=>{let n=setTimeout(()=>{this.connectionPromise=null,s(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(n),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(n),this.connectionPromise=null,s(o)},timeoutId:n}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{i.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{i.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{i.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,i.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{i.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{i.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{i.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{i.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{i.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{i.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{i.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{i.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){i.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();i.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else i.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.flushPendingToolResults(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){i.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||i.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){i.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,s=t?.type||t?.stop_type||"all";switch(i.debug(`[FRONTEND WS] Stop type: ${s}`),s){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:i.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",s=e.reason||"backend_stop_request";i.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${s}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){i.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,s=t.checkpoint_id,n=t.session_id,o=t.iteration;if(!s||!n||o===void 0){i.warn("[FRONTEND WS] Invalid checkpoint request format");return}i.debug(`[FRONTEND WS] Checkpoint request - ID: ${s}, Session: ${n}, Iteration: ${o}`);let r=pe.getInstance(),a=r.getQueuedMessages(),l=a.map(p=>({content:p.content,timestamp:Math.floor(p.timestamp.getTime())})),u=l.length>0;i.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:s,session_id:n,has_feedback:u,feedback:l}),u&&(i.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,s=e.isNew;if(!t||s===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:s})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){i.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){i.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}i.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),i.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},s=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(i.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,s,e.data?.arguments)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){i.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();i.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t,s){this.activeToolCount++;let n=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),i.debug("[FRONTEND WS] === EXECUTING TOOL ==="),i.debug(`[FRONTEND WS] Tool name: ${e.name}`),i.debug(`[FRONTEND WS] Tool ID: ${e.id}`),i.debug(`[FRONTEND WS] Tool call ID: ${t}`);let o=new Et(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,o);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success}),await this.handleLargeResponse(e.id,t,e.name,r,r.success,s)}catch(r){i.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-n)/1e3).toFixed(2);i.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(i.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),i.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}i.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(s){i.error(`[FRONTEND WS] Failed to send message: ${s}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;i.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),i.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(s){i.error(`[FRONTEND WS] Failed to send queued tool result: ${s}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,s,n,o){let r;if(n&&typeof n=="object"&&"content"in n&&Array.isArray(n.content))r=n.content;else{let a;typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),r=this.createContentBlocks(a,o,s)}if(o){let a=this.createDeviceKnowledgeReminderBlock();r.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:r,success:!0,error:null})}sendToolError(e,t,s,n){let o=this.createContentBlocks(n.message,!1,s);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:o,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
|
|
332
|
+
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var kt,Zn=R(()=>{"use strict";B();Qt();kt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await _e.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return i.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(o){return i.error(`[TakeScreenshotTool] Failed to capture screenshot: ${o.message}`),[{type:"text",text:`Failed to capture screenshot: ${o.message}`}]}}}});function es(c){c.register(new it),c.register(new at),c.register(new ct),c.register(new lt),c.register(new ut),c.register(new dt),c.register(new pt),c.register(new gt),c.register(new ht),c.register(new ft),c.register(new vt),c.register(new Tt),c.register(new St),c.register(new Ct),c.register(new kt)}var ts=R(()=>{"use strict";En();In();Pn();Dn();An();Nn();Rn();Bn();Hn();qn();Gn();Vn();Kn();Qn();Zn()});var Et,ns=R(()=>{"use strict";Et=class{constructor(e,t,n,s,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=o}}});var os={};ae(os,{FrontendWebSocketService:()=>K});import{EventEmitter as go}from"events";import{io as ho}from"socket.io-client";import ss from"os";import fo from"path";var K,Ke=R(()=>{"use strict";B();we();se();Ne();Cn();ts();ns();K=class c extends go{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=3e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=1e4;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;maxResponseCharacters=87500;wsConnectionStartTime=null;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new nt,es(this.toolRegistry),i.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?i.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):i.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{i.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return i.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return i.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(i.debug("[FRONTEND WS] connectForConversation called"),i.debug(`[FRONTEND WS] New sessionId: ${t}`),i.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),i.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t&&(i.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1)),this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)i.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return i.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(i.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){i.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],i.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){i.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(i.debug("[FRONTEND WS] connect() called"),this.socket?.connected){i.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(i.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),i.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;i.debug(`[FRONTEND WS] Connecting to ${t}`),i.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),i.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),i.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=ho(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){i.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){i.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,i.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(i.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),i.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(s),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(s),this.connectionPromise=null,n(o)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{i.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{i.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{i.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,i.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{i.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{i.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{i.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{i.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{i.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{i.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{i.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{i.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){i.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();i.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else i.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.flushPendingToolResults(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){i.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||i.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){i.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(i.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:i.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",n=e.reason||"backend_stop_request";i.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${n}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){i.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,o=t.iteration;if(!n||!s||o===void 0){i.warn("[FRONTEND WS] Invalid checkpoint request format");return}i.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${o}`);let r=pe.getInstance(),a=r.getQueuedMessages(),l=a.map(p=>({content:p.content,timestamp:Math.floor(p.timestamp.getTime())})),u=l.length>0;i.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:u,feedback:l}),u&&(i.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){i.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){i.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}i.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),i.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(i.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n,e.data?.arguments)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){i.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();i.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t,n){this.activeToolCount++;let s=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),i.debug("[FRONTEND WS] === EXECUTING TOOL ==="),i.debug(`[FRONTEND WS] Tool name: ${e.name}`),i.debug(`[FRONTEND WS] Tool ID: ${e.id}`),i.debug(`[FRONTEND WS] Tool call ID: ${t}`);let o=new Et(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,o);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success}),await this.handleLargeResponse(e.id,t,e.name,r,r.success,n)}catch(r){i.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-s)/1e3).toFixed(2);i.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(i.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),i.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}i.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(n){i.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;i.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),i.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){i.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,n,s,o){let r;if(s&&typeof s=="object"&&"content"in s&&Array.isArray(s.content))r=s.content;else{let a;typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),r=this.createContentBlocks(a,o,n)}if(o){let a=this.createDeviceKnowledgeReminderBlock();r.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}sendToolError(e,t,n,s){let o=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:o,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
|
|
311
333
|
|
|
312
|
-
UPDATE DEVICE KNOWLEDGE: ${
|
|
334
|
+
UPDATE DEVICE KNOWLEDGE: ${fo.join(ss.homedir(),".orion","device-knowledge.md")}
|
|
313
335
|
Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
|
|
314
|
-
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,
|
|
336
|
+
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
|
|
315
337
|
|
|
316
|
-
No output was produced, which may be expected for this operation.`:
|
|
338
|
+
No output was produced, which may be expected for this operation.`:s=`Command '${n}' failed but no error message was provided.`);try{let o=JSON.parse(s);if(Array.isArray(o)){let r=[];for(let a of o)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?r.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&r.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(r.length>0)return r}}catch{}return[{type:"text",text:s}]}async handleLargeResponse(e,t,n,s,o,r){let a;if(typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),n==="take_screenshot"||n==="take_current_screenshot"){await this.sendToolResult(e,t,n,s,o);return}if(a.length>this.maxResponseCharacters){if(i.debug(`[FRONTEND WS] Response too large (${a.length} chars), creating temp file`),n.toLowerCase()==="read"&&r?.file_path){let f=r.file_path,y=a.substring(0,5e3),T=`File too large (${a.length} characters > 87,500 limit).
|
|
317
339
|
|
|
318
340
|
FILE PATH: ${f}
|
|
319
341
|
|
|
@@ -321,33 +343,33 @@ This file is already on disk. Use Read tool with offset and limit parameters.
|
|
|
321
343
|
|
|
322
344
|
PREVIEW (first 5,000 characters):
|
|
323
345
|
${"─".repeat(50)}
|
|
324
|
-
`+
|
|
346
|
+
`+y+(a.length>5e3?`
|
|
325
347
|
${"─".repeat(50)}
|
|
326
|
-
... (${a.length-5e3} more characters)`:"");await this.sendToolResult(e,t,
|
|
348
|
+
... (${a.length-5e3} more characters)`:"");await this.sendToolResult(e,t,n,T,o);return}let u=await this.createTempFile(a,n);if(!u){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.truncateOutput(a),o);return}let p=this.generatePreview(a,u);await this.sendToolResult(e,t,n,p,o)}else await this.sendToolResult(e,t,n,a,o)}async createTempFile(e,t){try{let n=await import("fs/promises"),s=await import("path"),o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=ss.homedir(),u=s.join(l,".orion","tool_outputs");await n.mkdir(u,{recursive:!0});let p=s.join(u,a);return await n.writeFile(p,e,"utf-8"),i.debug(`[FRONTEND WS] Created temp file: ${p}`),p}catch(n){return i.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}generatePreview(e,t){let n=e.substring(0,5e3),s=`Response too large (${e.length} characters > 87,500 limit), saved to temporary file.
|
|
327
349
|
|
|
328
|
-
`;return
|
|
329
|
-
`,
|
|
350
|
+
`;return s+=`TEMP FILE PATH: ${t}
|
|
351
|
+
`,s+=`Use read_file, grep, cat, or other tools to access the full content.
|
|
330
352
|
|
|
331
|
-
`,
|
|
332
|
-
`,
|
|
333
|
-
`,n
|
|
334
|
-
${"─".repeat(50)}`,
|
|
335
|
-
... (${e.length-5e3} more characters available in temp file)`),
|
|
353
|
+
`,s+=`PREVIEW (first 5,000 characters):
|
|
354
|
+
`,s+=`${"─".repeat(50)}
|
|
355
|
+
`,s+=n,e.length>5e3&&(s+=`
|
|
356
|
+
${"─".repeat(50)}`,s+=`
|
|
357
|
+
... (${e.length-5e3} more characters available in temp file)`),s+=`
|
|
336
358
|
|
|
337
|
-
To read full content: use tools like 'read_file' with path above`,
|
|
359
|
+
To read full content: use tools like 'read_file' with path above`,s}truncateOutput(e){return e.length<=this.maxResponseCharacters?e:e.substring(0,this.maxResponseCharacters)+`
|
|
338
360
|
|
|
339
|
-
[Output truncated at ${this.maxResponseCharacters} characters]`}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),i.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},this.baseAggressiveHeartbeatInterval),i.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),i.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}sendAggressiveHeartbeat(){this.lastHeartbeatSent=new Date,this.socket?.connected&&(this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size}),i.debug(`[FRONTEND WS] Sent aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)),this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3;e<10?this.connectionQuality="excellent":e<30?this.connectionQuality="good":e<60?this.connectionQuality="fair":this.connectionQuality="poor"}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),i.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),i.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});i.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}terminateAllRunningProcesses(){i.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),i.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(
|
|
340
|
-
`);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(
|
|
361
|
+
[Output truncated at ${this.maxResponseCharacters} characters]`}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),i.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},this.baseAggressiveHeartbeatInterval),i.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),i.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}sendAggressiveHeartbeat(){this.lastHeartbeatSent=new Date,this.socket?.connected&&(this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size}),i.debug(`[FRONTEND WS] Sent aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)),this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3;e<10?this.connectionQuality="excellent":e<30?this.connectionQuality="good":e<60?this.connectionQuality="fair":this.connectionQuality="poor"}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),i.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),i.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});i.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}terminateAllRunningProcesses(){i.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),i.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){i.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){i.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){i.debug("[FRONTEND WS] Not connected, cannot register session");return}i.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw i.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};i.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async captureFrontendToolResultForHistory(e,t,n,s){let o=t.map(r=>r.text||"").join(`
|
|
362
|
+
`);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(be(),$e)),a=r.getInstance(),l=s?`Error: ${s}`:o;a.captureFrontendToolResult(e,l,n),i.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){i.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}forceCleanup(){if(i.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.socket){try{this.socket.disconnect()}catch{}this.socket=null}i.debug("[FRONTEND WS] Force cleanup complete")}destroy(){i.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Ee,is=R(()=>{"use strict";Ee=class{static remove(e){if(!e||!e.includes("<context>"))return e;let t=e,n=/<context>[\s\S]*?<\/context>/gi;return t=t.replace(n,""),t=t.replace(/\n{3,}/g,`
|
|
341
363
|
|
|
342
|
-
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var $e={};ae($e,{PersonalAgentService:()=>ee});import{EventEmitter as
|
|
364
|
+
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var $e={};ae($e,{PersonalAgentService:()=>ee});import{EventEmitter as vo}from"events";import Jt from"axios";import yo from"http";import bo from"https";import{v4 as Ie}from"uuid";import he from"fs";import Qe from"path";import Me from"os";var Je,ee,be=R(()=>{"use strict";De();se();Ke();Ne();B();is();Je=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,o=String(n||""),r=Number(s);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(o)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||r===401||r===403||o==="401"||o==="403"?"critical":"parsing"}},ee=class c extends vo{static instance;authService;apiEndpoint="https://snowx.ai/api-beta/api/chat/tool-calling";httpAgent;httpsAgent;currentTodoList=null;activeWebViewURLs=[];operatorTaskState=null;currentOutput="";completeOutputWithToolResults="";currentPromptId=null;currentAbortController=null;currentModel=null;currentSessionId=null;accumulatedToolCalls=new Map;processedToolCallIds=new Set;constructor(){super(),this.authService=H.getInstance(),this.httpAgent=new yo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new bo.Agent({keepAlive:!0,timeout:36e5}),i.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),K.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(i.warn("[PersonalAgent] No auth token available - user may not be authenticated"),"")}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform;if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"){try{let t=Es("fs");if(t.existsSync("/etc/os-release")){let s=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(s)return s[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return he.existsSync(e)?t=he.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
|
|
343
365
|
|
|
344
366
|
Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge (${this.getDeviceKnowledgePath()}): No specific device knowledge available.
|
|
345
367
|
|
|
346
|
-
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=Qe.join(Me.homedir(),".orion");return Qe.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(
|
|
368
|
+
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=Qe.join(Me.homedir(),".orion");return Qe.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(he.existsSync(e))return;let t=Qe.join(Me.homedir(),"Documents","orion","orion-device-knowledge.md");if(he.existsSync(t)){i.info("📦 Migrating device knowledge to cross-platform location...");let n=Qe.dirname(e);he.existsSync(n)||he.mkdirSync(n,{recursive:!0});let s=he.readFileSync(t,"utf8");he.writeFileSync(e,s,"utf8"),i.info(`✅ Device knowledge migrated to: ${e}`),i.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){i.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=Qe.dirname(e);he.existsSync(t)||he.mkdirSync(t,{recursive:!0});let n=Me.platform(),s=Me.arch(),o=Me.hostname(),r=Me.userInfo(),a=`# Device Knowledge
|
|
347
369
|
|
|
348
370
|
## System Information
|
|
349
|
-
- **Platform**: ${
|
|
350
|
-
- **Architecture**: ${
|
|
371
|
+
- **Platform**: ${n}
|
|
372
|
+
- **Architecture**: ${s}
|
|
351
373
|
- **Hostname**: ${o}
|
|
352
374
|
- **Username**: ${r.username}
|
|
353
375
|
- **Home Directory**: ${r.homedir}
|
|
@@ -363,84 +385,84 @@ Remember to update memory about device if any new information is learned during
|
|
|
363
385
|
|
|
364
386
|
---
|
|
365
387
|
*Last updated: ${new Date().toISOString()}*
|
|
366
|
-
`;return
|
|
388
|
+
`;return he.writeFileSync(e,a,"utf8"),a}catch{return"Basic device knowledge initialization failed."}}static getInstance(){return c.instance||(c.instance=new c),c.instance}async sendMessageWithToolCalling(e,t,n,s=.7,o=!0,r,a,l){this.currentPromptId=Ie(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let u=l?.crossDeviceTaskId;u&&i.debug(`[PERSONAL AGENT] Executing cross-device task: ${u}`),l?.mode==="new"&&(t=[],i.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let p=r||this.authService.getUserId();i.debug("🔌 WebSocket will connect after receiving sessionId from API...");let y=(await Promise.resolve().then(()=>(we(),Ge))).DeviceRegistrationService.getInstance().getCurrentDeviceId();if(!y)throw i.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let T={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:e},...a.map(b=>({type:"image_url",image_url:{url:b}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:y,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(l?.conversationId)T.conversationId=l.conversationId,i.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),i.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let b=t.map(d=>{let g,m=d;m.metadata?.toolResults?g=m.metadata.toolResults:m.originalContent?g=m.originalContent:g=typeof d.content=="string"?d.content:JSON.stringify(d.content);let C=[{type:"text",text:g}];return m.imageUrls&&m.imageUrls.length>0&&C.push(...m.imageUrls.map(S=>({type:"image_url",image_url:{url:S}}))),{role:d.role,content:C}});for(let d=0;d<b.length;d++)b[d].role;T.messages=b,i.debug(`[PERSONAL AGENT] Sending request with ${b.length} messages (new conversation)`)}else i.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return o?this.performStreamingToolCall(T):this.performNonStreamingToolCall(T)}async performStreamingToolCall(e){let t=await this.getFirebaseIdToken();return t||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((n,s)=>{this.currentAbortController=new AbortController;let o="",r=Buffer.alloc(0),a="",l="",u=[],p=null,f=!1,y="";this.currentOutput="",this.completeOutputWithToolResults="";let T=new Map,b=new Set,d=this.authService.getUserId();Jt.post(this.apiEndpoint,e,{responseType:"stream",signal:this.currentAbortController.signal,timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}}).then(async g=>{let m=g.data,C=g.headers["x-session-id"]||g.headers["session-id"];if(C){p=C,this.currentSessionId=C,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${C}`);let S=(await Promise.resolve().then(()=>(Ke(),os))).FrontendWebSocketService.getInstance();i.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await S.connectForConversation(d||void 0,C)?i.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):i.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else i.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");m.on("data",S=>{try{r=Buffer.concat([r,S]);let A="",M=0;for(let q=0;q<r.length;q++)try{A=r.slice(0,q+1).toString("utf8"),M=q+1}catch{break}if(M>0){let q=r.slice(0,M);r=r.slice(M),o+=q.toString("utf8")}}catch{o+=S.toString()}let k=[/\r?\n/,/\r/],v=[],x=o;v=x.split(/\r?\n/),x=v.pop()||"",o=x;for(let A of v){let M=A.trim();if(M.startsWith("data: ")){let q=M.slice(6).trim();if(q==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),n(a);return}try{let P=JSON.parse(q);if(P.type==="session_start"&&P.conversationId){let N=P.conversationId,w=P.isNewConversation||!1,I=P.title;i.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),i.debug(`[PERSONAL AGENT] conversationId: ${N}`),i.debug(`[PERSONAL AGENT] isNewConversation: ${w}`),I&&i.debug(`[PERSONAL AGENT] title: "${I}"`),this.emit("conversation_id_received",{conversationId:N,isNew:w,title:I||void 0});continue}if(P.type==="title_generated"&&P.title&&P.conversationId){let N=P.title,w=P.conversationId;i.debug("[PERSONAL AGENT] Received title_generated event!"),i.debug(`[PERSONAL AGENT] conversationId: ${w}`),i.debug(`[PERSONAL AGENT] title: "${N}"`),this.emit("conversation_title_updated",{conversationId:w,title:N});continue}if(P.tool_response&&P.tool_response.content){let N=P.tool_response.content,w=P.tool_response.id||"unknown",I=P.tool_response.name||"unknown";this.emit("tool_completed",{toolName:I,toolId:w,result:N,todos:P.tool_response.todos||null}),this.emit("toolComplete",I);let F="";Array.isArray(N)?F=N.map(O=>typeof O=="string"?O:O&&typeof O=="object"&&(O.text||O.content)||"").join(""):typeof N=="string"?F=N:F=JSON.stringify(N),(!F||F.trim().length===0)&&(F="(empty tool result)");let $=`<context>
|
|
367
389
|
${F}
|
|
368
390
|
</context>`;u.push($),a+=$+`
|
|
369
391
|
`,this.completeOutputWithToolResults+=$+`
|
|
370
392
|
`,this.currentOutput+=$+`
|
|
371
|
-
`;continue}if(P.tool_calls){i.debug("Processing tool calls:",P.tool_calls.length,"items");for(let[
|
|
372
|
-
${
|
|
393
|
+
`;continue}if(P.tool_calls){i.debug("Processing tool calls:",P.tool_calls.length,"items");for(let[N,w]of P.tool_calls.entries())if(i.debug("Tool call ["+N+"]:"),w.id){i.debug("Processing tool call ID:",w.id);let I=T.get(w.id)||{};for(let[F,$]of Object.entries(w))if(F==="function"&&typeof $=="object"&&$!==null){let O=I.function||{};I.function={...O,...$}}else I[F]=$;if(T.set(w.id,I),I.function?.name&&!b.has(w.id)){let F=I.function.name;i.debug("[TOOL-DISPLAY] Showing tool call:",F,"ID:",w.id),this.emit("toolExecuting",F)}if(I.function?.arguments&&I.function?.name){let F=I.function.arguments;F.endsWith("}")||F.endsWith('"}')?(i.debug("Complete tool call accumulated:",w.id,"-",I.function.name),i.debug("Arguments:",F.substring(0,100)+(F.length>100?"...":"")),b.has(w.id)||(b.add(w.id),this.handleCompleteToolCall(I))):i.debug("Partial tool call:",w.id,"-",I.function.name)}}}else if(P.tool_response&&P.tool_response.content){let N=P.tool_response.content,w=P.tool_response.id||"unknown",I=P.tool_response.name||"unknown",F=P.tool_response.role||"unknown";i.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),i.debug(" Tool ID:",w),i.debug(" Tool Name:",I),i.debug(" Tool Role:",F),i.debug(" Content Length:",N.length),i.debug(" Content Preview:",N.substring(0,200)+"..."),this.emit("tool_completed",{toolName:I,toolId:w,result:N,todos:P.tool_response.todos||null}),this.emit("toolComplete",I),P.tool_response.todos&&Array.isArray(P.tool_response.todos)&&(i.debug("[PERSONAL AGENT] Tool response contains",P.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:P.tool_response.todos}));let $=`<context>
|
|
394
|
+
${N}
|
|
373
395
|
</context>`;u.push($),a+=$+`
|
|
374
396
|
`,this.completeOutputWithToolResults+=$+`
|
|
375
397
|
`,this.currentOutput+=$+`
|
|
376
|
-
`,i.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(P.content!==void 0){let
|
|
398
|
+
`,i.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(P.content!==void 0){let N=P.content;if(N&&N.length>0&&i.debug(`[STREAMING] Received content chunk: "${N}" (length: ${N.length})`),N&&N.includes('{"tool_response"'))try{let w,I=!1;try{w=JSON.parse(N),I=!0}catch{let F=N.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(F){let $=F[0];w=JSON.parse($),I=!1}}if(w&&w.tool_response&&w.tool_response.content){let F=w.tool_response.content,$=w.tool_response.id||"unknown",O=w.tool_response.name||"unknown";this.emit("tool_completed",{toolName:O,toolId:$,result:F,todos:w.tool_response.todos||null}),this.emit("toolComplete",O),w.tool_response.todos&&Array.isArray(w.tool_response.todos)&&this.handleTodoUpdate({items:w.tool_response.todos});let ue="";Array.isArray(F)?ue=F.map(G=>G.text||"").join(""):typeof F=="string"?ue=F:ue=JSON.stringify(F);let re=`<context>
|
|
377
399
|
${ue}
|
|
378
400
|
</context>`;if(u.push(re),a+=re+`
|
|
379
401
|
`,this.completeOutputWithToolResults+=re+`
|
|
380
402
|
`,this.currentOutput+=re+`
|
|
381
|
-
`,!I){let G=
|
|
382
|
-
${
|
|
403
|
+
`,!I){let G=N.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(G){let j=N.replace(G[0],"").trim();if(j.length>0){a+=j,l+=j,this.currentOutput+=j,this.completeOutputWithToolResults+=j;let Z=Ee.remove(j);this.emit("data",Z)}}}continue}}catch{}if(N.includes("<think>")){f=!0;let w=N.split("<think>")[0];if(w){a+=w,l+=w,this.currentOutput+=w,this.completeOutputWithToolResults+=w;let I=Ee.remove(w);this.emit("data",I)}}else if(N.includes("</think>")){f=!1,y+=N.split("</think>")[0],this.emit("thinking",y),y="";let w=N.split("</think>")[1]||"";if(w){a+=w,l+=w,this.currentOutput+=w,this.completeOutputWithToolResults+=w;let I=Ee.remove(w);this.emit("data",I)}}else if(f)y+=N,this.emit("thinking",y);else{a+=N,l+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let w=Ee.remove(N);this.emit("data",w)}}else if(P.type==="checkpoint_reached"||P.event==="checkpoint_reached")i.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(P.type==="todo_update")this.handleTodoUpdate(P.data);else if(P.type==="webview_update")this.handleWebViewUpdate(P.data);else if(P.type==="operator_progress")this.handleOperatorProgress(P.data);else if(P.type==="stop"){this.handleStop(P.data),n(a);return}}catch{i.debug("Treating as plain text"),a+=q,l+=q,this.currentOutput+=q,this.completeOutputWithToolResults+=q;let N=Ee.remove(q);this.emit("data",N)}}}}),m.on("end",()=>{this.emit("done"),n(a)}),m.on("error",S=>{switch(i.debug("Streaming error, disconnecting WebSocket and cleaning up"),Je.classify(S)){case"parsing":let v={type:"tool_result",tool_call_id:`error_${Ie()}`,error:!0,content:`Streaming parsing error occurred: ${S.message}. Please check response format and retry.`};i.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(v)),K.getInstance().handleConversationComplete(),n(a);return;case"critical":K.getInstance().handleConversationComplete(),this.emit("error",S),s(S);break}})}).catch(g=>{if(g.code==="ERR_CANCELED")i.debug("Task was cancelled, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),this.emit("canceled"),n(a);else switch(Je.classify(g)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${Ie()}`,error:!0,content:`Request parsing error: ${g.message}. Please check request format and retry.`};i.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(C)),K.getInstance().handleConversationComplete(),n(a);break;case"critical":i.debug("Request failed, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),s(g);break}})})}async performNonStreamingToolCall(e){try{let t=await this.getFirebaseIdToken();t||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let n=await Jt.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}});if(n.data?.content){if(this.currentOutput=n.data.content,this.completeOutputWithToolResults=n.data.completeOutput||n.data.content,n.data.toolResults)for(let s of n.data.toolResults)this.handleToolResult(s.tool,s.result);return n.data.content}throw new Error("No response content received")}catch(t){switch(Je.classify(t)){case"parsing":let s={type:"tool_result",tool_call_id:`error_${Ie()}`,error:!0,content:`Non-streaming API parsing error: ${t.message}. Please check request format and retry.`};return i.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(s)),"";case"critical":throw this.emit("error",t),new Error(`Tool calling API Error: ${t.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{i.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}this.emit("toolExecuting",t),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=K.getInstance(),o={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(o)}catch(s){i.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),i.debug(`Tool Result: ${e.name}`),t&&i.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:o}=e;if(i.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
|
|
404
|
+
${n.map(l=>l.text||"").join("")}
|
|
383
405
|
</context>`;this.completeOutputWithToolResults+=a+`
|
|
384
406
|
`,this.currentOutput+=a+`
|
|
385
407
|
`,i.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(o){i.debug("[PERSONAL AGENT] WebSocket tool error:",o);let r=`<context>
|
|
386
408
|
Error: ${o}
|
|
387
409
|
</context>`;this.completeOutputWithToolResults+=r+`
|
|
388
|
-
`}}captureFrontendToolResult(e,t,s
|
|
410
|
+
`}}captureFrontendToolResult(e,t,n,s){let o=`<context>
|
|
389
411
|
Tool: ${e}
|
|
390
|
-
Success: ${
|
|
412
|
+
Success: ${n}
|
|
391
413
|
Output:
|
|
392
414
|
${t}
|
|
393
415
|
</context>`;this.completeOutputWithToolResults+=o+`
|
|
394
416
|
`,this.currentOutput+=o+`
|
|
395
|
-
`,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${
|
|
417
|
+
`,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),i.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:s,wrappedContent:o})}handleCheckpointReached(){let e=pe.getInstance(),t=e.getQueuedMessages();if(t.length===0){i.debug("[CHECKPOINT] No queued messages to convert");return}let n=t.filter(o=>!o.isCrossDeviceTask),s=t.filter(o=>o.isCrossDeviceTask);if(i.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),i.debug(` - ${n.length} user messages -> convert to feedback`),i.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let o=n.map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",o),i.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(r=>{e.removeFromQueueById(r.id)})}s.length>0&&i.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||Ie(),text:t.text,completed:t.completed||!1,priority:t.priority,status:t.status||(t.completed?"completed":"pending"),activeForm:t.activeForm||t.text})),timestamp:new Date(e.timestamp||Date.now())},this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||Ie(),taskId:e.taskId||e.id||Ie(),sessionId:e.sessionId||Ie(),status:e.status||"pending",task:e.task||e.description||"",llm:e.llm,currentStep:e.currentStep,totalSteps:e.totalSteps||0,steps:e.steps||[],result:e.result,error:e.error,startTime:e.startTime||new Date},this.emit("operator_progress",this.operatorTaskState)}handleStop(e){e.reason==="CONVERSATION_COMPLETE"&&this.handleConversationComplete(),this.emit("BotResponseStopped",{reason:e.reason||"user_manual_stop"}),this.emit("stop",e)}async handleConversationComplete(){if(i.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),K.getInstance().handleConversationComplete(),i.debug("[PERSONAL AGENT] WebSocket disconnected after conversation completion"),this.currentOutput.trim().length>0){let t={conversationId:null,content:this.currentOutput,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};i.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),i.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),i.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",{SNOWX_MODELS:s}=await Promise.resolve().then(()=>(De(),fn)),o=s.find(a=>a.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},r=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,r,o,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){i.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),K.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
|
|
396
418
|
|
|
397
|
-
[STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{i.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(n){i.debug("[PERSONAL AGENT] Firebase update failed for STOP:",n)}await this.completeConversation(s,"STOP"),i.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),i.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let o=(await Promise.resolve().then(()=>(be(),qe))).DeviceRegistrationService.getInstance().getCurrentDeviceId();o?(s.device_id=o,i.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${o}`)):i.debug("[PERSONAL AGENT] No device_id available for stop request"),i.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Jt.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(i.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&i.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&i.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){i.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){i.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),K.getInstance().handleConversationComplete();let n={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",n),this.resetState(),i.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear()}getCurrentTodoList(){return this.currentTodoList}getActiveWebViewURLs(){return this.activeWebViewURLs}getOperatorTaskState(){return this.operatorTaskState}getCompleteOutput(){return this.completeOutputWithToolResults||this.currentOutput}get isProcessing(){return this.currentAbortController!==null||this.currentPromptId!==null}}});var sn={};ae(sn,{FirebaseNativeService:()=>Ye,TaskMode:()=>es,TaskStatus:()=>ts});import{getDatabase as wo,ref as Zt,onChildAdded as To,update as So,set as Co,serverTimestamp as xo}from"firebase/database";import{EventEmitter as ko}from"events";var es,ts,Ye,ss=N(()=>{"use strict";B();tt();es=(t=>(t.NEW="new",t.EXISTING="existing",t))(es||{}),ts=(n=>(n.PENDING="pending",n.PROCESSING="processing",n.COMPLETED="completed",n.QUEUE_FULL="queue_full",n))(ts||{}),Ye=class c extends ko{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),i.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Se.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=wo(e),i.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(i.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(i.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){i.error("[Firebase Native] Firebase not initialized properly");return}i.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;i.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let n=Zt(this.database,s),o=this.auth?.currentUser;i.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=To(n,r=>{let a=r.key,l=r.val();if(i.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){i.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){i.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){i.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:l.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let u=Array.from(this.processedTaskIds);u.slice(0,u.length-this.MAX_PROCESSED_IDS).forEach(f=>this.processedTaskIds.delete(f))}i.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{i.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),i.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){i.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,i.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),i.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),i.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){i.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){i.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),i.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),i.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(ye(),$e))).PersonalAgentService.getInstance()){i.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}i.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?i.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):i.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),i.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),i.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(n){i.error("[FIREBASE-NATIVE] Task execution failed:",n.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ye(),$e)),s=t.getInstance();await this.cleanupObservers(),this.completedObserver=n=>{this.currentTaskId===e&&(i.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=n=>{if(this.currentTaskId!==e)return;let o=n?.message||n||"Unknown error occurred";i.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=n=>{if(this.currentTaskId!==e)return;let o=n?.reason;i.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),i.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(ye(),$e)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),i.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){i.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};s&&(o.result=s),i.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:n,status:t,hasResult:!!s});try{i.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(n,o),i.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){i.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:n,error:r.message}),i.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Zt(this.database,n),l={status:t,updatedAt:xo()};s&&(l.result=s),await So(a,l),i.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else i.error("[Firebase Native] Database not available for fallback")}catch(a){i.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,n){let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;i.debug("[Firebase Native] Sending task to device",{taskId:o,targetDeviceId:t,mode:n});try{let r=Zt(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:n,timestamp:Date.now(),status:"pending"};return await Co(r,a),i.debug("[Firebase Native] Task sent successfully",{taskId:o,targetDeviceId:t}),o}catch(r){throw r}}stopListening(){if(i.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,i.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){i.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),i.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Eo}from"events";var Ue,ns=N(()=>{"use strict";be();ne();tt();ss();ye();B();Ue=class c extends Eo{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.firebaseAPI=Se.getInstance(),this.firebaseNative=Ye.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=ee.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){i.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(i.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(i.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){i.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){i.debug("✅ [CrossDevice] No pending tasks in queue");return}let s=this.pendingTasksQueue.shift();i.debug(`📤 [CrossDevice] Processing next task from queue: ${s.taskId}`),this.executeTaskImmediately(s.taskId,s.prompt,s.mode)}async startListening(e,t){let s=t||this.deviceRegistrationService.getCurrentDeviceId();if(!s){i.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,i.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let n=this.authService.getFirebaseAuth();if(!n?.currentUser){i.error("No authenticated Firebase user - cannot start listeners");return}if(n.currentUser.uid!==e){i.error("SECURITY: User ID mismatch! Firebase UID:",n.currentUser.uid,"Requested:",e),i.error("Refusing to start listener for different user");return}i.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(n){throw i.error("Failed to start listener:",n.message),n}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),i.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){i.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){i.error("No stored user ID found - cannot authenticate Firebase for listeners");return}i.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let n=await this.authService.signInWithCustomToken(s);i.debug("Firebase authenticated successfully - UID:",n.user.uid)}}catch(s){i.warn("Firebase authentication failed:",s.message),i.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){i.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e.taskId),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}i.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,i.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),i.debug("Cross-device task UI flow triggered successfully")}catch(t){i.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){i.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(s){i.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),i.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let n=s[1],o=s[2];return n.length!==13||!Number.isInteger(Number(n))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,n=t.prompt,o=t.status;if(!s||!n){i.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){i.debug("⏭️ [CrossDevice] Skipping non-pending task:",s,"Status:",o);return}this.incomingTaskQueue.push({taskId:s,prompt:n,snapshot:e}),i.debug(`📨 [CrossDevice] Task queued for processing: ${s}`),i.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){i.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:s}=this.incomingTaskQueue.shift();i.debug(`🔵 [CrossDevice] Processing task: ${e}`),i.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let n=s.val();if(i.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(i.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){i.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}i.debug("✅ [CrossDevice] Task accepted:",e),i.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=(Ne(),kn(Ts)).MessageQueueManager.getInstance(),o=n.getQueueCount(),r=n.canAddToQueue();if(i.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,s){if(i.debug(`Executing task: ${e} with mode: ${s}`),i.debug(`Prompt to execute: ${t}`),ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),i.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}i.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{i.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(n){i.error("Task execution failed:",n.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,n={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,n)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},s=o=>{this.currentTaskId===e&&this.cleanupObservers()},n=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",n)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,s="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let n=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:Ce,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${n}`;try{await this.firebaseAPI.writeRealtimeData(r,o),i.debug("Task submitted to device:",e)}catch(a){throw i.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([s,n])=>({id:s,...n})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return i.error("Failed to get available devices:",e.message),[]}}enable(){i.debug("[CROSS DEVICE] Service enabled")}disable(){i.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){i.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var cn={};ae(cn,{SnowXStreamHandlerService:()=>rs});import{EventEmitter as Wo}from"events";var rs,ln=N(()=>{"use strict";rs=class extends Wo{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,s,n,o){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let p=this.byteBuffer.toString("utf8");this.buffer+=p,this.rawDataReceived+=p,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,n,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,n,o),this.printFinalStatistics(),!this.fullResponse&&!o){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let n,o=this.buffer.indexOf(`\r
|
|
398
|
-
`);if(o!==-1)
|
|
399
|
-
`);if(r!==-1)
|
|
400
|
-
`?this.buffer=this.buffer.substring(
|
|
419
|
+
[STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{i.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){i.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),i.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),i.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let o=(await Promise.resolve().then(()=>(we(),Ge))).DeviceRegistrationService.getInstance().getCurrentDeviceId();o?(n.device_id=o,i.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${o}`)):i.debug("[PERSONAL AGENT] No device_id available for stop request"),i.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Jt.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(i.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&i.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&i.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){i.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){i.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),K.getInstance().handleConversationComplete();let s={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",s),this.resetState(),i.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear()}getCurrentTodoList(){return this.currentTodoList}getActiveWebViewURLs(){return this.activeWebViewURLs}getOperatorTaskState(){return this.operatorTaskState}getCompleteOutput(){return this.completeOutputWithToolResults||this.currentOutput}get isProcessing(){return this.currentAbortController!==null||this.currentPromptId!==null}}});var rs={};ae(rs,{FirebaseNativeService:()=>Ye,TaskMode:()=>en,TaskStatus:()=>tn});import{getDatabase as So,ref as Zt,onChildAdded as Co,update as xo,set as ko,serverTimestamp as Eo}from"firebase/database";import{EventEmitter as Io}from"events";var en,tn,Ye,nn=R(()=>{"use strict";B();tt();en=(t=>(t.NEW="new",t.EXISTING="existing",t))(en||{}),tn=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(tn||{}),Ye=class c extends Io{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),i.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Ce.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=So(e),i.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(i.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(i.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){i.error("[Firebase Native] Firebase not initialized properly");return}i.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;i.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=Zt(this.database,n),o=this.auth?.currentUser;i.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=Co(s,r=>{let a=r.key,l=r.val();if(i.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){i.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){i.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){i.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:l.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let u=Array.from(this.processedTaskIds);u.slice(0,u.length-this.MAX_PROCESSED_IDS).forEach(f=>this.processedTaskIds.delete(f))}i.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{i.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),i.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){i.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,i.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),i.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),i.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){i.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){i.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),i.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),i.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(be(),$e))).PersonalAgentService.getInstance()){i.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}i.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?i.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):i.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),i.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),i.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){i.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(be(),$e)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(i.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.message||s||"Unknown error occurred";i.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.reason;i.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),i.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(be(),$e)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),i.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){i.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};n&&(o.result=n),i.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{i.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,o),i.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){i.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:r.message}),i.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Zt(this.database,s),l={status:t,updatedAt:Eo()};n&&(l.result=n),await xo(a,l),i.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else i.error("[Firebase Native] Database not available for fallback")}catch(a){i.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;i.debug("[Firebase Native] Sending task to device",{taskId:o,targetDeviceId:t,mode:s});try{let r=Zt(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await ko(r,a),i.debug("[Firebase Native] Task sent successfully",{taskId:o,targetDeviceId:t}),o}catch(r){throw r}}stopListening(){if(i.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,i.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){i.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),i.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Po}from"events";var Ue,sn=R(()=>{"use strict";we();se();tt();nn();be();B();Ue=class c extends Po{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.firebaseAPI=Ce.getInstance(),this.firebaseNative=Ye.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=ee.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){i.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(i.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(i.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){i.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){i.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();i.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){i.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,i.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){i.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){i.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),i.error("Refusing to start listener for different user");return}i.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw i.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),i.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){i.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){i.error("No stored user ID found - cannot authenticate Firebase for listeners");return}i.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);i.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){i.warn("Firebase authentication failed:",n.message),i.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){i.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e.taskId),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}i.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,i.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),i.debug("Cross-device task UI flow triggered successfully")}catch(t){i.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){i.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){i.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),i.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],o=n[2];return s.length!==13||!Number.isInteger(Number(s))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,o=t.status;if(!n||!s){i.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){i.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",o);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),i.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),i.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){i.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();i.debug(`🔵 [CrossDevice] Processing task: ${e}`),i.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(i.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(i.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){i.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}i.debug("✅ [CrossDevice] Task accepted:",e),i.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let s=(Ne(),Ps(Sn)).MessageQueueManager.getInstance(),o=s.getQueueCount(),r=s.canAddToQueue();if(i.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(i.debug(`Executing task: ${e} with mode: ${n}`),i.debug(`Prompt to execute: ${t}`),ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(r),i.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}i.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{i.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){i.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=o=>{this.currentTaskId===e&&this.cleanupObservers()},s=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:xe,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(r,o),i.debug("Task submitted to device:",e)}catch(a){throw i.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return i.error("Failed to get available devices:",e.message),[]}}enable(){i.debug("[CROSS DEVICE] Service enabled")}disable(){i.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){i.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var ds={};ae(ds,{SnowXStreamHandlerService:()=>an});import{EventEmitter as Ho}from"events";var an,ps=R(()=>{"use strict";an=class extends Ho{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,n,s,o){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let p=this.byteBuffer.toString("utf8");this.buffer+=p,this.rawDataReceived+=p,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(n,s,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,o),this.printFinalStatistics(),!this.fullResponse&&!o){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,o=this.buffer.indexOf(`\r
|
|
420
|
+
`);if(o!==-1)s=o;else{let r=this.buffer.indexOf(`
|
|
421
|
+
`);if(r!==-1)s=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)s=a;else return}}for(;s!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,s);this.linesProcessed++,this.buffer.substring(s,s+2)===`\r
|
|
422
|
+
`?this.buffer=this.buffer.substring(s+2):this.buffer=this.buffer.substring(s+1);let a=r.trim();if(!a){s=this.findNextLineEnd();continue}if(a.startsWith(":")){s=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,n),s=this.findNextLineEnd()}}processDataLine(e,t,n,s){if(this.isCancelled)return;this.dataLinesFound++;let o=e.substring(6).trim();if(o==="[DONE]"){this.emit("streamEnd");return}if(o)try{let r=JSON.parse(o);if(r.choices&&r.choices.length>0){let a=r.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)s?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,n))}}catch{}}processThinkingContent(e,t,n){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let s=this.thinkingBuffer.indexOf("</think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.thinkingContent+=o,n?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",n?.(this.thinkingContent));break}else{let s=this.thinkingBuffer.indexOf("<think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.regularContent+=o,this.fullResponse+=o,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,n){if(this.rawDataReceived.startsWith("data: ")){let s=this.rawDataReceived.substring(6).trim();try{let o=JSON.parse(s);o.choices&&o.choices.length>0&&o.choices[0].delta.content&&this.processThinkingContent(o.choices[0].delta.content,e,t)}catch{}}else try{let s=JSON.parse(this.rawDataReceived);s.choices?.[0]?.message?.content&&this.processThinkingContent(s.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
|
|
401
423
|
`);if(e!==-1)return e;let t=this.buffer.indexOf(`
|
|
402
|
-
`);if(t!==-1)return t;let s=this.buffer.indexOf("\r");return s!==-1?s:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import Bo from"axios";import{EventEmitter as Ho}from"events";import Go from"http";import qo from"https";var Dt,un=N(()=>{"use strict";ne();Dt=class extends Ho{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Go.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new qo.Agent({keepAlive:!0,timeout:36e5}),this.client=Bo.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=H.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let s=0;s<t;s++)try{return await e()}catch(n){if(n.response?.status===429){if(s===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,s);await new Promise(r=>setTimeout(r,o*1e3))}else throw n}throw new Error("Max retries exceeded")}buildRequest(e,t,s,n=.7,o=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:n,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,n=.9,o,r){let a=this.buildRequest(e,t,!1,s,n,o,r);try{let u=(await this.executeWithRetry(async()=>{let{data:p}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return p})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,s=.7,n=.9,o,r,a,l,u){let{SnowXStreamHandlerService:p}=await Promise.resolve().then(()=>(ln(),cn)),f=this.buildRequest(e,t,!0,s,n,o,r);return new Promise((v,b)=>{this.currentAbortController=new AbortController;let T=[],d=new Map,g=new p;this.client.post("/chat/completions",f,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async m=>{let S=m.data,x=m.headers["content-type"]||"",E=y=>{if(y?.index!==void 0){let k=y.index;d.has(k)||d.set(k,{});let R=d.get(k);y.id&&(R.id=y.id,R.type="function"),y.function&&(R.function||(R.function={name:"",arguments:""}),y.function.name&&(R.function.name=y.function.name),y.function.arguments&&(R.function.arguments+=y.function.arguments))}u?.(y),this.emit("tool_call_delta",y)};g.on("streamEnd",()=>{d.forEach((y,k)=>{y.id&&y.function?.name&&T.push(y)}),this.emit("done"),v({content:g.getFinalResponse(),toolCalls:T.length>0?T:void 0})}),g.on("cancelled",()=>{this.emit("canceled"),v({content:g.getFinalResponse(),toolCalls:T.length>0?T:void 0})});try{await g.processStreamingResponse(S,x,a||(()=>{}),l,E),d.forEach((y,k)=>{y.id&&y.function?.name&&T.push(y)}),this.emit("done"),v({content:g.getFinalResponse(),toolCalls:T.length>0?T:void 0})}catch(y){this.emit("error",y),b(y)}}).catch(m=>{m.code==="ERR_CANCELED"?(this.emit("canceled"),v({content:"",toolCalls:T.length>0?T:void 0})):b(m)})})}stopStreaming(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=void 0)}async testConnection(e){try{let t={role:"user",content:"Hello"};return!!(await this.performNonStreamingRequest([t],e,.7,.9)).content}catch{return!1}}}});import{io as zo}from"socket.io-client";import{EventEmitter as Xo}from"events";var At,dn=N(()=>{"use strict";be();At=class c extends Xo{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=de.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let s={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=zo(t,s),this.setupEventHandlers(),new Promise((n,o)=>{let r=setTimeout(()=>{o(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),n(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(s){return console.error("❌ Failed to connect WebSocket:",s),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let s={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,s)}sendCrossDeviceMessage(e,t,s){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:s,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,s){this.send("conversation_sync",{conversationId:e,action:t,data:s,timestamp:Date.now()})}syncToolExecution(e,t,s){this.send("tool_execution",{toolName:e,status:t,result:s,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var pn,mn=N(()=>{"use strict";pn={apiKey:process.env.FIREBASE_API_KEY||"AIzaSyARpn1ypwsrIwB53shF2K0AKvHjNABcpBA",authDomain:process.env.FIREBASE_AUTH_DOMAIN||"snowx-31c33.firebaseapp.com",databaseURL:process.env.FIREBASE_DATABASE_URL||"https://snowx-31c33-default-rtdb.firebaseio.com",projectId:process.env.FIREBASE_PROJECT_ID||"snowx-31c33",storageBucket:process.env.FIREBASE_STORAGE_BUCKET||"snowx-31c33.firebasestorage.app",messagingSenderId:process.env.FIREBASE_MESSAGING_SENDER_ID||"679827069698",appId:process.env.FIREBASE_APP_ID||"1:679827069698:web:d4fd2c1c30d0b94ca04b5d",measurementId:process.env.FIREBASE_MEASUREMENT_ID||"G-1HZDCGCV7M"}});var hn={};ae(hn,{ServiceManager:()=>et});import{EventEmitter as jo}from"events";import{initializeApp as Vo,getApps as gn}from"firebase/app";import{getAuth as Ko}from"firebase/auth";var et,as=N(()=>{"use strict";ye();un();ne();be();dn();Ke();ns();mt();Pe();B();mn();et=class c extends jo{static instance;initialized=!1;personalAgent;networkClient;authService;deviceRegistration;webSocketService;frontendWebSocketService;crossDeviceService;toolCalling;firebaseApp=null;firebaseAuth=null;options={enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0};constructor(){super(),this.personalAgent=ee.getInstance(),this.networkClient=new Dt,this.authService=H.getInstance(),this.deviceRegistration=de.getInstance(),this.webSocketService=At.getInstance(),this.frontendWebSocketService=K.getInstance(),this.crossDeviceService=Ue.getInstance(),this.toolCalling=Ve.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}isInitialized(){return this.initialized}async initialize(e={}){if(!this.initialized){this.options={...this.options,...e};try{this.options.enableFirebase&&await this.initializeFirebase(),this.options.enableWebSocket&&await this.initializeWebSocket(),this.options.enableCrossDevice&&this.options.enableWebSocket&&await this.initializeCrossDevice(),this.options.enableToolCalling&&await this.initializeToolCalling(),this.setupServiceConnections(),this.initialized=!0,this.emit("initialized")}catch(t){throw t}}}async initializeFirebase(){try{let e=this.options.firebaseConfig||pn;if(gn().length===0?(this.firebaseApp=Vo(e),i.debug("Firebase app initialized")):(this.firebaseApp=gn()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=Ko(this.firebaseApp),i.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),i.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(ss(),sn));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),i.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{i.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){i.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=X[0],s={}){let{usePersonalAgent:n=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=s;try{let l=[];if(n)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=o?this.toolCalling.getAvailableTools():void 0;return a?new Promise((p,f)=>{let v="";this.networkClient.on("data",b=>{v+=b}),this.networkClient.on("done",()=>{p(v)}),this.networkClient.on("error",f),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:s}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return X.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((s,n)=>{let o=setTimeout(()=>{n(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),s()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),s())})}}});import*as us from"@sentry/node";us.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as si}from"commander";import Jo from"react";import{render as Yo}from"ink";ne();import h,{useState as on,useEffect as Ze,useCallback as is,useRef as Do}from"react";import{Box as D,Text as C,useInput as Ao,useApp as No}from"ink";import Ro from"ink-spinner";import rn from"ink-select-input";ye();Qt();import le from"chalk";import yo from"ora";var te=class{static spinner=null;static formatUserMessage(e){return le.cyan("You: ")+e}static formatAssistantMessage(e){return le.green("Assistant: ")+e}static formatError(e){return le.red("Error: ")+e}static formatWarning(e){return le.yellow("Warning: ")+e}static formatInfo(e){return le.blue("Info: ")+e}static formatSuccess(e){return le.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=yo(e).start()}static updateSpinner(e){this.spinner&&(this.spinner.text=e)}static stopSpinner(e=!0,t){this.spinner&&(t?e?this.spinner.succeed(t):this.spinner.fail(t):this.spinner.stop(),this.spinner=null)}static clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}static printDivider(){console.log(le.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(le.bold.cyan(e)),console.log(le.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return le.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return le.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(le.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};B();Ne();import{EventEmitter as bo}from"events";import Yt from"chalk";var It=class extends bo{delegate=null;personalAgentService=ee.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",s=console.log;this.delegate?.usesCustomUI||(console.log=(...n)=>{let o=String(n[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),s.apply(console,n)}),this.personalAgentService.on("data",n=>{if(t+=n,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=n:o.content+=n),r&&r.isStreaming&&(!r.content||r.content===""?r.content=n:r.content+=n)}}),this.personalAgentService.on("thinking",n=>{}),this.personalAgentService.on("toolExecuting",n=>{this.delegate?.usesCustomUI||console.log(`
|
|
403
|
-
▸ ${
|
|
404
|
-
❌ Error:`,
|
|
424
|
+
`);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import qo from"axios";import{EventEmitter as Go}from"events";import zo from"http";import Xo from"https";var Dt,ms=R(()=>{"use strict";se();Dt=class extends Go{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new zo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Xo.Agent({keepAlive:!0,timeout:36e5}),this.client=qo.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=H.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){if(s.response?.status===429){if(n===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,n);await new Promise(r=>setTimeout(r,o*1e3))}else throw s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,o=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,o,r){let a=this.buildRequest(e,t,!1,n,s,o,r);try{let u=(await this.executeWithRetry(async()=>{let{data:p}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return p})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,o,r,a,l,u){let{SnowXStreamHandlerService:p}=await Promise.resolve().then(()=>(ps(),ds)),f=this.buildRequest(e,t,!0,n,s,o,r);return new Promise((y,T)=>{this.currentAbortController=new AbortController;let b=[],d=new Map,g=new p;this.client.post("/chat/completions",f,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async m=>{let C=m.data,S=m.headers["content-type"]||"",k=v=>{if(v?.index!==void 0){let x=v.index;d.has(x)||d.set(x,{});let A=d.get(x);v.id&&(A.id=v.id,A.type="function"),v.function&&(A.function||(A.function={name:"",arguments:""}),v.function.name&&(A.function.name=v.function.name),v.function.arguments&&(A.function.arguments+=v.function.arguments))}u?.(v),this.emit("tool_call_delta",v)};g.on("streamEnd",()=>{d.forEach((v,x)=>{v.id&&v.function?.name&&b.push(v)}),this.emit("done"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})}),g.on("cancelled",()=>{this.emit("canceled"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})});try{await g.processStreamingResponse(C,S,a||(()=>{}),l,k),d.forEach((v,x)=>{v.id&&v.function?.name&&b.push(v)}),this.emit("done"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})}catch(v){this.emit("error",v),T(v)}}).catch(m=>{m.code==="ERR_CANCELED"?(this.emit("canceled"),y({content:"",toolCalls:b.length>0?b:void 0})):T(m)})})}stopStreaming(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=void 0)}async testConnection(e){try{let t={role:"user",content:"Hello"};return!!(await this.performNonStreamingRequest([t],e,.7,.9)).content}catch{return!1}}}});import{io as jo}from"socket.io-client";import{EventEmitter as Vo}from"events";var At,gs=R(()=>{"use strict";we();At=class c extends Vo{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=de.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=jo(t,n),this.setupEventHandlers(),new Promise((s,o)=>{let r=setTimeout(()=>{o(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var hs,fs=R(()=>{"use strict";hs={apiKey:process.env.FIREBASE_API_KEY||"AIzaSyARpn1ypwsrIwB53shF2K0AKvHjNABcpBA",authDomain:process.env.FIREBASE_AUTH_DOMAIN||"snowx-31c33.firebaseapp.com",databaseURL:process.env.FIREBASE_DATABASE_URL||"https://snowx-31c33-default-rtdb.firebaseio.com",projectId:process.env.FIREBASE_PROJECT_ID||"snowx-31c33",storageBucket:process.env.FIREBASE_STORAGE_BUCKET||"snowx-31c33.firebasestorage.app",messagingSenderId:process.env.FIREBASE_MESSAGING_SENDER_ID||"679827069698",appId:process.env.FIREBASE_APP_ID||"1:679827069698:web:d4fd2c1c30d0b94ca04b5d",measurementId:process.env.FIREBASE_MEASUREMENT_ID||"G-1HZDCGCV7M"}});var ys={};ae(ys,{ServiceManager:()=>et});import{EventEmitter as Ko}from"events";import{initializeApp as Qo,getApps as vs}from"firebase/app";import{getAuth as Jo}from"firebase/auth";var et,cn=R(()=>{"use strict";be();ms();se();we();gs();Ke();sn();mt();De();B();fs();et=class c extends Ko{static instance;initialized=!1;personalAgent;networkClient;authService;deviceRegistration;webSocketService;frontendWebSocketService;crossDeviceService;toolCalling;firebaseApp=null;firebaseAuth=null;options={enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0};constructor(){super(),this.personalAgent=ee.getInstance(),this.networkClient=new Dt,this.authService=H.getInstance(),this.deviceRegistration=de.getInstance(),this.webSocketService=At.getInstance(),this.frontendWebSocketService=K.getInstance(),this.crossDeviceService=Ue.getInstance(),this.toolCalling=Ve.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}isInitialized(){return this.initialized}async initialize(e={}){if(!this.initialized){this.options={...this.options,...e};try{this.options.enableFirebase&&await this.initializeFirebase(),this.options.enableWebSocket&&await this.initializeWebSocket(),this.options.enableCrossDevice&&this.options.enableWebSocket&&await this.initializeCrossDevice(),this.options.enableToolCalling&&await this.initializeToolCalling(),this.setupServiceConnections(),this.initialized=!0,this.emit("initialized")}catch(t){throw t}}}async initializeFirebase(){try{let e=this.options.firebaseConfig||hs;if(vs().length===0?(this.firebaseApp=Qo(e),i.debug("Firebase app initialized")):(this.firebaseApp=vs()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=Jo(this.firebaseApp),i.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),i.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(nn(),rs));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),i.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{i.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){i.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=X[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=n;try{let l=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=o?this.toolCalling.getAvailableTools():void 0;return a?new Promise((p,f)=>{let y="";this.networkClient.on("data",T=>{y+=T}),this.networkClient.on("done",()=>{p(y)}),this.networkClient.on("error",f),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return X.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let o=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n())})}}});import*as dn from"@sentry/node";dn.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as oi}from"commander";import Zo from"react";import{render as ei}from"ink";se();import h,{useState as cs,useEffect as Ze,useCallback as rn,useRef as No}from"react";import{Box as D,Text as E,useInput as Ro,useApp as Fo}from"ink";import $o from"ink-spinner";import ls from"ink-select-input";be();Qt();import le from"chalk";import wo from"ora";var te=class{static spinner=null;static formatUserMessage(e){return le.cyan("You: ")+e}static formatAssistantMessage(e){return le.green("Assistant: ")+e}static formatError(e){return le.red("Error: ")+e}static formatWarning(e){return le.yellow("Warning: ")+e}static formatInfo(e){return le.blue("Info: ")+e}static formatSuccess(e){return le.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=wo(e).start()}static updateSpinner(e){this.spinner&&(this.spinner.text=e)}static stopSpinner(e=!0,t){this.spinner&&(t?e?this.spinner.succeed(t):this.spinner.fail(t):this.spinner.stop(),this.spinner=null)}static clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}static printDivider(){console.log(le.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(le.bold.cyan(e)),console.log(le.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return le.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return le.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(le.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};B();Ne();import{EventEmitter as To}from"events";import Yt from"chalk";var It=class extends To{delegate=null;personalAgentService=ee.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let o=String(s[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s),r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
|
|
425
|
+
▸ ${s}`)}),this.personalAgentService.on("tool_completed",s=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:r,error:a}=s;console.log(r!==!1?`✓ ${o}`:`✗ ${o} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",s=>{}),this.personalAgentService.on("todo_update",s=>{}),this.personalAgentService.on("operator_progress",s=>{}),this.personalAgentService.on("webview_update",s=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(s.isStreaming=!1),o&&o.isStreaming&&(o.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",s=>{console.error(`
|
|
426
|
+
❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(i.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(s.content&&s.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${s.content.substring(0,50)}..."`),o.content=s.content,o.originalContent=s.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),s.completeWithTools&&(o.metadata={toolResults:s.completeWithTools}),o.isStreaming=!1,i.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(s.content&&s.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${s.content.substring(0,50)}..."`),r.content=s.content,r.originalContent=s.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),s.completeWithTools&&(r.metadata={toolResults:s.completeWithTools}),r.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t=!0){if(!this.delegate||!e.trim())return;let n=87500,s=e.trim();if(s.length>n){console.log(te.formatError(`Prompt too large (${s.length} characters). Please reduce it to ${n} characters or less.`));return}if(this.delegate.isLoading){let r=pe.getInstance();r.addToQueue({content:s,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Yt.blue(`⚡ Message queued (${r.getQueueCount()} in queue)`)),console.log(Yt.dim(" Your feedback will be sent when AI completes current task"))):console.log(Yt.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let o=null;this.delegate.isVisionEnabled&&(o=await _e.getInstance().captureScreen(),o?i.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${o.length} chars`):i.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision")),this.delegate.currentInput="";try{t?await this.processStreamingMessage(o):await this.processNonStreamingMessage(o)}catch(r){console.error(te.formatError(`Message failed: ${r.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",r.message)}}async processStreamingMessage(e){if(this.delegate)try{i.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(o=>!(o.isStreaming||o.role==="system"||!o.content||typeof o.content=="string"&&o.content.trim().length===0)).map(o=>({role:o.role,content:o.content})),n=this.delegate.fullConversationHistory.filter(o=>o.role==="user"),s=n[n.length-1];if(s)try{let o=e?[e]:void 0,r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,o,r),i.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(o){throw i.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${o.message}`),o}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let o=t.content;o.trim().length>0&&(o+=`
|
|
405
427
|
|
|
406
|
-
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let
|
|
407
|
-
`).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());r.length>0&&t.push({options:r})}let
|
|
428
|
+
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(o=>o.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,ee.getInstance().stopStreaming().catch(s=>{i.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};be();Mt();Ne();Ke();sn();De();ce();me();import on from"terminal-link";import{homedir as Do}from"os";function as(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",Do())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Ao(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function Pt(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let o=s;return!Ao(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(o=as(s)),on(n,o,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(s)?t:on(t,t,{fallback:(o,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(s)||s.includes("http"))return t;let o=as(t);return on(t,o,{fallback:(r,a)=>r})}),e}var Oo=0;function V(){return`msg-${Date.now()}-${++Oo}`}function _o(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(c))!==null;){let r=n[1].split(`
|
|
429
|
+
`).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());r.length>0&&t.push({options:r})}let s=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return s=s.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:s}}function Mo(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,s;for(;(s=e.exec(c))!==null;){let r=s[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],p=l[2];n.has(p)||(n.add(p),t.push({name:u,path:p}))}}let o=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return o=o.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:o}}function us(){let{exit:c}=Fo(),e=H.getInstance(),t=ee.getInstance(),n=pe.getInstance(),s=K.getInstance(),o=Ue.getInstance();Ze(()=>(_.enableCustomUI(),()=>_.disableCustomUI()),[]);let[r,a]=cs({messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
408
430
|
|
|
409
431
|
Your autonomous on-device AI agent.
|
|
410
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",isLoading:!1,loadingMessage:"Processing",mode:"prompt",showHelp:!1,showModelMenu:!1,showCommandMenu:!1,tokens:0,cost:0,selectedModel:X.find(d=>d.name===
|
|
432
|
+
Type a message to start.`,timestamp:Date.now()}],input:"",isLoading:!1,loadingMessage:"Processing",mode:"prompt",showHelp:!1,showModelMenu:!1,showCommandMenu:!1,tokens:0,cost:0,selectedModel:X.find(d=>d.name===Se.string("selectedPersonalModel"))||X.find(d=>d.name==="snowx-c5")||X[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=No(null),[u]=cs(()=>{let d={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:X.find(g=>g.name===Se.string("selectedPersonalModel"))||X.find(g=>g.name==="snowx-c5")||X[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new It(d)}),p=rn(async()=>{},[]);Ze(()=>{let d=r.messages.map(m=>({role:m.role,content:m.content,timestamp:new Date(m.timestamp||Date.now()),...m.tool&&{tool:m.tool},...m.toolOutput&&{toolOutput:m.toolOutput}})),g={messages:d,fullConversationHistory:d,isLoading:r.isLoading,currentInput:r.input,selectedModel:r.selectedModel,isVisionEnabled:r.isVisionEnabled,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:p};u.setDelegate(g)},[r.messages,r.selectedModel,r.isVisionEnabled,r.isLoading,r.input,r.conversationId,u,p]);let f=rn(async d=>{if(d.startsWith("/")){let v=d.toLowerCase().trim();if(v==="/help"||v==="/?"){a(x=>({...x,showCommandMenu:!0,input:""}));return}if(v==="/model"){a(x=>({...x,showModelMenu:!0,input:""}));return}if(v==="/clear"||v==="/new"){a(x=>({...x,messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
411
433
|
|
|
412
434
|
Your intelligent AI assistant.
|
|
413
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(
|
|
435
|
+
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(v==="/vision"){a(x=>({...x,isVisionEnabled:!x.isVisionEnabled,messages:[...x.messages,{id:V(),role:"system",content:`Vision mode ${x.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(v==="/exit"||v==="/quit"){c();return}if(v==="/stop"){r.isLoading?(t.stopStreaming(),a(x=>({...x,isLoading:!1,messages:[...x.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(x=>({...x,messages:[...x.messages,{id:V(),role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(v==="/signout"){a(x=>({...x,messages:[...x.messages,{id:V(),role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(A=>({...A,messages:[...A.messages,{id:V(),role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(A=>({...A,messages:[...A.messages,{id:V(),role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(x){a(A=>({...A,messages:[...A.messages,{id:V(),role:"system",content:`❌ Error: ${x.message}`,timestamp:Date.now()}]}))}return}a(x=>({...x,messages:[...x.messages,{id:V(),role:"system",content:`Unknown command: ${d}
|
|
414
436
|
|
|
415
|
-
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(r.isLoading){let
|
|
416
|
-
[TOOL:${w}]`;d+=I,a(F=>{let $=F.messages.map((O,ue)=>O.role==="assistant"&&!F.messages.slice(ue+1).some(G=>G.role==="assistant")?{...O,content:O.content+I}:O);return{...F,messages:$,loadingMessage:`${w}`}})},
|
|
437
|
+
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(r.isLoading){let v=n.addToQueue({content:d,imageUrls:[],attachments:[],model:r.selectedModel.name});a(v?x=>({...x,input:""}):x=>({...x,messages:[...x.messages,{id:V(),role:"system",content:"⚠️ Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let g=Date.now(),m={id:V(),role:"user",content:d,timestamp:g},C={id:V(),role:"assistant",content:"",timestamp:g+1},S=[...r.messages,m,C];a(v=>({...v,messages:S,input:"",isLoading:!0,loadingMessage:"Processing"}));let k=S.map(v=>({role:v.role,content:v.content,timestamp:new Date(v.timestamp||Date.now()),...v.tool&&{tool:v.tool},...v.toolOutput&&{toolOutput:v.toolOutput}}));u.setDelegate({messages:k,fullConversationHistory:k,isLoading:!1,currentInput:"",selectedModel:r.selectedModel,isVisionEnabled:r.isVisionEnabled,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:p});try{await u.sendMessage(d)}catch(v){a(x=>({...x,messages:[...x.messages,{id:V(),role:"system",content:`Error: ${v.message}`,timestamp:Date.now()}],isLoading:!1}))}},[r.isLoading,r.isVisionEnabled,r.selectedModel,n,u,e,c]),y=rn(()=>{if(!n.hasQueuedMessages())return;let d=n.processNextMessage();d&&(n.startProcessing(),f(d.content))},[n,f]);Ze(()=>{let d="",g=!1,m=!1,C=100,S=w=>{a(I=>({...I,conversationId:w.conversationId,conversationTitleGenerated:!!w.title}))},k=w=>{},v=()=>{a(w=>({...w,loadingMessage:"Processing"}))},x=()=>{if(m=!1,!g)return;g=!1;let w=d;a(I=>{let F=I.messages.map(($,O)=>$.role==="assistant"&&!I.messages.slice(O+1).some(re=>re.role==="assistant")?{...$,content:w}:$);return{...I,messages:F}})},A=w=>{d+=w,g=!0,m||(m=!0,setTimeout(x,C))},M=w=>{let I=`
|
|
438
|
+
[TOOL:${w}]`;d+=I,a(F=>{let $=F.messages.map((O,ue)=>O.role==="assistant"&&!F.messages.slice(ue+1).some(G=>G.role==="assistant")?{...O,content:O.content+I}:O);return{...F,messages:$,loadingMessage:`${w}`}})},q=w=>{if(w&&w.toolName&&w.result){let I="";typeof w.result=="string"?I=w.result:Array.isArray(w.result)?I=w.result.map(G=>typeof G=="string"?G:G&&typeof G=="object"?G.text||G.content||JSON.stringify(G):"").join(""):w.result.output?I=typeof w.result.output=="string"?w.result.output:JSON.stringify(w.result.output,null,2):w.result.content?I=w.result.content:I=JSON.stringify(w.result,null,2);let F=`<context>
|
|
417
439
|
${I}
|
|
418
|
-
</context>`;a(G=>{let j=G.messages.map((Z,
|
|
440
|
+
</context>`;a(G=>{let j=G.messages.map((Z,fe)=>{if(Z.role==="assistant"&&!G.messages.slice(fe+1).some(ne=>ne.role==="assistant")){let ne=Z.metadata?.toolResults;return{...Z,metadata:{...Z.metadata,toolResults:ne?ne+`
|
|
419
441
|
`+F:F}}}return Z});return{...G,messages:j}});let $=w.toolName.toLowerCase(),O="";if(I){let G=I.split(`
|
|
420
|
-
`).filter(J=>J.trim()),j=G.length,Z=I.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||I.match(/^\s*(\S+\.\w+)/m),he=Z?Z[1].split("/").pop():null;if($.includes("todo")){let J=w.todos;if(J&&Array.isArray(J)&&J.length>0){let se=J.filter(we=>we.status==="completed").length,We=J.filter(we=>we.status==="in_progress"||we.status==="inProgress");if(O=` ${se}/${J.length} done`,We.length>0){let we=We[0].text||We[0].content||"",bn=we.length>40?we.substring(0,40)+"…":we;O+=` → ${bn}`}}}else if($.includes("read"))he?O=` ${he} (${j} lines)`:O=` ${j} lines`;else if($.includes("write"))he?O=` ${he} ✓`:O=" ✓";else if($.includes("edit"))he?O=` ${he} ✓`:O=" ✓";else if($.includes("bash")||$.includes("command"))if(I.includes("error")||I.includes("Error"))O=" ✗ error";else if(j===0||j===1&&G[0].trim()==="")O=" ✓";else if(j<=3){let J=G.slice(0,2).join(" ").substring(0,50);O=j===1?` → ${J}`:` → ${J}…`}else O=` ✓ ${j} lines`;else if($.includes("grep")||$.includes("search")){let J=G.length;O=J>0?` ${J} matches`:" no matches"}else $.includes("glob")?O=` ${j} files`:$.includes("task")?O=" ✓":O=j>0?" ✓":""}let ue=`[TOOL:${w.toolName}]`,re=`[TOOL:${w.toolName}|${O.trim()}]`;d=d.replace(ue,re),a(G=>{let j=G.messages.map((Z,he)=>{if(Z.role==="assistant"&&!G.messages.slice(he+1).some(se=>se.role==="assistant")){let se=Z.content;if($.includes("todo")){let We=/\n\[TOOL:TodoWrite\][^\n]*/g;se=se.replace(We,"")}return se=se.replace(ue,re),{...Z,content:se}}return Z});return{...G,messages:j}})}},P=()=>{if(g){g=!1,m=!1;let w=d;a(I=>{let F=I.messages.map(($,O)=>$.role==="assistant"&&!I.messages.slice(O+1).some(re=>re.role==="assistant")?{...$,content:w}:$);return{...I,messages:F,isLoading:!1}})}else a(w=>({...w,isLoading:!1}));d=""},A=w=>{a(I=>({...I,messages:[...I.messages,{id:V(),role:"system",content:`Error: ${w.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),d=""};return t.on("conversation_id_received",x),t.on("conversation_title_updated",E),t.on("thinking",y),t.on("data",R),t.on("toolExecuting",L),t.on("tool_completed",z),t.on("done",P),t.on("error",A),()=>{t.off("conversation_id_received",x),t.off("conversation_title_updated",E),t.off("thinking",y),t.off("data",R),t.off("toolExecuting",L),t.off("tool_completed",z),t.off("done",P),t.off("error",A)}},[t,v]),Ze(()=>{let d=x=>{a(E=>({...E,queuedMessages:x}))},g=x=>{},m=x=>{l.current=x,a(E=>({...E,todoList:x}))},S=x=>{if(r.isLoading){s.addToQueue({content:x.prompt,imageUrls:[],attachments:[],model:r.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:x.taskId})||a(y=>({...y,messages:[...y.messages,{id:V(),role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(x.prompt)};return s.on("queue:updated",d),n.on("feedback:sent",g),t.on("todo_update",m),o.on("CrossDeviceTaskSendMessage",S),()=>{s.off("queue:updated",d),n.off("feedback:sent",g),t.off("todo_update",m),o.off("CrossDeviceTaskSendMessage",S)}},[s,n,t,o,f,r.isLoading,r.selectedModel.name]),Ze(()=>{!r.isLoading&&s.hasQueuedMessages()&&v()},[r.isLoading,s,v]),Ao((d,g)=>{if(g.escape){if(r.isLoading){t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(r.showModelMenu||r.showCommandMenu){a(m=>({...m,showModelMenu:!1,showCommandMenu:!1,input:m.showCommandMenu&&m.input==="/"?"":m.input}));return}if(r.showHelp){a(m=>({...m,showHelp:!1}));return}}if(!r.showModelMenu){if(g.ctrl&&d==="c"){r.isLoading?(t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(d==="?"&&r.input===""){a(m=>({...m,showHelp:!m.showHelp}));return}if(g.return&&!r.showCommandMenu){r.input.trim()&&f(r.input);return}if(g.delete||g.backspace){a(m=>{let S=m.input.slice(0,-1);return m.showCommandMenu&&!S.startsWith("/")?{...m,input:S,showCommandMenu:!1}:{...m,input:S}});return}!g.ctrl&&!g.meta&&d&&a(m=>{let S=m.input+d;return S==="/"&&!m.showCommandMenu?{...m,input:S,showCommandMenu:!0}:{...m,input:S}})}});let b=e.getUserEmail()||"User",T=ie.getDisplayName(ie.getCurrentUserTier());return h.createElement(D,{flexDirection:"column",width:"100%"},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},h.createElement(C,{color:"white"},r.selectedModel.displayName),h.createElement(C,{color:"gray",dimColor:!0}," • "),h.createElement(C,{color:"gray"},b),h.createElement(C,{color:"gray",dimColor:!0}," • "),h.createElement(C,{color:"white"},T),r.queuedMessages.length>0&&h.createElement(h.Fragment,null,h.createElement(C,{color:"gray",dimColor:!0}," • "),h.createElement(C,{color:"white",inverse:!0,bold:!0}," ",r.queuedMessages.length," "),h.createElement(C,{color:"gray"}," queued")),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(h.Fragment,null,h.createElement(C,{color:"gray",dimColor:!0}," • "),h.createElement(C,{color:"blue",inverse:!0,bold:!0}," 📱 ",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," "),h.createElement(C,{color:"gray"}," cross-device"))),h.createElement(D,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},r.messages.map(d=>h.createElement(Lo,{key:d.id,message:d,onSuggestionClick:g=>{a(m=>({...m,input:g}))}}))),r.todoList&&r.todoList.todos.length>0&&r.todoList.todos.some(d=>d.status!=="completed")&&h.createElement(D,{paddingX:2,marginBottom:1},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(D,{marginBottom:1},h.createElement(C,{color:"white",bold:!0},"Tasks"),h.createElement(C,{color:"gray"}," • "),h.createElement(C,{color:"gray"},r.todoList.todos.filter(d=>d.status==="completed").length,"/",r.todoList.todos.length)),r.todoList.todos.map((d,g)=>{let m=d.status==="completed"?"✓":d.status==="in_progress"?"⋯":"○",S=d.status==="completed"?"green":d.status==="in_progress"?"blue":"gray";return h.createElement(D,{key:d.id||g},h.createElement(C,{color:S},m),h.createElement(C,{color:"gray"}," "),h.createElement(C,{color:d.status==="completed"?"gray":"white",dimColor:d.status==="completed"},d.status==="in_progress"&&d.activeForm?d.activeForm:d.text))}))),r.isLoading&&h.createElement(D,{paddingX:0,marginBottom:1,flexDirection:"column"},h.createElement(D,null,h.createElement(C,{color:"magenta"},h.createElement(Ro,{type:"dots"})),h.createElement(C,{color:"white"}," ",r.loadingMessage,"… "),h.createElement(C,{color:"white"},"(esc to interrupt)")),h.createElement(D,{marginLeft:2},h.createElement(C,{color:"yellow"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),r.showHelp&&h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(C,{bold:!0,color:"white"},"Keyboard Shortcuts"),h.createElement(D,{marginTop:1,flexDirection:"column"},h.createElement(C,{color:"white"},"• ",h.createElement(C,{color:"white",bold:!0},"Enter")," ",h.createElement(C,{color:"white"},"Submit message")),h.createElement(C,{color:"white"},"• ",h.createElement(C,{color:"white",bold:!0},"?")," ",h.createElement(C,{color:"white"},"Toggle this help")),h.createElement(C,{color:"white"},"• ",h.createElement(C,{color:"white",bold:!0},"Esc")," ",h.createElement(C,{color:"white"},"Stop generation / Close menus")),h.createElement(C,{color:"white"},"• ",h.createElement(C,{color:"white",bold:!0},"Ctrl+C")," ",h.createElement(C,{color:"white"},"Stop generation / Exit"))),h.createElement(D,{marginTop:1},h.createElement(C,{color:"white"},"Press Esc to close"))),r.showModelMenu&&(()=>{let d=ie.getCurrentUserTier(),g=X.filter(y=>y.name.startsWith("snowx-o4")||y.name.startsWith("snowx-c")||y.name.startsWith("snowx-h")),m=X.filter(y=>y.name.startsWith("snowx-5")||y.name.startsWith("snowx-o3")||y.name.startsWith("snowx-4")),S=X.filter(y=>y.name.startsWith("snowx-g")),x=y=>y.map(k=>{let R=ie.isModelAccessible(k.name,d);return{label:R?k.displayName:`🔒 ${k.displayName}`,value:k.name,isAccessible:R}}),E=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1},...x(g),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1},...x(m),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1},...x(S)];return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(C,{bold:!0,color:"white"},"Select Model"),h.createElement(C,{color:"gray",dimColor:!0},"Tier: ",ie.getDisplayName(d)),h.createElement(D,{marginTop:1},h.createElement(rn,{items:E.map(y=>({label:y.label,value:y.value})),onSelect:y=>{if(y.value.startsWith("_"))return;if(!E.find(L=>L.value===y.value)?.isAccessible){a(L=>({...L,messages:[...L.messages,{id:V(),role:"system",content:ie.getAccessDeniedMessage(y.value),timestamp:Date.now()}]}));return}let R=X.find(L=>L.name===y.value);R&&(Te.set("selectedPersonalModel",R.name),a(L=>({...L,selectedModel:R,showModelMenu:!1,messages:[...L.messages,{id:V(),role:"system",content:`Switched to ${R.displayName}`,timestamp:Date.now()}]})))}})),h.createElement(D,{marginTop:1},h.createElement(C,{color:"white"},"Esc to cancel")))})(),r.showCommandMenu&&(()=>{let d=[{label:"/model — Change AI model",value:"model"},{label:"/new — Start new conversation",value:"new"},{label:"/clear — Clear conversation",value:"clear"},{label:"/stop — Stop current generation",value:"stop"},{label:"/vision — Toggle vision mode",value:"vision"},{label:"/signout — Sign out and exit",value:"signout"},{label:"/exit — Exit Orion",value:"exit"},{label:"/help — Show this menu",value:"help"}],g=r.input.startsWith("/")?r.input.substring(1).toLowerCase():"",m=g?d.filter(S=>S.value.toLowerCase().includes(g)):d;return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(C,{bold:!0,color:"white"},"Available Commands ",g&&`(filtered: "${g}")`),h.createElement(D,{marginTop:1},h.createElement(rn,{items:m.length>0?m:[{label:"No matching commands",value:""}],onSelect:S=>{S.value&&(a(x=>({...x,showCommandMenu:!1,input:""})),f(`/${S.value}`))}})),h.createElement(D,{marginTop:1},h.createElement(C,{color:"white"},"Esc to cancel")))})(),r.queuedMessages.length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.map((d,g)=>h.createElement(D,{key:d.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(C,{color:"white",bold:!0},g+1),h.createElement(C,{color:"white"}," • "),h.createElement(C,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(C,{color:"white"},r.queuedMessages.length," message",r.queuedMessages.length>1?"s":""," queued"))),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.filter(d=>d.isCrossDeviceTask).map((d,g)=>h.createElement(D,{key:`cross-${d.id}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(C,{color:"blue",bold:!0},"📱 ",g+1),h.createElement(C,{color:"white"}," • "),h.createElement(C,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(C,{color:"blue"},r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," cross-device task",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>1?"s":""," waiting"))),h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},h.createElement(D,null,h.createElement(C,{color:"white"},"▶ "),h.createElement(C,{color:"white"},r.input,!r.isLoading&&h.createElement(C,{color:"white",inverse:!0}," "))),h.createElement(D,{marginTop:0},h.createElement(C,{color:"white"},r.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),h.createElement(D,{paddingX:2,paddingY:0},h.createElement(C,{color:"white"},"? help · Ctrl+C exit")))}function _o(c){let e=c;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/\*(.+?)\*/g,"$1"),e=e.replace(/_(.+?)_/g,"$1"),e=e.replace(/`(.+?)`/g,"$1"),e=Pt(e),e}function Mo({suggestions:c,onSelect:e}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},c.map((t,s)=>h.createElement(D,{key:`sug-block-${s}-${t.options.join(",").slice(0,20)}`,flexWrap:"wrap",gap:1},t.options.map(n=>h.createElement(D,{key:`sug-opt-${n.slice(0,30)}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(C,{color:"cyan"},n))))),e&&h.createElement(D,{marginTop:0},h.createElement(C,{color:"gray",dimColor:!0},"Type a suggestion to use it")))}function Uo({workingFiles:c}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},h.createElement(D,{marginBottom:0},h.createElement(C,{color:"gray",bold:!0},"Working Files"),h.createElement(C,{color:"gray",dimColor:!0}," (",c.length,")")),h.createElement(D,{flexWrap:"wrap",gap:1},c.map(e=>h.createElement(D,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(C,{color:"white"},e.name)))))}function Lo({message:c,onSuggestionClick:e}){let{role:t,content:s,tool:n}=c;if(t==="system"){let o=s.split(`
|
|
421
|
-
`);return h.createElement(D,{marginBottom:1,marginTop:1,flexDirection:"column"},h.createElement(D,null,h.createElement(
|
|
422
|
-
`);return h.createElement(D,{key:`text-${g}-${d.content.slice(0,15)}`,flexDirection:"column",paddingLeft:1},m.map((S
|
|
423
|
-
🔐 Orion Authentication`)),console.log(
|
|
424
|
-
📋 To authenticate, please follow these steps:`)),console.log(
|
|
425
|
-
Paste your access token here:`));let{accessToken:t}=await
|
|
426
|
-
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let
|
|
427
|
-
✅ Authentication successful!`)),
|
|
428
|
-
❌ Authentication failed. Please try again.`))}catch(
|
|
429
|
-
❌ Authentication error: ${
|
|
430
|
-
🔄 Signing out...`)),console.log(
|
|
431
|
-
✅ Successfully signed out`)),console.log(
|
|
432
|
-
❌ Logout failed`)),console.log(
|
|
433
|
-
✅ Authenticated`)),t){console.log(
|
|
434
|
-
Usage:`)),console.log(
|
|
435
|
-
⚠️ Not authenticated`)),console.log(
|
|
436
|
-
❌ Failed to initialize services:`,
|
|
442
|
+
`).filter(J=>J.trim()),j=G.length,Z=I.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||I.match(/^\s*(\S+\.\w+)/m),fe=Z?Z[1].split("/").pop():null;if($.includes("todo")){let J=w.todos;if(J&&Array.isArray(J)&&J.length>0){let ne=J.filter(Te=>Te.status==="completed").length,We=J.filter(Te=>Te.status==="in_progress"||Te.status==="inProgress");if(O=` ${ne}/${J.length} done`,We.length>0){let Te=We[0].text||We[0].content||"",Ss=Te.length>40?Te.substring(0,40)+"…":Te;O+=` → ${Ss}`}}}else if($.includes("read"))fe?O=` ${fe} (${j} lines)`:O=` ${j} lines`;else if($.includes("write"))fe?O=` ${fe} ✓`:O=" ✓";else if($.includes("edit"))fe?O=` ${fe} ✓`:O=" ✓";else if($.includes("bash")||$.includes("command"))if(I.includes("error")||I.includes("Error"))O=" ✗ error";else if(j===0||j===1&&G[0].trim()==="")O=" ✓";else if(j<=3){let J=G.slice(0,2).join(" ").substring(0,50);O=j===1?` → ${J}`:` → ${J}…`}else O=` ✓ ${j} lines`;else if($.includes("grep")||$.includes("search")){let J=G.length;O=J>0?` ${J} matches`:" no matches"}else $.includes("glob")?O=` ${j} files`:$.includes("task")?O=" ✓":O=j>0?" ✓":""}let ue=`[TOOL:${w.toolName}]`,re=`[TOOL:${w.toolName}|${O.trim()}]`;d=d.replace(ue,re),a(G=>{let j=G.messages.map((Z,fe)=>{if(Z.role==="assistant"&&!G.messages.slice(fe+1).some(ne=>ne.role==="assistant")){let ne=Z.content;if($.includes("todo")){let We=/\n\[TOOL:TodoWrite\][^\n]*/g;ne=ne.replace(We,"")}return ne=ne.replace(ue,re),{...Z,content:ne}}return Z});return{...G,messages:j}})}},P=()=>{if(g){g=!1,m=!1;let w=d;a(I=>{let F=I.messages.map(($,O)=>$.role==="assistant"&&!I.messages.slice(O+1).some(re=>re.role==="assistant")?{...$,content:w}:$);return{...I,messages:F,isLoading:!1}})}else a(w=>({...w,isLoading:!1}));d=""},N=w=>{a(I=>({...I,messages:[...I.messages,{id:V(),role:"system",content:`Error: ${w.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),d=""};return t.on("conversation_id_received",S),t.on("conversation_title_updated",k),t.on("thinking",v),t.on("data",A),t.on("toolExecuting",M),t.on("tool_completed",q),t.on("done",P),t.on("error",N),()=>{t.off("conversation_id_received",S),t.off("conversation_title_updated",k),t.off("thinking",v),t.off("data",A),t.off("toolExecuting",M),t.off("tool_completed",q),t.off("done",P),t.off("error",N)}},[t,y]),Ze(()=>{let d=S=>{a(k=>({...k,queuedMessages:S}))},g=S=>{},m=S=>{l.current=S,a(k=>({...k,todoList:S}))},C=S=>{if(r.isLoading){n.addToQueue({content:S.prompt,imageUrls:[],attachments:[],model:r.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:S.taskId})||a(v=>({...v,messages:[...v.messages,{id:V(),role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(S.prompt)};return n.on("queue:updated",d),s.on("feedback:sent",g),t.on("todo_update",m),o.on("CrossDeviceTaskSendMessage",C),()=>{n.off("queue:updated",d),s.off("feedback:sent",g),t.off("todo_update",m),o.off("CrossDeviceTaskSendMessage",C)}},[n,s,t,o,f,r.isLoading,r.selectedModel.name]),Ze(()=>{!r.isLoading&&n.hasQueuedMessages()&&y()},[r.isLoading,n,y]),Ro((d,g)=>{if(g.escape){if(r.isLoading){t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(r.showModelMenu||r.showCommandMenu){a(m=>({...m,showModelMenu:!1,showCommandMenu:!1,input:m.showCommandMenu&&m.input==="/"?"":m.input}));return}if(r.showHelp){a(m=>({...m,showHelp:!1}));return}}if(!r.showModelMenu){if(g.ctrl&&d==="c"){r.isLoading?(t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(d==="?"&&r.input===""){a(m=>({...m,showHelp:!m.showHelp}));return}if(g.return&&!r.showCommandMenu){r.input.trim()&&f(r.input);return}if(g.delete||g.backspace){a(m=>{let C=m.input.slice(0,-1);return m.showCommandMenu&&!C.startsWith("/")?{...m,input:C,showCommandMenu:!1}:{...m,input:C}});return}!g.ctrl&&!g.meta&&d&&a(m=>{let C=m.input+d;return C==="/"&&!m.showCommandMenu?{...m,input:C,showCommandMenu:!0}:{...m,input:C}})}});let T=e.getUserEmail()||"User",b=ie.getDisplayName(ie.getCurrentUserTier());return h.createElement(D,{flexDirection:"column",width:"100%"},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},h.createElement(E,{color:"white"},r.selectedModel.displayName),h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"gray"},T),h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"white"},b),r.queuedMessages.length>0&&h.createElement(h.Fragment,null,h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"white",inverse:!0,bold:!0}," ",r.queuedMessages.length," "),h.createElement(E,{color:"gray"}," queued")),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(h.Fragment,null,h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"blue",inverse:!0,bold:!0}," 📱 ",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," "),h.createElement(E,{color:"gray"}," cross-device"))),h.createElement(D,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},r.messages.map(d=>h.createElement(Bo,{key:d.id,message:d,onSuggestionClick:g=>{a(m=>({...m,input:g}))}}))),r.todoList&&r.todoList.todos.length>0&&r.todoList.todos.some(d=>d.status!=="completed")&&h.createElement(D,{paddingX:2,marginBottom:1},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(D,{marginBottom:1},h.createElement(E,{color:"white",bold:!0},"Tasks"),h.createElement(E,{color:"gray"}," • "),h.createElement(E,{color:"gray"},r.todoList.todos.filter(d=>d.status==="completed").length,"/",r.todoList.todos.length)),r.todoList.todos.map((d,g)=>{let m=d.status==="completed"?"✓":d.status==="in_progress"?"⋯":"○",C=d.status==="completed"?"green":d.status==="in_progress"?"blue":"gray";return h.createElement(D,{key:d.id||g},h.createElement(E,{color:C},m),h.createElement(E,{color:"gray"}," "),h.createElement(E,{color:d.status==="completed"?"gray":"white",dimColor:d.status==="completed"},d.status==="in_progress"&&d.activeForm?d.activeForm:d.text))}))),r.isLoading&&h.createElement(D,{paddingX:0,marginBottom:1,flexDirection:"column"},h.createElement(D,null,h.createElement(E,{color:"magenta"},h.createElement($o,{type:"dots"})),h.createElement(E,{color:"white"}," ",r.loadingMessage,"… "),h.createElement(E,{color:"white"},"(esc to interrupt)")),h.createElement(D,{marginLeft:2},h.createElement(E,{color:"yellow"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),r.showHelp&&h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Keyboard Shortcuts"),h.createElement(D,{marginTop:1,flexDirection:"column"},h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Enter")," ",h.createElement(E,{color:"white"},"Submit message")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"?")," ",h.createElement(E,{color:"white"},"Toggle this help")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Esc")," ",h.createElement(E,{color:"white"},"Stop generation / Close menus")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Ctrl+C")," ",h.createElement(E,{color:"white"},"Stop generation / Exit"))),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Press Esc to close"))),r.showModelMenu&&(()=>{let d=ie.getCurrentUserTier(),g=X.filter(v=>v.name.startsWith("snowx-o4")||v.name.startsWith("snowx-c")||v.name.startsWith("snowx-h")),m=X.filter(v=>v.name.startsWith("snowx-5")||v.name.startsWith("snowx-o3")||v.name.startsWith("snowx-4")),C=X.filter(v=>v.name.startsWith("snowx-g")),S=v=>v.map(x=>{let A=ie.isModelAccessible(x.name,d);return{label:A?x.displayName:`🔒 ${x.displayName}`,value:x.name,isAccessible:A}}),k=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1},...S(g),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1},...S(m),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1},...S(C)];return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Select Model"),h.createElement(E,{color:"gray",dimColor:!0},"Tier: ",ie.getDisplayName(d)),h.createElement(D,{marginTop:1},h.createElement(ls,{items:k.map(v=>({label:v.label,value:v.value})),onSelect:v=>{if(v.value.startsWith("_"))return;if(!k.find(M=>M.value===v.value)?.isAccessible){a(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:ie.getAccessDeniedMessage(v.value),timestamp:Date.now()}]}));return}let A=X.find(M=>M.name===v.value);A&&(Se.set("selectedPersonalModel",A.name),a(M=>({...M,selectedModel:A,showModelMenu:!1,messages:[...M.messages,{id:V(),role:"system",content:`Switched to ${A.displayName}`,timestamp:Date.now()}]})))}})),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Esc to cancel")))})(),r.showCommandMenu&&(()=>{let d=[{label:"/model — Change AI model",value:"model"},{label:"/new — Start new conversation",value:"new"},{label:"/clear — Clear conversation",value:"clear"},{label:"/stop — Stop current generation",value:"stop"},{label:"/vision — Toggle vision mode",value:"vision"},{label:"/signout — Sign out and exit",value:"signout"},{label:"/exit — Exit Orion",value:"exit"},{label:"/help — Show this menu",value:"help"}],g=r.input.startsWith("/")?r.input.substring(1).toLowerCase():"",m=g?d.filter(C=>C.value.toLowerCase().includes(g)):d;return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Available Commands ",g&&`(filtered: "${g}")`),h.createElement(D,{marginTop:1},h.createElement(ls,{items:m.length>0?m:[{label:"No matching commands",value:""}],onSelect:C=>{C.value&&(a(S=>({...S,showCommandMenu:!1,input:""})),f(`/${C.value}`))}})),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Esc to cancel")))})(),r.queuedMessages.length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.map((d,g)=>h.createElement(D,{key:d.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(E,{color:"white",bold:!0},g+1),h.createElement(E,{color:"white"}," • "),h.createElement(E,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(E,{color:"white"},r.queuedMessages.length," message",r.queuedMessages.length>1?"s":""," queued"))),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.filter(d=>d.isCrossDeviceTask).map((d,g)=>h.createElement(D,{key:`cross-${d.id}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(E,{color:"blue",bold:!0},"📱 ",g+1),h.createElement(E,{color:"white"}," • "),h.createElement(E,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(E,{color:"blue"},r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," cross-device task",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>1?"s":""," waiting"))),h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},h.createElement(D,null,h.createElement(E,{color:"white"},"▶ "),h.createElement(E,{color:"white"},r.input,!r.isLoading&&h.createElement(E,{color:"white",inverse:!0}," "))),h.createElement(D,{marginTop:0},h.createElement(E,{color:"white"},r.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),h.createElement(D,{paddingX:2,paddingY:0},h.createElement(E,{color:"white"},"? help · Ctrl+C exit")))}function Uo(c){let e=c;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/\*(.+?)\*/g,"$1"),e=e.replace(/_(.+?)_/g,"$1"),e=e.replace(/`(.+?)`/g,"$1"),e=Pt(e),e}function Lo({suggestions:c,onSelect:e}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},c.map((t,n)=>h.createElement(D,{key:`sug-block-${n}-${t.options.join(",").slice(0,20)}`,flexWrap:"wrap",gap:1},t.options.map(s=>h.createElement(D,{key:`sug-opt-${s.slice(0,30)}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(E,{color:"cyan"},s))))),e&&h.createElement(D,{marginTop:0},h.createElement(E,{color:"gray",dimColor:!0},"Type a suggestion to use it")))}function Wo({workingFiles:c}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},h.createElement(D,{marginBottom:0},h.createElement(E,{color:"gray",bold:!0},"Working Files"),h.createElement(E,{color:"gray",dimColor:!0}," (",c.length,")")),h.createElement(D,{flexWrap:"wrap",gap:1},c.map(e=>h.createElement(D,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(E,{color:"white"},e.name)))))}function Bo({message:c,onSuggestionClick:e}){let{role:t,content:n,tool:s}=c;if(t==="system"){let o=n.split(`
|
|
443
|
+
`);return h.createElement(D,{marginBottom:1,marginTop:1,flexDirection:"column"},h.createElement(D,null,h.createElement(E,{color:"gray",dimColor:!0},"System")),h.createElement(D,{paddingLeft:1,flexDirection:"column"},o.map((r,a)=>h.createElement(E,{key:`sys-${a}-${r.slice(0,20)}`,color:"gray"},r))))}if(t==="user")return h.createElement(D,{marginBottom:1,marginTop:1,flexDirection:"column"},h.createElement(D,null,h.createElement(E,{color:"blue",bold:!0},"You")),h.createElement(D,{paddingLeft:1},h.createElement(E,{color:"white"},n)));if(t==="assistant"){let{suggestions:o,cleanedContent:r}=_o(n),{workingFiles:a,cleanedContent:l}=Mo(r),u=[],p=l.split(/(\[TOOL:[^\]]+\])/);for(let d of p){if(!d)continue;let g=d.match(/^\[TOOL:([^|\]]+)(?:\|([^\]]*))?\]$/);g?u.push({type:"tool",content:d,toolName:g[1],toolResult:g[2]||""}):d.trim()&&u.push({type:"text",content:d})}let f=d=>{let g=d.toLowerCase();return g.includes("read")?{icon:"◆",color:"cyan"}:g.includes("write")?{icon:"◇",color:"green"}:g.includes("edit")?{icon:"✎",color:"yellow"}:g.includes("bash")||g.includes("command")?{icon:"▸",color:"magenta"}:g.includes("grep")||g.includes("search")?{icon:"⌕",color:"blue"}:g.includes("glob")?{icon:"⊕",color:"blue"}:g.includes("todo")?{icon:"☰",color:"cyan"}:g.includes("task")?{icon:"◈",color:"magenta"}:g.includes("web")?{icon:"◎",color:"blue"}:{icon:"●",color:"gray"}},y=u.some(d=>d.type==="tool"),T=u.filter(d=>d.type==="text"),b=u.filter(d=>d.type==="tool");return h.createElement(D,{marginBottom:1,flexDirection:"column"},h.createElement(D,{marginBottom:0},h.createElement(E,{color:"green",bold:!0},"Orion")),T.map((d,g)=>{let m=d.content.split(`
|
|
444
|
+
`);return h.createElement(D,{key:`text-${g}-${d.content.slice(0,15)}`,flexDirection:"column",paddingLeft:1},m.map((C,S)=>C.trim()===""?h.createElement(E,{key:`ln-${S}-empty`}," "):h.createElement(E,{key:`ln-${S}-${C.slice(0,15)}`,color:"white"},Uo(C))))}),y&&b.length>0&&h.createElement(D,{flexDirection:"column",marginTop:1,paddingLeft:1},b.map((d,g)=>{let m=f(d.toolName||""),C=d.toolResult&&d.toolResult.length>0,S=d.toolResult?.includes("✓"),k=d.toolResult?.includes("✗")||d.toolResult?.includes("error");return h.createElement(D,{key:`tool-${g}-${d.toolName}`},h.createElement(E,{color:m.color},m.icon),h.createElement(E,{color:"gray"}," ",d.toolName),C&&h.createElement(E,{color:k?"red":S?"green":"gray"}," ",d.toolResult),!C&&h.createElement(E,{color:"gray",dimColor:!0}," …"))})),a.length>0&&h.createElement(Wo,{workingFiles:a}),o.length>0&&h.createElement(Lo,{suggestions:o,onSelect:e}))}return null}cn();se();se();import L from"chalk";import Yo from"inquirer";var Pe=class{authService;constructor(){this.authService=H.getInstance()}async login(){console.log(L.blue(`
|
|
445
|
+
🔐 Orion Authentication`)),console.log(L.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(L.yellow(`
|
|
446
|
+
📋 To authenticate, please follow these steps:`)),console.log(L.white("1. Open this URL in a browser (on any device):")),console.log(L.cyan.underline(` ${e}`)),console.log(L.white("2. Log in with your Orion account")),console.log(L.white("3. Copy the access token shown after login")),console.log(L.white("4. Paste the token below")),console.log(L.yellow(`
|
|
447
|
+
Paste your access token here:`));let{accessToken:t}=await Yo.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(L.gray(`
|
|
448
|
+
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(L.green(`
|
|
449
|
+
✅ Authentication successful!`)),s&&(console.log(L.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(L.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(L.red(`
|
|
450
|
+
❌ Authentication failed. Please try again.`))}catch(n){console.log(L.red(`
|
|
451
|
+
❌ Authentication error: ${n.message}`))}}async logout(){console.log(L.yellow(`
|
|
452
|
+
🔄 Signing out...`)),console.log(L.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(L.green(`
|
|
453
|
+
✅ Successfully signed out`)),console.log(L.gray("All authentication data and settings have been cleared.")),console.log(L.gray('Run "orion auth login" to sign in again.'))):(console.log(L.red(`
|
|
454
|
+
❌ Logout failed`)),console.log(L.gray("Some cleanup operations may have failed, but local data has been cleared.")))}async status(){if(await this.authService.autoAuthenticate(),this.authService.isAuthenticated()){let t=await this.authService.getUserInfo();if(console.log(L.green(`
|
|
455
|
+
✅ Authenticated`)),t){console.log(L.gray("─".repeat(50))),console.log(L.white("User:",t.name||t.username||"N/A")),console.log(L.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(L.white("Subscription:",n)),t.usage&&(console.log(L.gray(`
|
|
456
|
+
Usage:`)),console.log(L.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(L.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(L.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(L.yellow(`
|
|
457
|
+
⚠️ Not authenticated`)),console.log(L.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};me();var bs=!1;async function ln(){if(bs){console.log("Already running...");return}bs=!0,_.enableCustomUI();let c=et.getInstance(),e=H.getInstance();if(!c.isInitialized()){console.log("🔧 Initializing Orion services...");try{await c.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(n){console.error(`
|
|
458
|
+
❌ Failed to initialize services:`,n.message),console.error(`
|
|
437
459
|
💡 Tip: Check your internet connection and Firebase configuration.
|
|
438
460
|
`),process.exit(1)}}(!await e.autoAuthenticate()||!e.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
|
|
439
|
-
`),await new
|
|
461
|
+
`),await new Pe().login(),e.isAuthenticated()||(console.error(`
|
|
440
462
|
❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
|
|
441
463
|
✨ Starting Orion CLI...
|
|
442
464
|
`)),e.isFirebaseAuthenticated()||(console.error(`
|
|
443
465
|
❌ Firebase authentication failed.`),console.error("This may be due to:"),console.error(" 1. Network connectivity issues"),console.error(" 2. Firewall blocking Firebase services (firebaseio.com)"),console.error(" 3. Temporary server issues"),console.error(`
|
|
444
466
|
Please check your connection and try again.
|
|
445
|
-
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),
|
|
446
|
-
`)),process.exit(0)}catch(t){i.debug("Auto-update failed:",t)}}async checkForUpdates(){try{let e=await this.fetchLatestVersion();return{hasUpdate:this.isNewerVersion(e,this.currentVersion),latestVersion:e}}catch(e){return i.debug("Update check failed:",e),{hasUpdate:!1}}}};import
|
|
467
|
+
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),ei(Zo.createElement(us),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1})}De();B();import{EventEmitter as ti}from"events";import ni from"axios";import{execSync as si}from"child_process";import ws from"chalk";var Nt=class c extends ti{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;constructor(e){super(),this.currentVersion=e}static getInstance(e){return c.instance||(c.instance=new c(e)),c.instance}async checkAndUpdate(){if(!this.isChecking){this.isChecking=!0;try{let e=await this.fetchLatestVersion();this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):i.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){i.debug("Update check failed:",e)}finally{this.isChecking=!1}}}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`;return(await ni.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let n=e.split(".").map(Number),s=t.split(".").map(Number);for(let o=0;o<3;o++){let r=n[o]||0,a=s[o]||0;if(r>a)return!0;if(r<a)return!1}return!1}async performUpdate(e){try{let t=`npm install -g ${this.packageName}@latest`;i.debug(`Auto-updating from ${this.currentVersion} to ${e}`),si(t,{stdio:"pipe",encoding:"utf8"}),console.log(ws.green(`✓ Updated to v${e}`)+ws.gray(` - restarting...
|
|
468
|
+
`)),process.exit(0)}catch(t){i.debug("Auto-update failed:",t)}}async checkForUpdates(){try{let e=await this.fetchLatestVersion();return{hasUpdate:this.isNewerVersion(e,this.currentVersion),latestVersion:e}}catch(e){return i.debug("Update check failed:",e),{hasUpdate:!1}}}};import ii from"dotenv";import{fileURLToPath as ri}from"url";import{dirname as ai,join as ci}from"path";import{readFileSync as li}from"fs";ii.config();var ui=ri(import.meta.url),di=ai(ui),Ts=JSON.parse(li(ci(di,"..","package.json"),"utf8")),pi=Nt.getInstance(Ts.version);pi.checkAndUpdate().catch(()=>{});var Le=new oi;Le.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Ts.version);Le.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await ln()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});Le.command("ask <question>").description("Ask a single question (Advanced Mode with Orion features)").option("-m, --model <model>","Select AI model","snowx-5c").option("-s, --stream","Enable streaming response",!0).action(async(c,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(cn(),ys)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=X.find(r=>r.name===e.model)||X[0];console.log("💭 Sending message...");let o=await n.sendMessage(c,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Pt(o))}catch(t){te.stopSpinner(!1),console.error(te.formatError(t.message)),process.exit(1)}});var un=Le.command("auth").description("Authentication commands");un.command("login").description("Login to Orion").action(async()=>{try{await new Pe().login()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});un.command("logout").description("Logout from Orion").action(async()=>{try{await new Pe().logout()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});un.command("status").description("Check authentication status").action(async()=>{try{await new Pe().status()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});Le.command("models").description("List available AI models").action(()=>{te.printHeader("Available Models");for(let c of X)console.log(`${te.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?ln().catch(c=>{console.error(te.formatError(c.message)),process.exit(1)}):Le.parse(process.argv);
|