@zinley/orion 1.2.10 → 1.2.11
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 +131 -131
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Et=Object.defineProperty;var mn=Object.getOwnPropertyDescriptor;var gn=Object.getOwnPropertyNames;var hn=Object.prototype.hasOwnProperty;var fn=(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 F=(c,e)=>()=>(c&&(e=c(c=0)),e);var se=(c,e)=>{for(var t in e)Et(c,t,{get:e[t],enumerable:!0})},vn=(c,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gn(e))!hn.call(c,n)&&n!==t&&Et(c,n,{get:()=>e[n],enumerable:!(s=mn(e,n))||s.enumerable});return c};var yn=c=>vn(Et({},"__esModule",{value:!0}),c);var ls={};se(ls,{AccountStatus:()=>cs,SNOWX_MODELS:()=>X,SignUpMethod:()=>as,SnowXProvider:()=>It,TaskStatus:()=>rs,TodoStatus:()=>is});var It,X,is,rs,as,cs,Se=F(()=>{"use strict";It=(r=>(r.GPT="GPT",r.BEDROCK="BEDROCK",r.ANTHROPIC="ANTHROPIC",r.OPENAI="OPENAI",r.FOUNDRY="FOUNDRY",r.GOOGLE="google",r))(It||{}),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}],is=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s))(is||{}),rs=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(rs||{}),as=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(as||{}),cs=(s=>(s.ACTIVE="active",s.SUSPENDED="suspended",s.PENDING="pending",s))(cs||{})});var Pt,i,B=F(()=>{"use strict";Pt=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=Pt.getInstance()});var le={};se(le,{UserDefaults:()=>he});import $e from"fs";import Dt from"path";import bn from"os";var At,he,ne=F(()=>{"use strict";B();At=class c{static instance;preferencesPath;preferences={};constructor(){let e=Dt.join(bn.homedir(),".orion");this.preferencesPath=Dt.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if($e.existsSync(this.preferencesPath)){let e=$e.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=Dt.dirname(this.preferencesPath);$e.existsSync(e)||$e.mkdirSync(e,{recursive:!0}),$e.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)}},he=At.getInstance()});var te,Nt=F(()=>{"use strict";Se();ne();B();te=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=he.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){he.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 wn from"axios";import{EventEmitter as Tn}from"events";var ve,fe,Ve=F(()=>{"use strict";ve="firebase_timestamp",fe=class c extends Tn{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=wn.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(()=>(ne(),le));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(Z(),us));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 Me={};se(Me,{DeviceRegistrationService:()=>ie});import{EventEmitter as Sn}from"events";import{v4 as ds}from"uuid";import Oe from"os";import ps from"fs/promises";import Cn from"path";import{execSync as _e}from"child_process";import xn from"crypto";var ie,pe=F(()=>{"use strict";Ve();Z();B();ie=class c extends Sn{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=fe.getInstance(),this.authService=H.getInstance(),this.configDir=Cn.join(Oe.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=Oe.platform();if(e==="darwin")try{let n=_e("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=_e('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=Oe.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}`),Oe.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Oe.platform();try{let t=null;switch(e){case"darwin":try{let a=_e("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=_e("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 ps.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await ps.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=_e("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=xn.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(()=>(ne(),le)),n="snowx_fallback_device_id",o=s.string(n);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=ds(),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(()=>(ne(),le)),n="snowx_fallback_device_id",o=s.string(n);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=ds(),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:ve,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:ve,lastSeenAt:ve};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:ve,lastSeenAt:ve}],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 us={};se(us,{AuthService:()=>H});import{EventEmitter as kn}from"events";import{signInAnonymously as En,signInWithEmailAndPassword as In,createUserWithEmailAndPassword as Pn,signOut as Dn,onAuthStateChanged as ms,updateProfile as An,signInWithCustomToken as Nn}from"firebase/auth";import ye from"axios";import Rt from"fs/promises";import gs from"path";import Rn from"os";var H,Z=F(()=>{"use strict";Nt();B();H=class c extends kn{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=gs.join(Rn.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=gs.dirname(this.tokenFilePath);await Rt.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ne(),le)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let n=await Rt.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 Rt.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(()=>(ne(),le));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(()=>(ne(),le));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,ms(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}te.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(ne(),le));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),i.debug(`User tier updated: ${te.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 En(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 In(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 Pn(this.auth,e,t);return this.currentUser=n.user,s&&await An(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(()=>(pe(),Me));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Dn(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(()=>(pe(),Me));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ne(),le)),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 ye.post(`${this.snowxAuthEndpoint}/login`,e):t=await ye.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 ye.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(()=>(ne(),le));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=ms(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 Nn(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 ye.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 ye.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 ye.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 ye.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 te.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 ye.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 hs={};se(hs,{MessageQueueManager:()=>re});import{EventEmitter as Fn}from"events";var re,ke=F(()=>{"use strict";B();re=class c extends Fn{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 Ke,fs=F(()=>{"use strict";B();Ke=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(),s=[];for(let n of this.tools.keys())n.toLowerCase()===t&&s.push(n);for(let n of s)this.tools.delete(n);i.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),i.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var
|
|
5
|
-
${n} ${
|
|
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(),s=[];for(let n of this.tools.keys())n.toLowerCase()===t&&s.push(n);for(let n of s)this.tools.delete(n);i.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),i.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var Cs={};ae(Cs,{ToolDisplay:()=>_});import q from"chalk";var _,me=N(()=>{"use strict";_=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,s){if(c.customUIMode)return;let n=this.getToolPrefix(e);if(console.log(q.cyan(`
|
|
5
|
+
${n} ${q.bold(e)}`)),t&&console.log(q.gray(` ${t}`)),s){let o=s.length>120?s.substring(0,120)+q.gray("..."):s;console.log(q.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:s,success:n,executionTime:o,truncateLines:r=50}=e,a=s||"";s&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(s,r):t.toLowerCase().includes("write")?a=this.formatWriteOutput(s,r):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(s,r):a=this.formatGenericOutput(s,r)),a&&a.trim()&&console.log(a);let l=n?q.green("✓"):q.red("✗"),u=n?q.green("SUCCESS"):q.red("FAILED"),p=o?q.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=>q.gray(" ")+p).join(`
|
|
8
8
|
`);return a.length>20&&(u+=`
|
|
9
|
-
`+
|
|
10
|
-
`),n=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";n&&(o+=
|
|
11
|
-
`);let r=s.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(o+=r.slice(0,10).map(a=>
|
|
9
|
+
`+q.gray(` ... (${a.length-20} more lines)`)),u}let s=e.split(`
|
|
10
|
+
`),n=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";n&&(o+=q.gray(" ")+q.dim(n[1])+`
|
|
11
|
+
`);let r=s.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(o+=r.slice(0,10).map(a=>q.gray(" ")+q.dim(a)).join(`
|
|
12
12
|
`),r.length>10&&(o+=`
|
|
13
|
-
`+
|
|
14
|
-
`).filter(r=>r.trim());if(s.length===0)return"";if(s.length<=t)return s.map(r=>
|
|
15
|
-
`);let o=s.slice(0,t).map(r=>
|
|
13
|
+
`+q.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 s=e.split(`
|
|
14
|
+
`).filter(r=>r.trim());if(s.length===0)return"";if(s.length<=t)return s.map(r=>q.gray(" ")+q.dim(r)).join(`
|
|
15
|
+
`);let o=s.slice(0,t).map(r=>q.gray(" ")+q.dim(r)).join(`
|
|
16
16
|
`);return o+=`
|
|
17
|
-
`+
|
|
18
|
-
${
|
|
17
|
+
`+q.gray(` ... (${s.length-t} more lines)`),o}static error(e,t){c.customUIMode||(console.log(`
|
|
18
|
+
${q.red("✗")} ${q.red.bold(e)} ${q.red("ERROR")}`),console.log(q.gray(" ")+q.white(t)),console.log(""))}}});import xs from"os";import Lt from"path";function nt(){return process.platform==="win32"}function De(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,xs.homedir())),nt()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,xs.homedir())),!nt()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),nt()&&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=De(c);if(nt()){let s=Lt.basename(e).split(".")[0].toUpperCase();if(Bn.includes(s))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${s}`}}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 Bn,ot=N(()=>{"use strict";Bn=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});var it,ks=N(()=>{"use strict";B();me();ot();it=class{toolNames=["read","Read"];async execute(e,t,s,n){let o=s.file_path||s.path,r=s.offset,a=s.limit;if(!o)throw new Error("Missing file_path or path argument");let l=De(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",s.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 v=await f.stat(l);if(v.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let b=await f.readFile(l,"utf-8"),T=b.length,d=b.split(`
|
|
24
|
+
`),g=d.length,m=Math.max(r??0,0),S=87500;if(T>S&&r===void 0&&a===void 0){let L=v.size/1024,z=L/1024,P=z>=1?`${z.toFixed(2)} MB`:`${L.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: ${
|
|
28
|
+
- Size: ${P} (${T} characters)
|
|
29
29
|
- Total Lines: ${g}
|
|
30
|
-
- Character Limit: ${
|
|
30
|
+
- Character Limit: ${S.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||b.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
|
|
45
|
-
`),
|
|
44
|
+
The file has ${g.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(g===0||b.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 x=a!==void 0?Math.min(m+a,g):g,E=d.slice(m,x),y=E.map((L,z)=>`${(m+z+1).toString().padStart(6," ")} ${L}`).join(`
|
|
45
|
+
`),k=y;if(r!==void 0||a!==void 0){let L=`
|
|
46
46
|
|
|
47
|
-
[Read ${E.length} lines (${m+1}-${
|
|
47
|
+
[Read ${E.length} lines (${m+1}-${x}) of ${g} total lines]`;k=y+L}let R=Date.now()-p;return _.result({toolName:"Read",filePath:l,output:k,success:!0,executionTime:R}),[{type:"text",text:k}]}catch(f){i.debug(`[ReadFileTool] Failed to read file: ${f.message}`);let v;f.code==="ENOENT"?v=`Error: File does not exist at path: ${l}`:f.code==="EACCES"?v=`Error: Permission denied. Cannot read file: ${l}`:f.code==="EISDIR"?v=`Error: Path is a directory, not a file: ${l}`:v=`Error reading file: ${f.message}`;let b=Date.now()-p;return _.result({toolName:"Read",filePath:l,output:v,success:!1,executionTime:b}),[{type:"text",text:v}]}}}});import rt from"fs/promises";import Hn from"form-data";import Wt from"axios";import Bt from"path";var at,Es=N(()=>{"use strict";B();me();ne();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,s,n){let o=s.path;if(!o)throw new Error("Missing path argument");i.debug(`[ReadSpecialFileTool] Converting file: ${o}`);let r=Date.now();_.start("ReadSpecialFile",s.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 x=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: ${x}`}]}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 E=(await rt.readFile(o)).toString("base64"),y=this.imageMimeTypes[a]||"application/octet-stream";i.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${E.length} chars)`);let k=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:k}),[{type:"image_url",image_url:{url:`data:${y};base64,${E}`}}]}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 v=f.files[0];if(!v||v.status==="failed"){let x=v?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${x}`}]}let b=await this.fetchFileContent(v.file_id);if(!b.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let T=l.size/1024,d=T/1024,g=d>=1?`${d.toFixed(2)} MB`:`${T.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
|
-
${b.markdown_content}`,
|
|
56
|
+
${b.markdown_content}`,S=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${g})`,success:!0,executionTime:S}),[{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 s=await
|
|
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 s=await rt.readFile(e),n=Bt.extname(t).substring(1).toLowerCase(),r=await H.getInstance().getFirebaseIdToken(),a=new Hn;a.append("files",s,{filename:t,contentType:this.getMimeType(n)});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 s=await H.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);for(let o=1;o<=this.maxPollAttempts;o++)try{let a=(await Wt.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:n})).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 s=await H.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);try{let o=await Wt.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:n});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,Is=N(()=>{"use strict";B();me();ot();ct=class{toolNames=["write","Write","write_file"];async execute(e,t,s,n){let o=s.file_path,r=s.content,a=s.edits;if(!o)throw new Error("Missing file_path argument");let l=De(o),u=Re(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let p=Date.now();return _.start("Write",s.description,l),r!=null?await this.executeSimpleWrite(l,r,p):await this.executeEditsMode(l,a,p)}async executeSimpleWrite(e,t,s){i.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let n=await import("fs/promises"),r=(await import("path")).dirname(e);await n.mkdir(r,{recursive:!0}),await n.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()-s;return _.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:p}),[{type:"text",text:u}]}catch(n){i.debug(`[WriteFileTool] Failed to write file: ${n.message}`);let o=`Error writing file: ${n.message}`,r=Date.now()-s;return _.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:r}),[{type:"text",text:o}]}}async executeEditsMode(e,t,s){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 n=await import("fs/promises"),o=await import("path");for(let b=0;b<t.length;b++){let
|
|
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()-s;return _.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:p}),[{type:"text",text:u}]}catch(n){i.debug(`[WriteFileTool] Failed to write file: ${n.message}`);let o=`Error writing file: ${n.message}`,r=Date.now()-s;return _.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:r}),[{type:"text",text:o}]}}async executeEditsMode(e,t,s){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 n=await import("fs/promises"),o=await import("path");for(let b=0;b<t.length;b++){let T=t[b];if(!T||typeof T!="object")throw new Error(`Edit operation ${b+1} must be an object with 'search' and 'replace' fields`);if(!T.hasOwnProperty("search")||typeof T.search!="string")throw new Error(`Edit operation ${b+1} missing required 'search' field (must be string)`);if(!T.hasOwnProperty("replace")||typeof T.replace!="string")throw new Error(`Edit operation ${b+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 b=o.dirname(e);await n.mkdir(b,{recursive:!0}),await n.writeFile(e,a,"utf-8");let T=a.split(`
|
|
69
|
+
`),d="";for(let g=0;g<Math.min(T.length,8);g++)d+=`+ ${T[g]}
|
|
70
|
+
`;return T.length>8&&(d+=`+ ...
|
|
71
71
|
|
|
72
|
-
(${
|
|
72
|
+
(${T.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 n.readFile(e,"utf-8"),i.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(b){throw b.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: ${b.message}`)}}let l=0,u=a,p=[];for(let b=0;b<t.length;b++){let T=t[b];if(i.debug(`[WriteFileTool] Applying edit ${b+1}/${t.length}`),T.search==="")if(r){p.push({index:b+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{i.debug("[WriteFileTool] Rewriting entire existing file"),u=T.replace,p.push({index:b+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let d=u.indexOf(T.search);if(d!==-1)u=u.substring(0,d)+T.replace+u.substring(d+T.search.length),i.debug("[WriteFileTool] Replaced first occurrence"),p.push({index:b+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let g=`Search string not found: '${T.search}'`;return p.push({index:b+1,success:!1,message:g,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${b+1}: '${T.search}'\\n\\nEdit Summary:\\n- Total edits: ${p.length}\\n- Successful: ${p.filter(S=>S.success).length}\\n- Failed: ${p.filter(S=>!S.success).length}\\n\\nIndividual Edit Results:\\n`+p.map(S=>`${S.success?"✅":"❌"} Edit ${S.index}: ${S.message}`).join("\\n")}]}}await n.writeFile(e,u,"utf-8"),i.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let f=u.split(`
|
|
73
73
|
`),v="";for(let b=0;b<Math.min(f.length,8);b++)v+=`+ ${f[b]}
|
|
74
74
|
`;return f.length>8&&(v+=`+ ...
|
|
75
75
|
|
|
76
|
-
(${f.length-8} more lines)`),[{type:"text",text:v.trim()}]}catch(n){return i.debug(`[WriteFileTool] Failed to write file: ${n.message}`),[{type:"text",text:`Error writing file: ${n.message}`}]}}}});var
|
|
76
|
+
(${f.length-8} more lines)`),[{type:"text",text:v.trim()}]}catch(n){return i.debug(`[WriteFileTool] Failed to write file: ${n.message}`),[{type:"text",text:`Error writing file: ${n.message}`}]}}}});var lt,Ps=N(()=>{"use strict";B();me();ot();lt=class{toolNames=["edit","Edit"];async execute(e,t,s,n){let o=s.file_path,r=s.old_string,a=s.new_string,l=s.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=De(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",s.description,u);try{let v=await import("fs/promises"),b=await v.readFile(u,"utf-8"),T,d=0;if(l)for(T=b;T.includes(r);)T=T.replace(r,a),d++;else b.includes(r)?(T=b.replace(r,a),d=1):T=b;if(d===0){let E=`No matches found for the specified old_string in file: ${u}`,y=Date.now()-f;return _.result({toolName:"Edit",filePath:u,output:E,success:!1,executionTime:y}),[{type:"text",text:E}]}await v.writeFile(u,T,"utf-8");let g=`Successfully edited file: Replaced ${d} occurrence(s)`;i.debug(`[EditFileTool] ${g}`);let m=Date.now()-f,S=(await import("chalk")).default,x=`${S.red("- "+r.split(`
|
|
77
77
|
`).slice(0,5).join(`
|
|
78
78
|
- `))}
|
|
79
|
-
${
|
|
79
|
+
${S.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:x,success:!0,executionTime:m}),[{type:"text",text:g}]}catch(v){i.debug(`[EditFileTool] Failed to edit file: ${v.message}`);let b=`Error editing file: ${v.message}`,T=Date.now()-f;return _.result({toolName:"Edit",filePath:u,output:b,success:!1,executionTime:T}),[{type:"text",text:b}]}}}});var ut,Ds=N(()=>{"use strict";B();ut=class{toolNames=["upload_file"];async execute(e,t,s,n){let o=s.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 Gn from"path";import qn from"form-data";import zn from"axios";var dt,As=N(()=>{"use strict";B();me();ne();dt=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let o=s.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();_.start("DeployZipHTML",s.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let R=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 ${R} 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=Gn.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipHTML] File: ${f}, Size: ${l.size} bytes`);let b=await H.getInstance().getFirebaseIdToken();if(!b)throw new Error("User must be authenticated to deploy projects");let T=new qn;T.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 zn.post(d,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${b}`},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 S=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,x=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let y=`# HTML Project Deployed Successfully!
|
|
84
84
|
|
|
85
|
-
**Deployment URL**: ${
|
|
85
|
+
**Deployment URL**: ${S}
|
|
86
86
|
|
|
87
87
|
**Project**: ${f}
|
|
88
88
|
**Type**: Static HTML
|
|
89
|
-
${
|
|
89
|
+
${x?`**Deploy ID**: ${x}
|
|
90
90
|
`:""}${E?`**Site ID**: ${E}
|
|
91
91
|
`:""}
|
|
92
92
|
Your site is now live and accessible!
|
|
93
93
|
|
|
94
|
-
${m.message||""}`,
|
|
94
|
+
${m.message||""}`,k=Date.now()-r;return _.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${S}`,success:!0,executionTime:k}),[{type:"text",text:y}]}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 Gt from"fs/promises";import Xn from"path";import jn from"form-data";import Vn from"axios";var pt,Ns=N(()=>{"use strict";B();me();ne();pt=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let o=s.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();_.start("DeployZipReact",s.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let R=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 ${R} seconds.`)}i.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await Gt.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 Gt.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 Gt.readFile(o),f=Xn.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipReact] File: ${f}, Size: ${l.size} bytes`);let b=await H.getInstance().getFirebaseIdToken();if(!b)throw new Error("User must be authenticated to deploy projects");let T=new jn;T.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 Vn.post(d,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${b}`},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 S=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,x=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let y=`# React Project Deployed Successfully!
|
|
106
106
|
|
|
107
|
-
**Deployment URL**: ${
|
|
107
|
+
**Deployment URL**: ${S}
|
|
108
108
|
|
|
109
109
|
**Project**: ${f}
|
|
110
110
|
**Type**: React / SPA
|
|
111
|
-
${
|
|
111
|
+
${x?`**Deploy ID**: ${x}
|
|
112
112
|
`:""}${E?`**Site ID**: ${E}
|
|
113
113
|
`:""}
|
|
114
114
|
Your React app is now live and accessible!
|
|
115
115
|
|
|
116
|
-
${m.message||""}`,
|
|
116
|
+
${m.message||""}`,k=Date.now()-r;return _.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${S}`,success:!0,executionTime:k}),[{type:"text",text:y}]}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,7 @@ 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 Rs=N(()=>{"use strict"});function ze(c){let t=c.trim().toLowerCase().split(/\s+/)[0]||"",s=new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","yes","printf"]),n=new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","basename","dirname","stat","file","du","df","free","uptime","ps"]),o=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 s.has(t)||n.has(t)&&c.length<100?Ae.fast:o.has(t)?Ae.extended:c.length<20?Ae.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?Ae.default:Ae.extended:Ae.default}var Ae,qt=N(()=>{"use strict";Rs();Ae={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as Kn,exec as Qn}from"child_process";import{promisify as Jn}from"util";function zt(){return process.platform}function Xe(){return process.platform==="win32"}function Zn(){return process.platform==="darwin"}function Fs(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 n=["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(n)return{isPrivileged:!0,reason:`Privileged command: ${n.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 eo(){return Xe()?"PowerShell or Command Prompt":(Zn(),"Terminal")}function $s(c,e){let t=eo();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
|
|
128
128
|
|
|
129
129
|
Reason: ${e}
|
|
130
130
|
|
|
@@ -138,16 +138,16 @@ To run this command:
|
|
|
138
138
|
2. Run the command manually: ${c}
|
|
139
139
|
3. Enter your password when prompted
|
|
140
140
|
|
|
141
|
-
Alternative: Break down the task into non-privileged commands if possible.`}var
|
|
141
|
+
Alternative: Break down the task into non-privileged commands if possible.`}var Yn,je,Xt=N(()=>{"use strict";qt();Yn=Jn(Qn);je=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,s,n,o="new",r){let a=r||ze(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Xe())await Yn(`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(s=>{let n=Date.now(),o=zt(),r,a;Xe()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=Kn(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Xe()}),u="",p="",f=!1,v=!1,b=null,T=setTimeout(async()=>{v||(f=!0,l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),b=setTimeout(async()=>{v||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),this.cleanupStreams(l),setTimeout(()=>{if(!v){v=!0;let d=Date.now()-n;s({output:u+p+`
|
|
142
142
|
|
|
143
|
-
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:d,platform:o})}},1e3))},3e3))},t.maxTimeout);l.stdout?.on("data",d=>{u+=d.toString()}),l.stderr?.on("data",d=>{p+=d.toString()}),l.on("close",d=>{if(v)return;v=!0,clearTimeout(
|
|
144
|
-
`).length,
|
|
143
|
+
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:d,platform:o})}},1e3))},3e3))},t.maxTimeout);l.stdout?.on("data",d=>{u+=d.toString()}),l.stderr?.on("data",d=>{p+=d.toString()}),l.on("close",d=>{if(v)return;v=!0,clearTimeout(T),b&&clearTimeout(b);let g=Date.now()-n,m=(u+p).trim(),S=3e4;if(m.length>S){let x=m.substring(0,S),y=x.split(`
|
|
144
|
+
`).length,k=m.length;m=x+`
|
|
145
145
|
|
|
146
|
-
[Output truncated at `+
|
|
146
|
+
[Output truncated at `+S+` characters]
|
|
147
147
|
[Showing first `+y+` lines of output]
|
|
148
|
-
[Total output was `+
|
|
148
|
+
[Total output was `+k+" characters]"}s(f?{output:m+`
|
|
149
149
|
|
|
150
|
-
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:g,platform:o}:{output:m,exitCode:d||0,isSuccess:(d||0)===0,duration:g,platform:o})}),l.on("error",d=>{if(v)return;v=!0,clearTimeout(
|
|
150
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:g,platform:o}:{output:m,exitCode:d||0,isSuccess:(d||0)===0,duration:g,platform:o})}),l.on("error",d=>{if(v)return;v=!0,clearTimeout(T),b&&clearTimeout(b);let g=Date.now()-n;s({output:"Process execution failed: "+d.message,exitCode:-1,isSuccess:!1,duration:g,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 to}from"events";import Os from"axios";import{exec as so,spawn as _s}from"child_process";import{promisify as no}from"util";import Y from"fs/promises";import ve from"fs";import Fe from"path";import oo from"os";var la,Ve,mt=N(()=>{"use strict";Xt();qt();la=no(so),Ve=class _ToolCallingService extends to{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
151
|
|
|
152
152
|
🔧 SESSION MODE SELECTION (REQUIRED):
|
|
153
153
|
• Use session: "existing" for workflows that need persistent state:
|
|
@@ -181,13 +181,13 @@ Alternative: Break down the task into non-privileged commands if possible.`}var
|
|
|
181
181
|
4. LLM receives prompt details and makes decision
|
|
182
182
|
5. LLM uses provide_input to send appropriate response
|
|
183
183
|
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(()=>(ae(),vs));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(()=>(de(),Pe)),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 Ds.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 K.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")&&ue.existsSync(e)){let o=await K.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 K.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}ue.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let n=Ie.dirname(e);return await K.mkdir(n,{recursive:!0}),s==="append"?await K.appendFile(e,t):await K.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 K.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let n=await K.stat(Ie.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=We.parseSessionMode(c.session),t=Ue(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 Ds({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=As("/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}
|
|
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}
|
|
185
185
|
PID: ${a.pid}
|
|
186
186
|
Command: ${e}
|
|
187
187
|
|
|
188
188
|
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 n=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:
|
|
190
|
-
`).filter(
|
|
189
|
+
Output will be collected automatically.`;return{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let n=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:ze(e),o=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",n);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:s,replace_all:n=!1}=c;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&ve.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 v=n?f.replaceAll(t,s):f.replace(t,s);return l.cells[u].source=v,await Y.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:n?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=n?o.replaceAll(t,s):o.replace(t,s);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:n?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:s,output_mode:n="files_with_matches",case_insensitive:o=!1}=c,r=[];return o&&r.push("-i"),n==="files_with_matches"?r.push("-l"):n==="count"&&r.push("-c"),s&&r.push("--glob",s),r.push(e,t),new Promise(a=>{let l=_s("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 v=u.trim().split(`
|
|
190
|
+
`).filter(T=>T),b=v.length;a({success:!0,result:{pattern:e,num_files:b,files:v,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,n=(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):(n.test(f)||n.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:s,cell_type:n="code",edit_mode:o="replace"}=c;if(!ve.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=s;break}case"insert":{if(!n)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:n,source:s,metadata:{},execution_count:n==="code"?null:void 0,outputs:n==="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=ve.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(ve.existsSync(c)){let s=await Y.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(ve.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,s=c>0?this.executionHistory.reduce((r,a)=>r+a.executionTime,0)/c:0,n=new Map;this.executionHistory.forEach(r=>{n.set(r.toolName,(n.get(r.toolName)||0)+1)});let o=n.size>0?Array.from(n.entries()).reduce((r,a)=>a[1]>r[1]?a:r)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(s),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 s=this.createTempFile(t,e);return s?{success:!0,result:this.generatePreview(t,s)}:{success:!0,result:this.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=oo.tmpdir(),s=Fe.join(t,"orion_tool_responses");ve.existsSync(s)||ve.mkdirSync(s,{recursive:!0});let n=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),r=`${e}_${n}_${o}.txt`,a=Fe.join(s,r);return ve.writeFileSync(a,c,"utf8"),a}catch{return null}}generatePreview(c,e){let t=c.substring(0,1e4),s=`📄 Response too large (${c.length} characters > 87,500 limit), saved to temporary file.
|
|
191
191
|
|
|
192
192
|
`;return s+=`📁 TEMP FILE PATH: ${e}
|
|
193
193
|
`,s+=`🔍 Use read_file, grep, cat, or other tools to access the full content.
|
|
@@ -200,15 +200,15 @@ ${"─".repeat(50)}`,s+=`
|
|
|
200
200
|
|
|
201
201
|
💡 To read full content: use tools like 'read_file' with path above`,s}truncateOutput(c){return c.length<=this.maxResponseCharacters?c:c.substring(0,this.maxResponseCharacters)+`
|
|
202
202
|
|
|
203
|
-
... (truncated due to size limit)`}stopAllRunningTools(){}}});var
|
|
204
|
-
`,g+=`Exit Code: ${
|
|
203
|
+
... (truncated due to size limit)`}stopAllRunningTools(){}}});var gt,Ms=N(()=>{"use strict";B();Xt();gt=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,n){let o=s.command,r=s.session||"new",a=s.description,l=s.timeout,u=s.run_in_background;if(!o)throw new Error("Missing command argument");if(o.trim().length===0)throw new Error("Command cannot be empty");let p=Fs(o);if(p.isPrivileged)return i.debug(`[RunCommandTool] Blocked privileged command: ${p.reason}`),[{type:"text",text:`Error: ${$s(o,p.reason||"Privileged command detected")}`}];if(r!=="new"&&r!=="existing")throw new Error(`Invalid session mode '${r}' - must be 'new' or 'existing'`);if(l!==void 0){if(l<=0)throw new Error(`Timeout must be positive. Received: ${l}ms`);if(l>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${l}ms`)}let f=l||12e4,v=zt();i.debug(`[RunCommandTool] Executing command on platform: ${v}`),i.debug(`[RunCommandTool] Command: ${o.substring(0,50)}${o.length>50?"...":""}`),a&&i.debug(`[RunCommandTool] Description: ${a}`),i.debug(`[RunCommandTool] Session: ${r}, Timeout: ${f}ms, Background: ${u||!1}`);try{let b=(await Promise.resolve().then(()=>(mt(),jt))).ToolCallingService.getInstance(),T={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:r,timeout:f})}},d=await b.executeTool(T),g="";if(d.success){let m=(d.result?.stdout||"").trim(),S=d.result?.exitCode??0;if(g=`Command: ${o}
|
|
204
|
+
`,g+=`Exit Code: ${S}
|
|
205
205
|
|
|
206
|
-
`,m.length>0){let
|
|
207
|
-
`),E=
|
|
208
|
-
`),
|
|
206
|
+
`,m.length>0){let x=m.split(`
|
|
207
|
+
`),E=x.slice(0,15);g+=E.join(`
|
|
208
|
+
`),x.length>15&&(g+=`
|
|
209
209
|
|
|
210
|
-
... (showing first 15 of ${
|
|
211
|
-
`,g+=`Exit Code: ${
|
|
210
|
+
... (showing first 15 of ${x.length} lines)`)}else g+="(no output)";return[{type:"text",text:g}]}else{let m=d.error||"Unknown error",S=d.result?.exitCode??1;return g=`Command: ${o}
|
|
211
|
+
`,g+=`Exit Code: ${S}
|
|
212
212
|
|
|
213
213
|
`,g+=`Error:
|
|
214
214
|
${m}`,[{type:"text",text:g}]}}catch(b){return i.debug(`[RunCommandTool] Failed to execute bash command: ${b.message}`),[{type:"text",text:`Command: ${o}
|
|
@@ -229,15 +229,15 @@ If you expected output, the command may need different parameters or the operati
|
|
|
229
229
|
Consider:
|
|
230
230
|
• Checking the command syntax and parameters
|
|
231
231
|
• Verifying file permissions and paths
|
|
232
|
-
• Running the command with verbose flags for more details`:n}}});var
|
|
232
|
+
• Running the command with verbose flags for more details`:n}}});var ht,Us=N(()=>{"use strict";B();ht=class{toolNames=["grep","Grep"];async execute(e,t,s,n){let o=s.pattern,r=s.output_mode||"files_with_matches",a=s.path||process.cwd(),l=s.glob,u=s.type,p=s["-i"]===!0,f=s["-n"]===!0,v=s["-A"],b=s["-B"],T=s["-C"],d=s.multiline===!0,g=s.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:S}=await import("util"),x=S(m),E="rg",y=!0;try{await x("which rg")}catch{i.debug("[GrepTool] ripgrep not found, falling back to grep"),E="grep -r",y=!1}if(y){switch(p&&(E+=" -i"),f&&(E+=" -n"),r){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break;case"content":default:break}T!==void 0?E+=` -C ${T}`:(v!==void 0&&(E+=` -A ${v}`),b!==void 0&&(E+=` -B ${b}`)),d&&(E+=" -U --multiline-dotall"),E+=` "${o.replace(/"/g,'\\"')}"`,l&&(E+=` --glob="${l}"`),u&&(E+=` --type=${u}`),E+=` "${a}"`}else{switch(p&&(E+=" -i"),f&&(E+=" -n"),r){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break}T!==void 0?E+=` -C ${T}`:(v!==void 0&&(E+=` -A ${v}`),b!==void 0&&(E+=` -B ${b}`)),E+=` "${o.replace(/"/g,'\\"')}"`,l&&(E+=` --include="${l}"`),E+=` "${a}"`}g!==void 0&&g>0&&(E+=` | head -n ${g}`),i.debug(`[GrepTool] Executing: ${E}`);let{stdout:k,stderr:R}=await x(E,{maxBuffer:10*1024*1024});if(!k&&!R)return[{type:"text",text:"No matches found"}];let L=k||R;if(r==="content"&&L){let P=`
|
|
233
233
|
|
|
234
|
-
[Found ${
|
|
235
|
-
`).length} matching line(s)]`;return[{type:"text",text:P
|
|
234
|
+
[Found ${L.trim().split(`
|
|
235
|
+
`).length} matching line(s)]`;return[{type:"text",text:L+P}]}return[{type:"text",text:L}]}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,Ls=N(()=>{"use strict";B();ft=class{toolNames=["glob","Glob"];async execute(e,t,s,n){let o=s.pattern,r=s.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:v}=await u(f);if(!v||v.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let b=v.trim().split(`
|
|
236
236
|
`);return[{type:"text",text:`Found ${b.length} file(s):
|
|
237
237
|
${b.join(`
|
|
238
|
-
`)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var
|
|
238
|
+
`)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var vt,Ws=N(()=>{"use strict";B();vt=class{toolNames=["open_url"];async execute(e,t,s,n){let o=s.url;if(!o)throw new Error("Missing url argument");i.debug(`[OpenUrlTool] Opening URL: ${o}`),n.activeWebViewURLs.includes(o)||(n.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 io,execSync as wa}from"child_process";import{promisify as ro}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 Sa,Bs=N(()=>{"use strict";Sa=ro(io)});import*as M from"fs";import*as Q from"path";import*as W from"os";import{exec as Hs}from"child_process";import{promisify as ao}from"util";var wt,Kt,oe,Gs=N(()=>{"use strict";Bs();wt=ao(Hs),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(!M.existsSync(this.orionDirectory))try{M.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{Hs(`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 M.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return M.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),M.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let s=(this.readDeviceKnowledge()||"")+`
|
|
239
239
|
|
|
240
|
-
`+e;return this.writeDeviceKnowledge(s)}getKnowledgeFileSize(){try{return
|
|
240
|
+
`+e;return this.writeDeviceKnowledge(s)}getKnowledgeFileSize(){try{return M.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
|
|
241
241
|
|
|
242
242
|
`;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
|
|
243
243
|
|
|
@@ -251,7 +251,7 @@ ${b.join(`
|
|
|
251
251
|
`,e+=`- **Username**: ${W.userInfo().username}
|
|
252
252
|
`,e+=`- **Home Directory**: ${W.homedir()}
|
|
253
253
|
|
|
254
|
-
`;let t=
|
|
254
|
+
`;let t=Vt();e+=`## Shell Environment
|
|
255
255
|
`,e+=`- **Default Shell**: ${t}
|
|
256
256
|
`,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
|
|
257
257
|
`),e+=`
|
|
@@ -259,28 +259,28 @@ ${b.join(`
|
|
|
259
259
|
`,e+=n.join(`
|
|
260
260
|
`),e+=`
|
|
261
261
|
|
|
262
|
-
`);let o=[];if(
|
|
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(M.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(M.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 v of u)M.existsSync(v.path)&&o.push(`- ${v.name}`);let p=["/usr/share/applications",Q.join(W.homedir(),".local/share/applications")],f=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let v of p)if(M.existsSync(v))try{let b=M.readdirSync(v);for(let T of b){let d=T.toLowerCase();for(let g of f)d.includes(g)&&!o.some(m=>m.toLowerCase().includes(g))&&o.push(`- ${T.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
|
|
263
263
|
`,e+=o.join(`
|
|
264
264
|
`),e+=`
|
|
265
265
|
|
|
266
266
|
`),e+=`## Important Directories
|
|
267
267
|
`,e+=`- **Home**: ${W.homedir()}
|
|
268
|
-
`,e+=`- **Desktop**: ${
|
|
269
|
-
`,e+=`- **Documents**: ${
|
|
270
|
-
`,e+=`- **Downloads**: ${
|
|
271
|
-
`,
|
|
268
|
+
`,e+=`- **Desktop**: ${Q.join(W.homedir(),"Desktop")}
|
|
269
|
+
`,e+=`- **Documents**: ${Q.join(W.homedir(),"Documents")}
|
|
270
|
+
`,e+=`- **Downloads**: ${Q.join(W.homedir(),"Downloads")}
|
|
271
|
+
`,yt()?(e+=`- **Applications**: /Applications
|
|
272
272
|
`,e+=`- **usr/local/bin**: /usr/local/bin
|
|
273
|
-
`):
|
|
273
|
+
`):Oe()?(e+=`- **Program Files**: C:\\Program Files
|
|
274
274
|
`,e+=`- **Program Files (x86)**: C:\\Program Files (x86)
|
|
275
|
-
`,e+=`- **AppData**: ${
|
|
276
|
-
`,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||
|
|
277
|
-
`):
|
|
275
|
+
`,e+=`- **AppData**: ${Q.join(W.homedir(),"AppData")}
|
|
276
|
+
`,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||Q.join(W.homedir(),"AppData","Local")}
|
|
277
|
+
`):bt()&&(e+=`- **/usr/bin**: /usr/bin
|
|
278
278
|
`,e+=`- **/usr/local/bin**: /usr/local/bin
|
|
279
279
|
`,e+=`- **/opt**: /opt
|
|
280
|
-
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||
|
|
281
|
-
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||
|
|
282
|
-
`,
|
|
283
|
-
`),
|
|
280
|
+
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||Q.join(W.homedir(),".config")}
|
|
281
|
+
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||Q.join(W.homedir(),".local/share")}
|
|
282
|
+
`,M.existsSync("/snap")&&(e+=`- **Snap**: /snap
|
|
283
|
+
`),M.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
|
|
284
284
|
`)),e+=`
|
|
285
285
|
`,e+=`## Network
|
|
286
286
|
`,e+=`- **Hostname**: ${W.hostname()}
|
|
@@ -297,19 +297,19 @@ ${b.join(`
|
|
|
297
297
|
`);return this.writeDeviceKnowledge(l)}addNote(e,t,s="Notes"){let n=new Date().toLocaleString(),o=`### ${e} (${n})
|
|
298
298
|
${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${s}`)){let a=r.split(`
|
|
299
299
|
`),l=[],u=!1,p=!1;for(let v of a)v.startsWith(`## ${s}`)?(u=!0,l.push(v)):v.startsWith("## ")&&u&&!p?(l.push(""),l.push(o),l.push(""),l.push(v),u=!1,p=!0):l.push(v);u&&!p&&(l.push(""),l.push(o));let f=l.join(`
|
|
300
|
-
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(s,o)}deleteDeviceKnowledge(){try{return
|
|
301
|
-
`):null}async getCommandVersion(e){try{let t=
|
|
302
|
-
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let s=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,s)*100)/100+" "+t[s]}},
|
|
300
|
+
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(s,o)}deleteDeviceKnowledge(){try{return M.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return M.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=M.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:s}=await wt("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),n=s.trim();n&&n!=="none"&&e.push(`- **Virtualization**: ${n}`)}catch{}if(M.existsSync("/proc/cpuinfo"))try{M.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(n=>n.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 s of t)if(M.existsSync(s))try{let n=M.readFileSync(s,"utf8").trim().toLowerCase();if(n.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(n.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(n.includes("kvm")||n.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(n.includes("hyper-v")||n.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(n.includes("xen")){e.push("- **VM Type**: Xen");break}else if(n.includes("amazon")||n.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(n.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(n.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(M.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),M.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),M.existsSync("/proc/version"))try{let s=M.readFileSync("/proc/version","utf8");(s.toLowerCase().includes("microsoft")||s.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(M.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),M.existsSync("/etc/os-release"))try{let n=M.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);n&&e.push(`- **Distribution**: ${n[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}),s=t.toLowerCase();(s.includes("virtual")||s.includes("vmware")||s.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(`
|
|
301
|
+
`):null}async getCommandVersion(e){try{let t=Vt(),{stdout:s,stderr:n}=await wt(e,{timeout:5e3,shell:t,windowsHide:!0});return(s+n).trim().split(`
|
|
302
|
+
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let s=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,s)*100)/100+" "+t[s]}},oe=Kt.shared()});var Tt,qs=N(()=>{"use strict";B();me();Gs();Tt=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,n){let o=s.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=s.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=s.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=s.section,f=s.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=s.title,f=s.content,v=s.category||"Notes";!p||!f?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):oe.addNote(p,f,v)?a=`Note "${p}" added to ${v} 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=s.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=s.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,zs=N(()=>{"use strict";B();St=class{toolNames=["operator_status"];async execute(e,t,s,n){let o=s.taskId,r=s.status,a=s.message;return i.debug(`[OperatorStatusTool] Operator status - Task ${o}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Ct,Xs=N(()=>{"use strict";B();Ct=class{toolNames=["provide_input"];async execute(e,t,s,n){let o=s.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 co}from"child_process";import{promisify as lo}from"util";import*as xt from"fs/promises";import*as js from"path";import*as Vs from"os";var uo,_e,Qt=N(()=>{"use strict";B();uo=lo(co),_e=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=js.join(Vs.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
303
|
[System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
|
|
304
304
|
Start-Sleep -Milliseconds 100;
|
|
305
305
|
$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
|
|
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 uo(t);let s=await xt.readFile(e),n=s.toString("base64");return await xt.unlink(e).catch(()=>{}),i.debug(`[SCREENSHOT] Captured screenshot: ${s.length} bytes`),`data:image/jpeg;base64,${n}`}catch(e){return i.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
|
|
307
307
|
⚠️ 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
308
|
`)):process.platform==="darwin"&&(console.log(`
|
|
309
309
|
⚠️ 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 yt,Gs=F(()=>{"use strict";B();qt();yt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,s,n){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await Ae.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 Ye),c.register(new et),c.register(new tt),c.register(new st),c.register(new nt),c.register(new ot),c.register(new it),c.register(new at),c.register(new ct),c.register(new lt),c.register(new ut),c.register(new gt),c.register(new ht),c.register(new ft),c.register(new yt)}var zs=F(()=>{"use strict";bs();ws();Ts();Ss();Cs();xs();ks();Ns();Rs();Fs();$s();Us();Ls();Ws();Gs()});var bt,Xs=F(()=>{"use strict";bt=class{constructor(e,t,s,n,o){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=n;this.activeWebViewURLs=o}}});var Vs={};se(Vs,{FrontendWebSocketService:()=>j});import{EventEmitter as oo}from"events";import{io}from"socket.io-client";import js from"os";import ro from"path";var j,He=F(()=>{"use strict";B();pe();Z();ke();fs();zs();Xs();j=class c extends oo{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=ie.getInstance(),this.authService=H.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new Ke,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=io(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=re.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 bt(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:`
|
|
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:`
|
|
311
311
|
|
|
312
|
-
UPDATE DEVICE KNOWLEDGE: ${
|
|
312
|
+
UPDATE DEVICE KNOWLEDGE: ${go.join(Zs.homedir(),".orion","device-knowledge.md")}
|
|
313
313
|
Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
|
|
314
314
|
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,s){let n=e.trim();n.length===0&&(t?n=`Command '${s}' executed successfully.
|
|
315
315
|
|
|
@@ -323,7 +323,7 @@ PREVIEW (first 5,000 characters):
|
|
|
323
323
|
${"─".repeat(50)}
|
|
324
324
|
`+v+(a.length>5e3?`
|
|
325
325
|
${"─".repeat(50)}
|
|
326
|
-
... (${a.length-5e3} more characters)`:"");await this.sendToolResult(e,t,s,b,o);return}let u=await this.createTempFile(a,s);if(!u){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,s,this.truncateOutput(a),o);return}let p=this.generatePreview(a,u);await this.sendToolResult(e,t,s,p,o)}else await this.sendToolResult(e,t,s,a,o)}async createTempFile(e,t){try{let s=await import("fs/promises"),n=await import("path"),o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=
|
|
326
|
+
... (${a.length-5e3} more characters)`:"");await this.sendToolResult(e,t,s,b,o);return}let u=await this.createTempFile(a,s);if(!u){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,s,this.truncateOutput(a),o);return}let p=this.generatePreview(a,u);await this.sendToolResult(e,t,s,p,o)}else await this.sendToolResult(e,t,s,a,o)}async createTempFile(e,t){try{let s=await import("fs/promises"),n=await import("path"),o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=Zs.homedir(),u=n.join(l,".orion","tool_outputs");await s.mkdir(u,{recursive:!0});let p=n.join(u,a);return await s.writeFile(p,e,"utf-8"),i.debug(`[FRONTEND WS] Created temp file: ${p}`),p}catch(s){return i.error(`[FRONTEND WS] Failed to create temp file: ${s}`),null}}generatePreview(e,t){let s=e.substring(0,5e3),n=`Response too large (${e.length} characters > 87,500 limit), saved to temporary file.
|
|
327
327
|
|
|
328
328
|
`;return n+=`TEMP FILE PATH: ${t}
|
|
329
329
|
`,n+=`Use read_file, grep, cat, or other tools to access the full content.
|
|
@@ -337,13 +337,13 @@ ${"─".repeat(50)}`,n+=`
|
|
|
337
337
|
To read full content: use tools like 'read_file' with path above`,n}truncateOutput(e){return e.length<=this.maxResponseCharacters?e:e.substring(0,this.maxResponseCharacters)+`
|
|
338
338
|
|
|
339
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(s){i.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.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,s,n){let o=t.map(r=>r.text||"").join(`
|
|
340
|
-
`);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(
|
|
340
|
+
`);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(ye(),$e)),a=r.getInstance(),l=n?`Error: ${n}`:o;a.captureFrontendToolResult(e,l,s),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 ke,tn=N(()=>{"use strict";ke=class{static remove(e){if(!e||!e.includes("<context>"))return e;let t=e,s=/<context>[\s\S]*?<\/context>/gi;return t=t.replace(s,""),t=t.replace(/\n{3,}/g,`
|
|
341
341
|
|
|
342
|
-
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var
|
|
342
|
+
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var $e={};ae($e,{PersonalAgentService:()=>ee});import{EventEmitter as ho}from"events";import Jt from"axios";import fo from"http";import vo from"https";import{v4 as Ee}from"uuid";import ge from"fs";import Qe from"path";import Me from"os";var Je,ee,ye=N(()=>{"use strict";Pe();ne();Ke();Ne();B();tn();Je=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code,n=e?.status||e?.statusCode||e?.response?.status,o=String(s||""),r=Number(n);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 ho{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 fo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new vo.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=Cn("fs");if(t.existsSync("/etc/os-release")){let n=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(n)return n[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return ge.existsSync(e)?t=ge.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
|
|
343
343
|
|
|
344
344
|
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
345
|
|
|
346
|
-
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=
|
|
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(ge.existsSync(e))return;let t=Qe.join(Me.homedir(),"Documents","orion","orion-device-knowledge.md");if(ge.existsSync(t)){i.info("📦 Migrating device knowledge to cross-platform location...");let s=Qe.dirname(e);ge.existsSync(s)||ge.mkdirSync(s,{recursive:!0});let n=ge.readFileSync(t,"utf8");ge.writeFileSync(e,n,"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);ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0});let s=Me.platform(),n=Me.arch(),o=Me.hostname(),r=Me.userInfo(),a=`# Device Knowledge
|
|
347
347
|
|
|
348
348
|
## System Information
|
|
349
349
|
- **Platform**: ${s}
|
|
@@ -363,22 +363,22 @@ Remember to update memory about device if any new information is learned during
|
|
|
363
363
|
|
|
364
364
|
---
|
|
365
365
|
*Last updated: ${new Date().toISOString()}*
|
|
366
|
-
`;return
|
|
366
|
+
`;return ge.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,s,n=.7,o=!0,r,a,l){this.currentPromptId=Ee(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=s;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 v=(await Promise.resolve().then(()=>(be(),qe))).DeviceRegistrationService.getInstance().getCurrentDeviceId();if(!v)throw i.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let b={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:e},...a.map(T=>({type:"image_url",image_url:{url:T}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:v,model:s.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)b.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 T=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 S=[{type:"text",text:g}];return m.imageUrls&&m.imageUrls.length>0&&S.push(...m.imageUrls.map(x=>({type:"image_url",image_url:{url:x}}))),{role:d.role,content:S}});for(let d=0;d<T.length;d++)T[d].role;b.messages=T,i.debug(`[PERSONAL AGENT] Sending request with ${T.length} messages (new conversation)`)}else i.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return o?this.performStreamingToolCall(b):this.performNonStreamingToolCall(b)}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((s,n)=>{this.currentAbortController=new AbortController;let o="",r=Buffer.alloc(0),a="",l="",u=[],p=null,f=!1,v="";this.currentOutput="",this.completeOutputWithToolResults="";let b=new Map,T=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,S=g.headers["x-session-id"]||g.headers["session-id"];if(S){p=S,this.currentSessionId=S,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${S}`);let x=(await Promise.resolve().then(()=>(Ke(),en))).FrontendWebSocketService.getInstance();i.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await x.connectForConversation(d||void 0,S)?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",x=>{try{r=Buffer.concat([r,x]);let R="",L=0;for(let z=0;z<r.length;z++)try{R=r.slice(0,z+1).toString("utf8"),L=z+1}catch{break}if(L>0){let z=r.slice(0,L);r=r.slice(L),o+=z.toString("utf8")}}catch{o+=x.toString()}let E=[/\r?\n/,/\r/],y=[],k=o;y=k.split(/\r?\n/),k=y.pop()||"",o=k;for(let R of y){let L=R.trim();if(L.startsWith("data: ")){let z=L.slice(6).trim();if(z==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),s(a);return}try{let P=JSON.parse(z);if(P.type==="session_start"&&P.conversationId){let A=P.conversationId,w=P.isNewConversation||!1,I=P.title;i.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),i.debug(`[PERSONAL AGENT] conversationId: ${A}`),i.debug(`[PERSONAL AGENT] isNewConversation: ${w}`),I&&i.debug(`[PERSONAL AGENT] title: "${I}"`),this.emit("conversation_id_received",{conversationId:A,isNew:w,title:I||void 0});continue}if(P.type==="title_generated"&&P.title&&P.conversationId){let A=P.title,w=P.conversationId;i.debug("[PERSONAL AGENT] Received title_generated event!"),i.debug(`[PERSONAL AGENT] conversationId: ${w}`),i.debug(`[PERSONAL AGENT] title: "${A}"`),this.emit("conversation_title_updated",{conversationId:w,title:A});continue}if(P.tool_response&&P.tool_response.content){let A=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:A,todos:P.tool_response.todos||null}),this.emit("toolComplete",I);let F="";Array.isArray(A)?F=A.map(O=>typeof O=="string"?O:O&&typeof O=="object"&&(O.text||O.content)||"").join(""):typeof A=="string"?F=A:F=JSON.stringify(A),(!F||F.trim().length===0)&&(F="(empty tool result)");let $=`<context>
|
|
367
|
+
${F}
|
|
368
|
+
</context>`;u.push($),a+=$+`
|
|
369
|
+
`,this.completeOutputWithToolResults+=$+`
|
|
370
|
+
`,this.currentOutput+=$+`
|
|
371
|
+
`;continue}if(P.tool_calls){i.debug("Processing tool calls:",P.tool_calls.length,"items");for(let[A,w]of P.tool_calls.entries())if(i.debug("Tool call ["+A+"]:"),w.id){i.debug("Processing tool call ID:",w.id);let I=b.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(b.set(w.id,I),I.function?.name&&!T.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?"...":"")),T.has(w.id)||(T.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 A=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:",A.length),i.debug(" Content Preview:",A.substring(0,200)+"..."),this.emit("tool_completed",{toolName:I,toolId:w,result:A,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>
|
|
367
372
|
${A}
|
|
368
|
-
</context>`;u.push(
|
|
369
|
-
`,this.completeOutputWithToolResults
|
|
370
|
-
`,this.currentOutput
|
|
371
|
-
|
|
372
|
-
${
|
|
373
|
-
</context>`;u.push(
|
|
374
|
-
`,this.completeOutputWithToolResults+=
|
|
375
|
-
`,this.currentOutput+=
|
|
376
|
-
|
|
377
|
-
${q}
|
|
378
|
-
</context>`;if(u.push(me),a+=me+`
|
|
379
|
-
`,this.completeOutputWithToolResults+=me+`
|
|
380
|
-
`,this.currentOutput+=me+`
|
|
381
|
-
`,!N){let ge=I.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(ge){let Q=I.replace(ge[0],"").trim();if(Q.length>0){a+=Q,l+=Q,this.currentOutput+=Q,this.completeOutputWithToolResults+=Q;let kt=be.remove(Q);this.emit("data",kt)}}}continue}}catch{}if(I.includes("<think>")){f=!0;let S=I.split("<think>")[0];if(S){a+=S,l+=S,this.currentOutput+=S,this.completeOutputWithToolResults+=S;let N=be.remove(S);this.emit("data",N)}}else if(I.includes("</think>")){f=!1,v+=I.split("</think>")[0],this.emit("thinking",v),v="";let S=I.split("</think>")[1]||"";if(S){a+=S,l+=S,this.currentOutput+=S,this.completeOutputWithToolResults+=S;let N=be.remove(S);this.emit("data",N)}}else if(f)v+=I,this.emit("thinking",v);else{a+=I,l+=I,this.currentOutput+=I,this.completeOutputWithToolResults+=I;let S=be.remove(I);this.emit("data",S)}}else if(D.type==="checkpoint_reached"||D.event==="checkpoint_reached")i.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(D.type==="todo_update")this.handleTodoUpdate(D.data);else if(D.type==="webview_update")this.handleWebViewUpdate(D.data);else if(D.type==="operator_progress")this.handleOperatorProgress(D.data);else if(D.type==="stop"){this.handleStop(D.data),s(a);return}}catch{i.debug("Treating as plain text"),a+=$,l+=$,this.currentOutput+=$,this.completeOutputWithToolResults+=$;let I=be.remove($);this.emit("data",I)}}}}),m.on("end",()=>{this.emit("done"),s(a)}),m.on("error",k=>{switch(i.debug("Streaming error, disconnecting WebSocket and cleaning up"),qe.classify(k)){case"parsing":let y={type:"tool_result",tool_call_id:`error_${we()}`,error:!0,content:`Streaming parsing error occurred: ${k.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(y)),j.getInstance().handleConversationComplete(),s(a);return;case"critical":j.getInstance().handleConversationComplete(),this.emit("error",k),n(k);break}})}).catch(g=>{if(g.code==="ERR_CANCELED")i.debug("Task was cancelled, disconnecting WebSocket"),j.getInstance().handleConversationComplete(),this.emit("canceled"),s(a);else switch(qe.classify(g)){case"parsing":let T={type:"tool_result",tool_call_id:`error_${we()}`,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(T)),j.getInstance().handleConversationComplete(),s(a);break;case"critical":i.debug("Request failed, disconnecting WebSocket"),j.getInstance().handleConversationComplete(),n(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 s=await zt.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}});if(s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let n of s.data.toolResults)this.handleToolResult(n.tool,n.result);return s.data.content}throw new Error("No response content received")}catch(t){switch(qe.classify(t)){case"parsing":let n={type:"tool_result",tool_call_id:`error_${we()}`,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(n)),"";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",s=null;if(e.function?.arguments)try{s=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,s)}async executeToolViaWebSocket(e,t,s){try{let n=j.getInstance(),o={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await n.sendToolRequest(o)}catch(n){i.debug(`Failed to execute tool via WebSocket: ${n.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:s,success:n,error:o}=e;if(i.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",n),n&&s){let a=`<context>
|
|
373
|
+
</context>`;u.push($),a+=$+`
|
|
374
|
+
`,this.completeOutputWithToolResults+=$+`
|
|
375
|
+
`,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 A=P.content;if(A&&A.length>0&&i.debug(`[STREAMING] Received content chunk: "${A}" (length: ${A.length})`),A&&A.includes('{"tool_response"'))try{let w,I=!1;try{w=JSON.parse(A),I=!0}catch{let F=A.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
|
+
${ue}
|
|
378
|
+
</context>`;if(u.push(re),a+=re+`
|
|
379
|
+
`,this.completeOutputWithToolResults+=re+`
|
|
380
|
+
`,this.currentOutput+=re+`
|
|
381
|
+
`,!I){let G=A.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(G){let j=A.replace(G[0],"").trim();if(j.length>0){a+=j,l+=j,this.currentOutput+=j,this.completeOutputWithToolResults+=j;let Z=ke.remove(j);this.emit("data",Z)}}}continue}}catch{}if(A.includes("<think>")){f=!0;let w=A.split("<think>")[0];if(w){a+=w,l+=w,this.currentOutput+=w,this.completeOutputWithToolResults+=w;let I=ke.remove(w);this.emit("data",I)}}else if(A.includes("</think>")){f=!1,v+=A.split("</think>")[0],this.emit("thinking",v),v="";let w=A.split("</think>")[1]||"";if(w){a+=w,l+=w,this.currentOutput+=w,this.completeOutputWithToolResults+=w;let I=ke.remove(w);this.emit("data",I)}}else if(f)v+=A,this.emit("thinking",v);else{a+=A,l+=A,this.currentOutput+=A,this.completeOutputWithToolResults+=A;let w=ke.remove(A);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),s(a);return}}catch{i.debug("Treating as plain text"),a+=z,l+=z,this.currentOutput+=z,this.completeOutputWithToolResults+=z;let A=ke.remove(z);this.emit("data",A)}}}}),m.on("end",()=>{this.emit("done"),s(a)}),m.on("error",x=>{switch(i.debug("Streaming error, disconnecting WebSocket and cleaning up"),Je.classify(x)){case"parsing":let y={type:"tool_result",tool_call_id:`error_${Ee()}`,error:!0,content:`Streaming parsing error occurred: ${x.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(y)),K.getInstance().handleConversationComplete(),s(a);return;case"critical":K.getInstance().handleConversationComplete(),this.emit("error",x),n(x);break}})}).catch(g=>{if(g.code==="ERR_CANCELED")i.debug("Task was cancelled, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),this.emit("canceled"),s(a);else switch(Je.classify(g)){case"parsing":let S={type:"tool_result",tool_call_id:`error_${Ee()}`,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(S)),K.getInstance().handleConversationComplete(),s(a);break;case"critical":i.debug("Request failed, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),n(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 s=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(s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let n of s.data.toolResults)this.handleToolResult(n.tool,n.result);return s.data.content}throw new Error("No response content received")}catch(t){switch(Je.classify(t)){case"parsing":let n={type:"tool_result",tool_call_id:`error_${Ee()}`,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(n)),"";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",s=null;if(e.function?.arguments)try{s=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,s)}async executeToolViaWebSocket(e,t,s){try{let n=K.getInstance(),o={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await n.sendToolRequest(o)}catch(n){i.debug(`Failed to execute tool via WebSocket: ${n.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:s,success:n,error:o}=e;if(i.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",n),n&&s){let a=`<context>
|
|
382
382
|
${s.map(l=>l.text||"").join("")}
|
|
383
383
|
</context>`;this.completeOutputWithToolResults+=a+`
|
|
384
384
|
`,this.currentOutput+=a+`
|
|
@@ -392,55 +392,55 @@ Output:
|
|
|
392
392
|
${t}
|
|
393
393
|
</context>`;this.completeOutputWithToolResults+=o+`
|
|
394
394
|
`,this.currentOutput+=o+`
|
|
395
|
-
`,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),i.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:n,wrappedContent:o})}handleCheckpointReached(){let e=
|
|
395
|
+
`,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),i.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:n,wrappedContent:o})}handleCheckpointReached(){let e=pe.getInstance(),t=e.getQueuedMessages();if(t.length===0){i.debug("[CHECKPOINT] No queued messages to convert");return}let s=t.filter(o=>!o.isCrossDeviceTask),n=t.filter(o=>o.isCrossDeviceTask);if(i.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),i.debug(` - ${s.length} user messages -> convert to feedback`),i.debug(` - ${n.length} cross-device tasks -> keep in queue`),s.length>0){let o=s.map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",o),i.info(`[CHECKPOINT] Converted ${s.length} user messages to feedback`),s.forEach(r=>{e.removeFromQueueById(r.id)})}n.length>0&&i.debug(`[CHECKPOINT] Kept ${n.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||Ee(),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||Ee(),taskId:e.taskId||e.id||Ee(),sessionId:e.sessionId||Ee(),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,s)=>typeof s.content=="string"?t+Math.ceil(s.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let s=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",{SNOWX_MODELS:n}=await Promise.resolve().then(()=>(Pe(),hs)),o=n.find(a=>a.name===s)||{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,s;if(t&&t.trim().length>0?s=t+`
|
|
396
396
|
|
|
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(()=>(pe(),Me))).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 zt.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}`),j.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 Qs={};se(Qs,{FirebaseNativeService:()=>ze,TaskMode:()=>Vt,TaskStatus:()=>Kt});import{getDatabase as mo,ref as jt,onChildAdded as go,update as ho,set as fo,serverTimestamp as vo}from"firebase/database";import{EventEmitter as yo}from"events";var Vt,Kt,ze,Qt=F(()=>{"use strict";B();Ve();Vt=(t=>(t.NEW="new",t.EXISTING="existing",t))(Vt||{}),Kt=(n=>(n.PENDING="pending",n.PROCESSING="processing",n.COMPLETED="completed",n.QUEUE_FULL="queue_full",n))(Kt||{}),ze=class c extends yo{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=fe.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=mo(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=jt(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=go(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(()=>(de(),Pe))).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(()=>(de(),Pe)),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(()=>(de(),Pe)),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=jt(this.database,n),l={status:t,updatedAt:vo()};s&&(l.result=s),await ho(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=jt(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 fo(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 bo}from"events";var Re,Jt=F(()=>{"use strict";pe();Z();Ve();Qt();de();B();Re=class c extends bo{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=ie.getInstance(),this.authService=H.getInstance(),this.firebaseAPI=fe.getInstance(),this.firebaseNative=ze.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=J.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(J.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(J.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=(ke(),yn(hs)).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}`),J.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:ve,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 tn={};se(tn,{SnowXStreamHandlerService:()=>es});import{EventEmitter as Ro}from"events";var es,sn=F(()=>{"use strict";es=class extends Ro{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
|
|
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
398
|
`);if(o!==-1)n=o;else{let r=this.buffer.indexOf(`
|
|
399
399
|
`);if(r!==-1)n=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)n=a;else return}}for(;n!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,n);this.linesProcessed++,this.buffer.substring(n,n+2)===`\r
|
|
400
400
|
`?this.buffer=this.buffer.substring(n+2):this.buffer=this.buffer.substring(n+1);let a=r.trim();if(!a){n=this.findNextLineEnd();continue}if(a.startsWith(":")){n=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),n=this.findNextLineEnd()}}processDataLine(e,t,s,n){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)n?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,s))}}catch{}}processThinkingContent(e,t,s){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let n=this.thinkingBuffer.indexOf("</think>");if(n!==-1){let o=this.thinkingBuffer.substring(0,n);o&&(this.thinkingContent+=o,s?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(n+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",s?.(this.thinkingContent));break}else{let n=this.thinkingBuffer.indexOf("<think>");if(n!==-1){let o=this.thinkingBuffer.substring(0,n);o&&(this.regularContent+=o,this.fullResponse+=o,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(n+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,s){if(this.rawDataReceived.startsWith("data: ")){let n=this.rawDataReceived.substring(6).trim();try{let o=JSON.parse(n);o.choices&&o.choices.length>0&&o.choices[0].delta.content&&this.processThinkingContent(o.choices[0].delta.content,e,t)}catch{}}else try{let n=JSON.parse(this.rawDataReceived);n.choices?.[0]?.message?.content&&this.processThinkingContent(n.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
|
|
401
401
|
`);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 Fo from"axios";import{EventEmitter as $o}from"events";import Oo from"http";import _o from"https";var St,nn=F(()=>{"use strict";Z();St=class extends $o{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Oo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new _o.Agent({keepAlive:!0,timeout:36e5}),this.client=Fo.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(()=>(sn(),tn)),f=this.buildRequest(e,t,!0,s,n,o,r);return new Promise((v,b)=>{this.currentAbortController=new AbortController;let w=[],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 T=m.data,k=m.headers["content-type"]||"",E=y=>{if(y?.index!==void 0){let x=y.index;d.has(x)||d.set(x,{});let O=d.get(x);y.id&&(O.id=y.id,O.type="function"),y.function&&(O.function||(O.function={name:"",arguments:""}),y.function.name&&(O.function.name=y.function.name),y.function.arguments&&(O.function.arguments+=y.function.arguments))}u?.(y),this.emit("tool_call_delta",y)};g.on("streamEnd",()=>{d.forEach((y,x)=>{y.id&&y.function?.name&&w.push(y)}),this.emit("done"),v({content:g.getFinalResponse(),toolCalls:w.length>0?w:void 0})}),g.on("cancelled",()=>{this.emit("canceled"),v({content:g.getFinalResponse(),toolCalls:w.length>0?w:void 0})});try{await g.processStreamingResponse(T,k,a||(()=>{}),l,E),d.forEach((y,x)=>{y.id&&y.function?.name&&w.push(y)}),this.emit("done"),v({content:g.getFinalResponse(),toolCalls:w.length>0?w:void 0})}catch(y){this.emit("error",y),b(y)}}).catch(m=>{m.code==="ERR_CANCELED"?(this.emit("canceled"),v({content:"",toolCalls:w.length>0?w: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 Mo}from"socket.io-client";import{EventEmitter as Uo}from"events";var Ct,on=F(()=>{"use strict";pe();Ct=class c extends Uo{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=ie.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=Mo(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 rn,an=F(()=>{"use strict";rn={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 ln={};se(ln,{ServiceManager:()=>je});import{EventEmitter as Lo}from"events";import{initializeApp as Wo,getApps as cn}from"firebase/app";import{getAuth as Bo}from"firebase/auth";var je,ts=F(()=>{"use strict";de();nn();Z();pe();on();He();Jt();rt();Se();B();an();je=class c extends Lo{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=J.getInstance(),this.networkClient=new St,this.authService=H.getInstance(),this.deviceRegistration=ie.getInstance(),this.webSocketService=Ct.getInstance(),this.frontendWebSocketService=j.getInstance(),this.crossDeviceService=Re.getInstance(),this.toolCalling=Be.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||rn;if(cn().length===0?(this.firebaseApp=Wo(e),i.debug("Firebase app initialized")):(this.firebaseApp=cn()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=Bo(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(()=>(Qt(),Qs));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 os from"@sentry/node";os.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as Vo}from"commander";import Go from"react";import{render as qo}from"ink";Z();import h,{useState as Ys,useEffect as Xe,useCallback as Zt,useRef as So}from"react";import{Box as R,Text as C,useInput as Co,useApp as xo}from"ink";import ko from"ink-spinner";import Zs from"ink-select-input";de();qt();import oe from"chalk";import uo from"ora";var Y=class{static spinner=null;static formatUserMessage(e){return oe.cyan("You: ")+e}static formatAssistantMessage(e){return oe.green("Assistant: ")+e}static formatError(e){return oe.red("Error: ")+e}static formatWarning(e){return oe.yellow("Warning: ")+e}static formatInfo(e){return oe.blue("Info: ")+e}static formatSuccess(e){return oe.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=uo(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(oe.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(oe.bold.cyan(e)),console.log(oe.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return oe.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return oe.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(oe.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};B();ke();import{EventEmitter as po}from"events";import Xt from"chalk";var wt=class extends po{delegate=null;personalAgentService=J.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(`
|
|
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
403
|
▸ ${n}`)}),this.personalAgentService.on("tool_completed",n=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:r,error:a}=n;console.log(r!==!1?`✓ ${o}`:`✗ ${o} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",n=>{}),this.personalAgentService.on("todo_update",n=>{}),this.personalAgentService.on("operator_progress",n=>{}),this.personalAgentService.on("webview_update",n=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(n.isStreaming=!1),o&&o.isStreaming&&(o.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",n=>{console.error(`
|
|
404
|
-
❌ Error:`,n.message||n),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",n=>{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&&(n.content&&n.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${n.content.substring(0,50)}..."`),o.content=n.content,o.originalContent=n.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),n.completeWithTools&&(o.metadata={toolResults:n.completeWithTools}),o.isStreaming=!1,i.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(n.content&&n.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${n.content.substring(0,50)}..."`),r.content=n.content,r.originalContent=n.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),n.completeWithTools&&(r.metadata={toolResults:n.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 s=87500,n=e.trim();if(n.length>s){console.log(
|
|
404
|
+
❌ Error:`,n.message||n),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",n=>{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&&(n.content&&n.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${n.content.substring(0,50)}..."`),o.content=n.content,o.originalContent=n.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),n.completeWithTools&&(o.metadata={toolResults:n.completeWithTools}),o.isStreaming=!1,i.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(n.content&&n.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${n.content.substring(0,50)}..."`),r.content=n.content,r.originalContent=n.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),n.completeWithTools&&(r.metadata={toolResults:n.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 s=87500,n=e.trim();if(n.length>s){console.log(te.formatError(`Prompt too large (${n.length} characters). Please reduce it to ${s} characters or less.`));return}if(this.delegate.isLoading){let r=pe.getInstance();r.addToQueue({content:n,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})),s=this.delegate.fullConversationHistory.filter(o=>o.role==="user"),n=s[s.length-1];if(n)try{let o=e?[e]:void 0,r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(n.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(n=>n.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
405
|
|
|
406
|
-
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let n=this.delegate.fullConversationHistory.find(o=>o.isStreaming);n&&(n.content=t.content,n.isStreaming=!1)}this.delegate.isLoading=!1,
|
|
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 n=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return n=n.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:n}}function
|
|
406
|
+
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let n=this.delegate.fullConversationHistory.find(o=>o.isStreaming);n&&(n.content=t.content,n.isStreaming=!1)}this.delegate.isLoading=!1,ee.getInstance().stopStreaming().catch(n=>{i.error("[MESSAGE HANDLER] Error in comprehensive stop:",n)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};ye();Mt();Ne();Ke();ns();Pe();ce();me();import os from"terminal-link";import{homedir as Io}from"os";function nn(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",Io())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Po(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function Pt(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,n)=>{let o=n;return!Po(n)&&!n.startsWith("file://")&&(n.startsWith("/")||n.startsWith("~")||/\.[a-z]{2,4}$/i.test(n))&&(o=nn(n)),os(s,o,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return s.test(n)?t:os(t,t,{fallback:(o,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(s.test(n)||n.includes("http"))return t;let o=nn(t);return os(t,o,{fallback:(r,a)=>r})}),e}var Fo=0;function V(){return`msg-${Date.now()}-${++Fo}`}function $o(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],s;for(;(s=e.exec(c))!==null;){let r=s[1].split(`
|
|
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 n=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return n=n.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:n}}function Oo(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],s=new Set,n;for(;(n=e.exec(c))!==null;){let r=n[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],p=l[2];s.has(p)||(s.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 an(){let{exit:c}=No(),e=H.getInstance(),t=ee.getInstance(),s=pe.getInstance(),n=K.getInstance(),o=Ue.getInstance();Ze(()=>(_.enableCustomUI(),()=>_.disableCustomUI()),[]);let[r,a]=on({messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
408
408
|
|
|
409
409
|
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===
|
|
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===Te.string("selectedPersonalModel"))||X.find(d=>d.name==="snowx-c5")||X[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=Do(null),[u]=on(()=>{let d={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:X.find(g=>g.name===Te.string("selectedPersonalModel"))||X.find(g=>g.name==="snowx-c5")||X[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new It(d)}),p=is(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=is(async d=>{if(d.startsWith("/")){let y=d.toLowerCase().trim();if(y==="/help"||y==="/?"){a(k=>({...k,showCommandMenu:!0,input:""}));return}if(y==="/model"){a(k=>({...k,showModelMenu:!0,input:""}));return}if(y==="/clear"||y==="/new"){a(k=>({...k,messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
411
411
|
|
|
412
412
|
Your intelligent AI assistant.
|
|
413
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(y==="/vision"){a(
|
|
414
|
-
|
|
415
|
-
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(r.isLoading){let y=s.addToQueue({content:d,imageUrls:[],attachments:[],model:r.selectedModel.name});a(y?
|
|
416
|
-
[TOOL:${
|
|
417
|
-
${
|
|
418
|
-
</context>`;a(
|
|
419
|
-
`+
|
|
420
|
-
`).filter(q=>q.trim()),A=N.length,M=$.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||$.match(/^\s*(\S+\.\w+)/m),z=M?M[1].split("/").pop():null;if(I.includes("todo")){let q=P.todos;if(q&&Array.isArray(q)&&q.length>0){let me=q.filter(Q=>Q.status==="completed").length,ge=q.filter(Q=>Q.status==="in_progress"||Q.status==="inProgress");if(S=` ${me}/${q.length} done`,ge.length>0){let Q=ge[0].text||ge[0].content||"",kt=Q.length>40?Q.substring(0,40)+"…":Q;S+=` → ${kt}`}}}else if(I.includes("read"))z?S=` ${z} (${A} lines)`:S=` ${A} lines`;else if(I.includes("write"))z?S=` ${z} ✓`:S=" ✓";else if(I.includes("edit"))z?S=` ${z} ✓`:S=" ✓";else if(I.includes("bash")||I.includes("command"))if($.includes("error")||$.includes("Error"))S=" ✗ error";else if(A===0||A===1&&N[0].trim()==="")S=" ✓";else if(A<=3){let q=N.slice(0,2).join(" ").substring(0,50);S=A===1?` → ${q}`:` → ${q}…`}else S=` ✓ ${A} lines`;else if(I.includes("grep")||I.includes("search")){let q=N.length;S=q>0?` ${q} matches`:" no matches"}else I.includes("glob")?S=` ${A} files`:I.includes("task")?S=" ✓":S=A>0?" ✓":""}a(N=>{let A=[...N.messages];for(let M=A.length-1;M>=0;M--)if(A[M].role==="assistant"){if(I.includes("todo")){let me=/\n\[TOOL:TodoWrite\][^\n]*/g;A[M].content=A[M].content.replace(me,"")}let z=`[TOOL:${P.toolName}]`,q=`[TOOL:${P.toolName}|${S.trim()}]`;A[M].content=A[M].content.replace(z,q),d=d.replace(z,q);break}return{...N,messages:A}})}},x=()=>{d="",a(P=>({...P,isLoading:!1}))},O=P=>{a($=>({...$,messages:[...$.messages,{role:"system",content:`Error: ${P.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),d=""};return t.on("conversation_id_received",g),t.on("conversation_title_updated",m),t.on("thinking",T),t.on("data",k),t.on("toolExecuting",E),t.on("tool_completed",y),t.on("done",x),t.on("error",O),()=>{t.off("conversation_id_received",g),t.off("conversation_title_updated",m),t.off("thinking",T),t.off("data",k),t.off("toolExecuting",E),t.off("tool_completed",y),t.off("done",x),t.off("error",O)}},[t,v]),Xe(()=>{let d=k=>{a(E=>({...E,queuedMessages:k}))},g=k=>{},m=k=>{l.current=k,a(E=>({...E,todoList:k}))},T=k=>{if(r.isLoading){s.addToQueue({content:k.prompt,imageUrls:[],attachments:[],model:r.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:k.taskId})||a(y=>({...y,messages:[...y.messages,{role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(k.prompt)};return s.on("queue:updated",d),n.on("feedback:sent",g),t.on("todo_update",m),o.on("CrossDeviceTaskSendMessage",T),()=>{s.off("queue:updated",d),n.off("feedback:sent",g),t.off("todo_update",m),o.off("CrossDeviceTaskSendMessage",T)}},[s,n,t,o,f,r.isLoading,r.selectedModel.name]),Xe(()=>{!r.isLoading&&s.hasQueuedMessages()&&v()},[r.isLoading,s,v]),Co((d,g)=>{if(g.escape){if(r.isLoading){t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{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,{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 T=m.input.slice(0,-1);return m.showCommandMenu&&!T.startsWith("/")?{...m,input:T,showCommandMenu:!1}:{...m,input:T}});return}!g.ctrl&&!g.meta&&d&&a(m=>{let T=m.input+d;return T==="/"&&!m.showCommandMenu?{...m,input:T,showCommandMenu:!0}:{...m,input:T}})}});let b=e.getUserEmail()||"User",w=te.getDisplayName(te.getCurrentUserTier());return h.createElement(R,{flexDirection:"column",width:"100%"},h.createElement(R,{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"},w),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(R,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},r.messages.map((d,g)=>h.createElement(No,{key:`${d.role}-${d.timestamp}-${g}`,message:d,onSuggestionClick:m=>{a(T=>({...T,input:m}))}}))),r.todoList&&r.todoList.todos.length>0&&r.todoList.todos.some(d=>d.status!=="completed")&&h.createElement(R,{paddingX:2,marginBottom:1},h.createElement(R,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(R,{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"?"⋯":"○",T=d.status==="completed"?"green":d.status==="in_progress"?"blue":"gray";return h.createElement(R,{key:d.id||g},h.createElement(C,{color:T},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(R,{paddingX:0,marginBottom:1,flexDirection:"column"},h.createElement(R,null,h.createElement(C,{color:"magenta"},h.createElement(ko,{type:"dots"})),h.createElement(C,{color:"white"}," ",r.loadingMessage,"… "),h.createElement(C,{color:"white"},"(esc to interrupt)")),h.createElement(R,{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(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(C,{bold:!0,color:"white"},"Keyboard Shortcuts"),h.createElement(R,{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(R,{marginTop:1},h.createElement(C,{color:"white"},"Press Esc to close"))),r.showModelMenu&&(()=>{let d=te.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")),T=X.filter(y=>y.name.startsWith("snowx-g")),k=y=>y.map(x=>{let O=te.isModelAccessible(x.name,d);return{label:O?x.displayName:`🔒 ${x.displayName}`,value:x.name,isAccessible:O}}),E=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1},...k(g),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1},...k(m),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1},...k(T)];return h.createElement(R,{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: ",te.getDisplayName(d)),h.createElement(R,{marginTop:1},h.createElement(Zs,{items:E.map(y=>({label:y.label,value:y.value})),onSelect:y=>{if(y.value.startsWith("_"))return;if(!E.find(P=>P.value===y.value)?.isAccessible){a(P=>({...P,messages:[...P.messages,{role:"system",content:te.getAccessDeniedMessage(y.value),timestamp:Date.now()}]}));return}let O=X.find(P=>P.name===y.value);O&&(he.set("selectedPersonalModel",O.name),a(P=>({...P,selectedModel:O,showModelMenu:!1,messages:[...P.messages,{role:"system",content:`Switched to ${O.displayName}`,timestamp:Date.now()}]})))}})),h.createElement(R,{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(T=>T.value.toLowerCase().includes(g)):d;return h.createElement(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(C,{bold:!0,color:"white"},"Available Commands ",g&&`(filtered: "${g}")`),h.createElement(R,{marginTop:1},h.createElement(Zs,{items:m.length>0?m:[{label:"No matching commands",value:""}],onSelect:T=>{T.value&&(a(k=>({...k,showCommandMenu:!1,input:""})),f(`/${T.value}`))}})),h.createElement(R,{marginTop:1},h.createElement(C,{color:"white"},"Esc to cancel")))})(),r.queuedMessages.length>0&&h.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.map((d,g)=>h.createElement(R,{key:d.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},h.createElement(R,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(R,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(R,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.filter(d=>d.isCrossDeviceTask).map((d,g)=>h.createElement(R,{key:`cross-${d.id}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},h.createElement(R,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(R,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(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},h.createElement(R,null,h.createElement(C,{color:"white"},"▶ "),h.createElement(C,{color:"white"},r.input,!r.isLoading&&h.createElement(C,{color:"white",inverse:!0}," "))),h.createElement(R,{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(R,{paddingX:2,paddingY:0},h.createElement(C,{color:"white"},"? help · Ctrl+C exit")))}function Po(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=Tt(e),e}function Do({suggestions:c,onSelect:e}){return c.length===0?null:h.createElement(R,{flexDirection:"column",marginTop:1},c.map((t,s)=>h.createElement(R,{key:s,flexWrap:"wrap",gap:1},t.options.map((n,o)=>h.createElement(R,{key:o,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(C,{color:"cyan"},n))))),e&&h.createElement(R,{marginTop:0},h.createElement(C,{color:"gray",dimColor:!0},"Type a suggestion to use it")))}function Ao({workingFiles:c}){return c.length===0?null:h.createElement(R,{flexDirection:"column",marginTop:1},h.createElement(R,{marginBottom:0},h.createElement(C,{color:"gray",bold:!0},"Working Files"),h.createElement(C,{color:"gray",dimColor:!0}," (",c.length,")")),h.createElement(R,{flexWrap:"wrap",gap:1},c.map((e,t)=>h.createElement(R,{key:t,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(C,{color:"white"},e.name)))))}function No({message:c,onSuggestionClick:e}){let{role:t,content:s,tool:n}=c;if(t==="system"){let o=s.split(`
|
|
421
|
-
`);return h.createElement(
|
|
422
|
-
`);return h.createElement(
|
|
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 n=await this.authService.getUserInfo();console.log(
|
|
427
|
-
✅ Authentication successful!`)),n&&(console.log(
|
|
428
|
-
❌ Authentication failed. Please try again.`))}catch(s){console.log(
|
|
429
|
-
❌ Authentication error: ${s.message}`))}}async logout(){console.log(
|
|
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(
|
|
413
|
+
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(y==="/vision"){a(k=>({...k,isVisionEnabled:!k.isVisionEnabled,messages:[...k.messages,{id:V(),role:"system",content:`Vision mode ${k.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(y==="/exit"||y==="/quit"){c();return}if(y==="/stop"){r.isLoading?(t.stopStreaming(),a(k=>({...k,isLoading:!1,messages:[...k.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(k=>({...k,messages:[...k.messages,{id:V(),role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(y==="/signout"){a(k=>({...k,messages:[...k.messages,{id:V(),role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(R=>({...R,messages:[...R.messages,{id:V(),role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(R=>({...R,messages:[...R.messages,{id:V(),role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(k){a(R=>({...R,messages:[...R.messages,{id:V(),role:"system",content:`❌ Error: ${k.message}`,timestamp:Date.now()}]}))}return}a(k=>({...k,messages:[...k.messages,{id:V(),role:"system",content:`Unknown command: ${d}
|
|
414
|
+
|
|
415
|
+
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(r.isLoading){let y=s.addToQueue({content:d,imageUrls:[],attachments:[],model:r.selectedModel.name});a(y?k=>({...k,input:""}):k=>({...k,messages:[...k.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},S={id:V(),role:"assistant",content:"",timestamp:g+1},x=[...r.messages,m,S];a(y=>({...y,messages:x,input:"",isLoading:!0,loadingMessage:"Processing"}));let E=x.map(y=>({role:y.role,content:y.content,timestamp:new Date(y.timestamp||Date.now()),...y.tool&&{tool:y.tool},...y.toolOutput&&{toolOutput:y.toolOutput}}));u.setDelegate({messages:E,fullConversationHistory:E,isLoading:!1,currentInput:"",selectedModel:r.selectedModel,isVisionEnabled:r.isVisionEnabled,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:p});try{await u.sendMessage(d)}catch(y){a(k=>({...k,messages:[...k.messages,{id:V(),role:"system",content:`Error: ${y.message}`,timestamp:Date.now()}],isLoading:!1}))}},[r.isLoading,r.isVisionEnabled,r.selectedModel,s,u,e,c]),v=is(()=>{if(!s.hasQueuedMessages())return;let d=s.processNextMessage();d&&(s.startProcessing(),f(d.content))},[s,f]);Ze(()=>{let d="",g=!1,m=!1,S=100,x=w=>{a(I=>({...I,conversationId:w.conversationId,conversationTitleGenerated:!!w.title}))},E=w=>{},y=()=>{a(w=>({...w,loadingMessage:"Processing"}))},k=()=>{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}})},R=w=>{d+=w,g=!0,m||(m=!0,setTimeout(k,S))},L=w=>{let I=`
|
|
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}`}})},z=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
|
+
${I}
|
|
418
|
+
</context>`;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.metadata?.toolResults;return{...Z,metadata:{...Z.metadata,toolResults:se?se+`
|
|
419
|
+
`+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(C,{color:"gray",dimColor:!0},"System")),h.createElement(D,{paddingLeft:1,flexDirection:"column"},o.map((r,a)=>h.createElement(C,{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(C,{color:"blue",bold:!0},"You")),h.createElement(D,{paddingLeft:1},h.createElement(C,{color:"white"},s)));if(t==="assistant"){let{suggestions:o,cleanedContent:r}=$o(s),{workingFiles:a,cleanedContent:l}=Oo(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"}},v=u.some(d=>d.type==="tool"),b=u.filter(d=>d.type==="text"),T=u.filter(d=>d.type==="tool");return h.createElement(D,{marginBottom:1,flexDirection:"column"},h.createElement(D,{marginBottom:0},h.createElement(C,{color:"green",bold:!0},"Orion")),b.map((d,g)=>{let m=d.content.split(`
|
|
422
|
+
`);return h.createElement(D,{key:`text-${g}-${d.content.slice(0,15)}`,flexDirection:"column",paddingLeft:1},m.map((S,x)=>S.trim()===""?h.createElement(C,{key:`ln-${x}-empty`}," "):h.createElement(C,{key:`ln-${x}-${S.slice(0,15)}`,color:"white"},_o(S))))}),v&&T.length>0&&h.createElement(D,{flexDirection:"column",marginTop:1,paddingLeft:1},T.map((d,g)=>{let m=f(d.toolName||""),S=d.toolResult&&d.toolResult.length>0,x=d.toolResult?.includes("✓"),E=d.toolResult?.includes("✗")||d.toolResult?.includes("error");return h.createElement(D,{key:`tool-${g}-${d.toolName}`},h.createElement(C,{color:m.color},m.icon),h.createElement(C,{color:"gray"}," ",d.toolName),S&&h.createElement(C,{color:E?"red":x?"green":"gray"}," ",d.toolResult),!S&&h.createElement(C,{color:"gray",dimColor:!0}," …"))})),a.length>0&&h.createElement(Uo,{workingFiles:a}),o.length>0&&h.createElement(Mo,{suggestions:o,onSelect:e}))}return null}as();ne();ne();import U from"chalk";import Qo from"inquirer";var Ie=class{authService;constructor(){this.authService=H.getInstance()}async login(){console.log(U.blue(`
|
|
423
|
+
🔐 Orion Authentication`)),console.log(U.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(U.yellow(`
|
|
424
|
+
📋 To authenticate, please follow these steps:`)),console.log(U.white("1. Open this URL in a browser (on any device):")),console.log(U.cyan.underline(` ${e}`)),console.log(U.white("2. Log in with your Orion account")),console.log(U.white("3. Copy the access token shown after login")),console.log(U.white("4. Paste the token below")),console.log(U.yellow(`
|
|
425
|
+
Paste your access token here:`));let{accessToken:t}=await Qo.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(U.gray(`
|
|
426
|
+
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let n=await this.authService.getUserInfo();console.log(U.green(`
|
|
427
|
+
✅ Authentication successful!`)),n&&(console.log(U.gray(`Logged in as: ${n.email||n.username||"User"}`)),console.log(U.gray(`Subscription: ${this.getSubscriptionDisplay(n.subscription?.tier)}`)))}else console.log(U.red(`
|
|
428
|
+
❌ Authentication failed. Please try again.`))}catch(s){console.log(U.red(`
|
|
429
|
+
❌ Authentication error: ${s.message}`))}}async logout(){console.log(U.yellow(`
|
|
430
|
+
🔄 Signing out...`)),console.log(U.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(U.green(`
|
|
431
|
+
✅ Successfully signed out`)),console.log(U.gray("All authentication data and settings have been cleared.")),console.log(U.gray('Run "orion auth login" to sign in again.'))):(console.log(U.red(`
|
|
432
|
+
❌ Logout failed`)),console.log(U.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(U.green(`
|
|
433
|
+
✅ Authenticated`)),t){console.log(U.gray("─".repeat(50))),console.log(U.white("User:",t.name||t.username||"N/A")),console.log(U.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(U.white("Subscription:",s)),t.usage&&(console.log(U.gray(`
|
|
434
|
+
Usage:`)),console.log(U.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(U.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(U.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(U.yellow(`
|
|
435
|
+
⚠️ Not authenticated`)),console.log(U.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 fn=!1;async function cs(){if(fn){console.log("Already running...");return}fn=!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(s){console.error(`
|
|
436
436
|
❌ Failed to initialize services:`,s.message),console.error(`
|
|
437
437
|
💡 Tip: Check your internet connection and Firebase configuration.
|
|
438
438
|
`),process.exit(1)}}(!await e.autoAuthenticate()||!e.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
|
|
439
|
-
`),await new
|
|
439
|
+
`),await new Ie().login(),e.isAuthenticated()||(console.error(`
|
|
440
440
|
❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
|
|
441
441
|
✨ Starting Orion CLI...
|
|
442
442
|
`)),e.isFirebaseAuthenticated()||(console.error(`
|
|
443
443
|
❌ 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
444
|
Please check your connection and try again.
|
|
445
|
-
`),process.exit(1)),console.log("✅ Authentication verified"),
|
|
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
|
|
445
|
+
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),Yo(Jo.createElement(an),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1})}Pe();B();import{EventEmitter as Zo}from"events";import ei from"axios";import{execSync as ti}from"child_process";import vn from"chalk";var Nt=class c extends Zo{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 ei.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let s=e.split(".").map(Number),n=t.split(".").map(Number);for(let o=0;o<3;o++){let r=s[o]||0,a=n[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}`),ti(t,{stdio:"pipe",encoding:"utf8"}),console.log(vn.green(`✓ Updated to v${e}`)+vn.gray(` - restarting...
|
|
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 ni from"dotenv";import{fileURLToPath as oi}from"url";import{dirname as ii,join as ri}from"path";import{readFileSync as ai}from"fs";ni.config();var ci=oi(import.meta.url),li=ii(ci),yn=JSON.parse(ai(ri(li,"..","package.json"),"utf8")),ui=Nt.getInstance(yn.version);ui.checkAndUpdate().catch(()=>{});var Le=new si;Le.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(yn.version);Le.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await cs()}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(()=>(as(),hn)),s=t.getInstance();console.log("🔧 Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let n=X.find(r=>r.name===e.model)||X[0];console.log("💭 Sending message...");let o=await s.sendMessage(c,n,{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 ls=Le.command("auth").description("Authentication commands");ls.command("login").description("Login to Orion").action(async()=>{try{await new Ie().login()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});ls.command("logout").description("Logout from Orion").action(async()=>{try{await new Ie().logout()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});ls.command("status").description("Check authentication status").action(async()=>{try{await new Ie().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?cs().catch(c=>{console.error(te.formatError(c.message)),process.exit(1)}):Le.parse(process.argv);
|