@zinley/orion 1.2.7 → 1.2.10

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.
Files changed (2) hide show
  1. package/dist/index.js +294 -175
  2. package/package.json +14 -13
package/dist/index.js CHANGED
@@ -1,53 +1,59 @@
1
1
  #!/usr/bin/env node
2
- var _s=Object.defineProperty;var F=(c,e)=>()=>(c&&(e=c(c=0)),e);var te=(c,e)=>{for(var t in e)_s(c,t,{get:e[t],enumerable:!0})};var qt={};te(qt,{AccountStatus:()=>Gt,SNOWX_MODELS:()=>H,SignUpMethod:()=>Bt,SnowXProvider:()=>lt,TaskStatus:()=>Lt,TodoStatus:()=>Ut});var lt,H,Ut,Lt,Bt,Gt,we=F(()=>{"use strict";lt=(u=>(u.GPT="GPT",u.BEDROCK="BEDROCK",u.ANTHROPIC="ANTHROPIC",u.OPENAI="OPENAI",u.FOUNDRY="FOUNDRY",u.DEEPSEEK="deepseek",u.GOOGLE="google",u.X_AI="x-ai",u.QWEN="qwen",u))(lt||{}),H=[{name:"snowx-5h",displayName:"GPT-5 High",provider:"GPT",apiModelName:"gpt-5-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5c",displayName:"GPT-5",provider:"GPT",apiModelName:"gpt-5",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-c4.1",displayName:"Claude Opus 4.1",provider:"BEDROCK",apiModelName:"us.anthropic.claude-opus-4-20250514-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-c4",displayName:"Claude Opus 4",provider:"ANTHROPIC",apiModelName:"claude-opus-4",maxTokens:4096,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-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-o4-mini",displayName:"GPT o4-mini",provider:"GPT",apiModelName:"o4-mini",maxTokens:65536,contextWindow:128e3,supportsVision:!0,reasoningEffort:"low"},{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.0-flash-exp",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.0-flash-exp",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g4fr",displayName:"Grok-4 Fast Reasoning",provider:"x-ai",apiModelName:"grok-4-fast-reasoning",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-g4f",displayName:"Grok-4 Fast",provider:"x-ai",apiModelName:"grok-4-fast",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-d31",displayName:"DeepSeek-V3.1",provider:"deepseek",apiModelName:"DeepSeek-V3.1",maxTokens:8192,contextWindow:64e3,supportsVision:!1},{name:"snowx-q3",displayName:"Qwen3 Coder 480B A35B",provider:"qwen",apiModelName:"Qwen3-Coder-480B-A35B",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-q3-325",displayName:"Qwen3 235B A22B 2507",provider:"qwen",apiModelName:"Qwen3-235B-A22B-2507",maxTokens:8192,contextWindow:128e3,supportsVision:!1}],Ut=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s))(Ut||{}),Lt=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(Lt||{}),Bt=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(Bt||{}),Gt=(s=>(s.ACTIVE="active",s.SUSPENDED="suspended",s.PENDING="pending",s))(Gt||{})});var ut,o,U=F(()=>{"use strict";ut=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)}},o=ut.getInstance()});var ie={};te(ie,{UserDefaults:()=>de});import Ne from"fs";import dt from"path";import Ms from"os";var pt,de,Y=F(()=>{"use strict";U();pt=class c{static instance;preferencesPath;preferences={};constructor(){let e=dt.join(Ms.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(Ne.existsSync(this.preferencesPath)){let e=Ne.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),o.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{o.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=dt.dirname(this.preferencesPath);Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0}),Ne.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),o.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){o.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),o.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(),o.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},de=pt.getInstance()});var le,gt=F(()=>{"use strict";we();Y();U();le=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){switch(e){case"snowx-c4.1":case"snowx-c4":case"snowx-o3-pro":return 2;case"snowx-4.1":case"snowx-g2":case"snowx-5c":case"snowx-c1":case"snowx-h4":case"snowx-d31":case"snowx-q3":case"snowx-q3-325":return 0;case"snowx-5h":case"snowx-c5":case"snowx-c3":case"snowx-o3":case"snowx-o4-mini":case"snowx-g1":case"snowx-g4fr":case"snowx-g4f":default:return 1}}static getCurrentUserTier(){let e=de.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){de.set("userSubscriptionTier",e),o.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),i=t>=s;return o.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${s} (${this.getDisplayName(s)}), Access=${i}`),i}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return H.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 Ws from"axios";import{EventEmitter as Us}from"events";var ge,pe,Ue=F(()=>{"use strict";ge="firebase_timestamp",pe=class c extends Us{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Ws.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(()=>(Y(),ie));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(se(),Ht));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 i={"Content-Type":"application/json"};await this.addAuthorizationHeader(i);let n={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",n,{headers:i})).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 i={collection:e};t&&(i.limit=t.toString());try{let r=(await this.client.get("/documents",{params:i,headers:s})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async queryDocuments(e,t,s,i,n,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:s,value:String(i)};n&&(u.limit=n.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let h=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(h.success)return Array.isArray(h.doc)?h.doc:h.doc&&typeof h.doc=="object"?[h.doc]:[];{let m=h.error||"Unknown error";throw new Error(m)}}catch(g){throw g}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let i={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:i,headers:s})).data;return r.success?r.doc:null}catch(n){throw n}}async updateDocument(e,t,s){let i={"Content-Type":"application/json"};await this.addAuthorizationHeader(i);let n={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,n,{headers:i})).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 i={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:i,headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async createDocumentInSubcollection(e,t,s,i,n){let r=`${e}/${t}/${s}`;return this.createDocument(r,i,n)}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 i=await this.getDocuments(s);for(let n of i)n.id&&await this.deleteDocument(s,n.id);for(let[n,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${n}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:n,conversationId:e};try{await this.createDocument(s,a,l)}catch{}}}catch(i){throw i}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((i,n)=>{if(i.order!==void 0&&n.order!==void 0)return i.order-n.order;let r=new Date(i.timestamp||0).getTime(),a=new Date(n.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let i={path:e,updates:t};try{let r=(await this.client.put("/realtime",i,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=(await this.client.get("/realtime",{params:s,headers:t})).data;if(n.success)return n.doc;{let r=n.error||"Unknown error";throw new Error(r)}}catch(i){throw i}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!n.success){let r=n.error||"Unknown error";throw new Error(r)}}catch(i){throw i}}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 i=await this.client.get("/realtime",{params:s,headers:t}),n=i.data;if(n.success)return i.data.data;{let r=n.error||"Unknown error";throw new Error(r)}}catch(i){throw i}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let i={path:e,data:t};try{let r=(await this.client.post("/realtime",i,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let i={path:e,data:t};try{let r=(await this.client.post("/realtime/push",i,{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(n){throw n}}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 Ae={};te(Ae,{DeviceRegistrationService:()=>ne});import{EventEmitter as Ls}from"events";import{v4 as Xt}from"uuid";import mt from"os";import Vt from"fs/promises";import Bs from"path";import{execSync as ht}from"child_process";import Gs from"crypto";var ne,ue=F(()=>{"use strict";Ue();se();U();ne=class c extends Ls{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=pe.getInstance(),this.authService=q.getInstance(),this.configDir=Bs.join(mt.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){o.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{o.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{o.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();o.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(o.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){o.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),o.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(o.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,o.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),o.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw o.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}o.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),o.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){o.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return o.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){return mt.hostname()||"Unknown CLI Device"}async getHardwareDeviceId(){let e=mt.platform();try{let t=null;switch(e){case"darwin":try{let a=ht("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],o.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=ht("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],o.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Vt.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),o.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Vt.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),o.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{o.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=ht("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
- `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),o.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:o.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=Gs.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 o.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie)),i="snowx_fallback_device_id",n=s.string(i);return n?o.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${n}`):(n=Xt(),s.set(i,n),o.debug(`[DEVICE REG] Generated NEW fallback UUID: ${n}`)),n}catch(t){o.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie)),i="snowx_fallback_device_id",n=s.string(i);return n?o.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${n}`):(n=Xt(),s.set(i,n),o.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${n}`)),n}}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 i=await this.api.getDocument(this.devicesCollection,e);if(i&&i.devices){let n=i.devices;if(n.some(a=>a.deviceId===t)){let a=n.map(l=>l.deviceId===t?{...l,lastSeenAt:ge,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:ge,lastSeenAt:ge};n.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:n})}}else{let r={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:ge,lastSeenAt:ge}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}o.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:s})}catch(i){throw i}}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 i=s.devices;if(!i.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=i.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 Ht={};te(Ht,{AuthService:()=>q});import{EventEmitter as qs}from"events";import{signInAnonymously as Hs,signInWithEmailAndPassword as Xs,createUserWithEmailAndPassword as Vs,signOut as zs,onAuthStateChanged as js,updateProfile as Qs,signInWithCustomToken as Js}from"firebase/auth";import ye from"axios";import ft from"fs/promises";import zt from"path";import Ks from"os";var q,se=F(()=>{"use strict";gt();U();q=class c extends qs{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=zt.join(Ks.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=zt.dirname(this.tokenFilePath);await ft.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(Y(),ie)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let i=await ft.readFile(this.tokenFilePath,"utf-8"),n=JSON.parse(i);n.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",n.userId),e.set("snowx_access_token",n.token),t=n.userId,s=n.token,await ft.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&s){let i={token:s,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=i,o.debug("Session restored from UserDefaults");try{let n=await this.getUserProfile();n&&n.tier!==void 0?this.authToken.tier=n.tier:await this.updateUserTierFromToken(i)}catch(n){console.warn("⚠️ Failed to fetch user profile during session restore:",n instanceof Error?n.message:"Unknown error"),await this.updateUserTierFromToken(i)}this.emit("authenticated",i)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Y(),ie));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(()=>(Y(),ie));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,js(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}le.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),o.debug(`User tier updated: ${le.getDisplayName(t)} (${e.tier})`),o.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 Hs(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 Xs(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 i=await Vs(this.auth,e,t);return this.currentUser=i.user,s&&await Qs(i.user,{displayName:s}),!0}catch(i){return console.error("❌ Failed to sign up with email:",i.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(ue(),Ae));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await zs(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(()=>(ue(),Ae));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Y(),ie)),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 n=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of n)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(()=>(Y(),ie));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(!this.currentUser)return null;try{return await this.currentUser.getIdToken()}catch(e){return console.error("❌ Failed to get Firebase ID token:",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(){return!!this.currentUser}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId();if(e){o.debug("Using existing authentication token"),o.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(t){return o.error("Failed to authenticate with Firebase during auto-authenticate:",t.message),t.response?.status===401||t.response?.status===403||t.response?.status===404?(o.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):o.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!"),o.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!"),o.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}`),o.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),o.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..."),o.debug("Signing into Firebase with custom token...");let t=await Js(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),o.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"}`),o.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}`),o.debug(`Getting custom token from API for user: ${e} (attempt ${s}/3)`);let i="https://snowx.ai/api-beta/api/fb/custom-token",n={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: ${i}`);try{let l=await ye.post(i,n,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let g=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${g}`),new Error(`Custom token API failed: ${g}`)}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"),o.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)}`),o.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 g=Math.pow(2,s)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${g}ms... (${t-1} attempts remaining)`),o.debug(`Retrying in ${g}ms...`),await new Promise(h=>setTimeout(h,g)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}async authenticateWithAccessToken(e){try{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,i=s.id||s.uid||s.user_id||s.userId||s.email;if(!i)throw new Error("No user ID found in API response");let n={token:e,userId:i,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(n),this.userProfile=s,await this.updateUserTierFromToken(n);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(o.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):o.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",n),this.emit("AuthenticationComplete",i),!0}return!1}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 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 le.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}}});import{EventEmitter as Ys}from"events";var me,Le=F(()=>{"use strict";U();me=class c extends Ys{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),o.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),o.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 Be,jt=F(()=>{"use strict";U();Be=class{tools=new Map;register(e){for(let t of e.toolNames){let s=t.toLowerCase();this.tools.set(s,e),o.debug(`[ToolRegistry] Registered tool: ${t}`)}}getTool(e){return this.tools.get(e.toLowerCase())}async executeTool(e,t,s,i){let n=this.getTool(e);if(!n)throw new Error(`Unknown tool: ${e}`);return await n.execute(t,e,s,i)}getAllToolNames(){return Array.from(this.tools.keys())}}});var Qt={};te(Qt,{ToolDisplay:()=>B});import L from"chalk";var B,he=F(()=>{"use strict";B=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 i=this.getToolPrefix(e);if(console.log(L.cyan(`
4
- ${i} ${L.bold(e)}`)),t&&console.log(L.gray(` ${t}`)),s){let n=s.length>120?s.substring(0,120)+L.gray("..."):s;console.log(L.white(` ${n}`))}}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:i,executionTime:n,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=i?L.green("✓"):L.red("✗"),u=i?L.green("SUCCESS"):L.red("FAILED"),g=n?L.gray(` (${n}ms)`):"";console.log(`${l} ${u}${g}
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 vs={};se(vs,{ToolDisplay:()=>_});import G from"chalk";var _,ae=F(()=>{"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(G.cyan(`
5
+ ${n} ${G.bold(e)}`)),t&&console.log(G.gray(` ${t}`)),s){let o=s.length>120?s.substring(0,120)+G.gray("..."):s;console.log(G.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?G.green("✓"):G.red("✗"),u=n?G.green("SUCCESS"):G.red("FAILED"),p=o?G.gray(` (${o}ms)`):"";console.log(`${l} ${u}${p}
5
6
  `)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
6
- `),u=a.slice(0,20).map(g=>L.gray(" ")+g).join(`
7
+ `),u=a.slice(0,20).map(p=>G.gray(" ")+p).join(`
7
8
  `);return a.length>20&&(u+=`
8
- `+L.gray(` ... (${a.length-20} more lines)`)),u}let s=e.split(`
9
- `),i=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),n="";i&&(n+=L.gray(" ")+L.dim(i[1])+`
10
- `);let r=s.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(n+=r.slice(0,10).map(a=>L.gray(" ")+L.dim(a)).join(`
11
- `),r.length>10&&(n+=`
12
- `+L.gray(` ... (${r.length-10} more changes)`)),n):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(`
13
- `).filter(r=>r.trim());if(s.length===0)return"";if(s.length<=t)return s.map(r=>L.gray(" ")+L.dim(r)).join(`
14
- `);let n=s.slice(0,t).map(r=>L.gray(" ")+L.dim(r)).join(`
15
- `);return n+=`
16
- `+L.gray(` ... (${s.length-t} more lines)`),n}static error(e,t){c.customUIMode||(console.log(`
17
- ${L.red("✗")} ${L.red.bold(e)} ${L.red("ERROR")}`),console.log(L.gray(" ")+L.white(t)),console.log(""))}}});var Ge,Jt=F(()=>{"use strict";U();he();Ge=class{toolNames=["read","Read"];async execute(e,t,s,i){let n=s.file_path||s.path,r=s.offset,a=s.limit;if(!n)throw new Error("Missing file_path or path argument");o.debug(`[ReadFileTool] Reading file: ${n}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let l=Date.now();B.start("Read",s.description,n);try{let u=await import("fs/promises");try{await u.access(n)}catch{return[{type:"text",text:`Error: File does not exist at path: ${n}`}]}let g=await u.stat(n);if(g.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${n}`}];let h=await u.readFile(n,"utf-8"),m=h.length,S=h.split(`
18
- `),w=S.length,p=Math.max(r??0,0),v=87500;if(m>v&&r===void 0&&a===void 0){let E=g.size/1024,_=E/1024,A=_>=1?`${_.toFixed(2)} MB`:`${E.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
9
+ `+G.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+=G.gray(" ")+G.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=>G.gray(" ")+G.dim(a)).join(`
12
+ `),r.length>10&&(o+=`
13
+ `+G.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=>G.gray(" ")+G.dim(r)).join(`
15
+ `);let o=s.slice(0,t).map(r=>G.gray(" ")+G.dim(r)).join(`
16
+ `);return o+=`
17
+ `+G.gray(` ... (${s.length-t} more lines)`),o}static error(e,t){c.customUIMode||(console.log(`
18
+ ${G.red("✗")} ${G.red.bold(e)} ${G.red("ERROR")}`),console.log(G.gray(" ")+G.white(t)),console.log(""))}}});import ys from"os";import Ft from"path";function Qe(){return process.platform==="win32"}function Ce(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,ys.homedir())),Qe()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,ys.homedir())),!Qe()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),Qe()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Ee(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=Ce(c);if(Qe()){let s=Ft.basename(e).split(".")[0].toUpperCase();if($n.includes(s))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${s}`}}return Ft.isAbsolute(e)?Ft.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
19
+
20
+ Path must be absolute (start with / on Unix or C:\\ on Windows)
21
+
22
+ Wrong: Downloads/file.pdf
23
+ Correct: /Users/username/Downloads/file.pdf`}}var $n,Je=F(()=>{"use strict";$n=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});var Ye,bs=F(()=>{"use strict";B();ae();Je();Ye=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=Ce(o),u=Ee(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"),w=b.length,d=b.split(`
24
+ `),g=d.length,m=Math.max(r??0,0),T=87500;if(w>T&&r===void 0&&a===void 0){let P=v.size/1024,$=P/1024,D=$>=1?`${$.toFixed(2)} MB`:`${P.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
19
25
 
20
26
  File Information:
21
- - Path: ${n}
22
- - Size: ${A} (${m} characters)
23
- - Total Lines: ${w}
24
- - Character Limit: ${v.toLocaleString()}
27
+ - Path: ${l}
28
+ - Size: ${D} (${w} characters)
29
+ - Total Lines: ${g}
30
+ - Character Limit: ${T.toLocaleString()}
25
31
 
26
32
  Suggested Solutions:
27
33
  1. Read specific lines using offset and limit:
28
- Read(path: "${n}", offset: 0, limit: 2000)
34
+ Read(path: "${l}", offset: 0, limit: 2000)
29
35
 
30
36
  2. Search for specific content:
31
- Grep(pattern: "your_search_term", path: "${n}")
37
+ Grep(pattern: "your_search_term", path: "${l}")
32
38
 
33
39
  3. Read in chunks:
34
- - Lines 0-2000: Read(path: "${n}", offset: 0, limit: 2000)
35
- - Lines 2000-4000: Read(path: "${n}", offset: 2000, limit: 2000)
40
+ - Lines 0-2000: Read(path: "${l}", offset: 0, limit: 2000)
41
+ - Lines 2000-4000: Read(path: "${l}", offset: 2000, limit: 2000)
36
42
  - And so on...
37
43
 
38
- The file has ${w.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(w===0||h.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(p>=w)return[{type:"text",text:`Error: Offset ${p} is beyond file length. File has ${w} total lines. Try a smaller offset (0 to ${w-1}).`}];let f=a!==void 0?Math.min(p+a,w):w,x=S.slice(p,f),P=x.map((E,_)=>`${(p+_+1).toString().padStart(6," ")} ${E}`).join(`
39
- `),D=P;if(r!==void 0||a!==void 0){let E=`
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 k=a!==void 0?Math.min(m+a,g):g,E=d.slice(m,k),y=E.map((P,$)=>`${(m+$+1).toString().padStart(6," ")} ${P}`).join(`
45
+ `),x=y;if(r!==void 0||a!==void 0){let P=`
40
46
 
41
- [Read ${x.length} lines (${p+1}-${f}) of ${w} total lines]`;D=P+E}let C=Date.now()-l;return B.result({toolName:"Read",filePath:n,output:D,success:!0,executionTime:C}),[{type:"text",text:D}]}catch(u){o.debug(`[ReadFileTool] Failed to read file: ${u.message}`);let g;u.code==="ENOENT"?g=`Error: File does not exist at path: ${n}`:u.code==="EACCES"?g=`Error: Permission denied. Cannot read file: ${n}`:u.code==="EISDIR"?g=`Error: Path is a directory, not a file: ${n}`:g=`Error reading file: ${u.message}`;let h=Date.now()-l;return B.result({toolName:"Read",filePath:n,output:g,success:!1,executionTime:h}),[{type:"text",text:g}]}}}});import vt from"fs/promises";import Zs from"form-data";import bt from"axios";import St from"path";var qe,Kt=F(()=>{"use strict";U();he();qe=class{toolNames=["read_special_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm"];async execute(e,t,s,i){let n=s.path;if(!n)throw new Error("Missing path argument");o.debug(`[ReadSpecialFileTool] Converting file: ${n}`);let r=Date.now();B.start("ReadSpecialFile",s.description,n);try{try{await vt.access(n)}catch{return[{type:"text",text:`Error: File does not exist at path: ${n}`}]}let a=St.extname(n).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let P=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), and web files (html, htm). For plain text files, use the run_command tool with 'cat' instead.
47
+ [Read ${E.length} lines (${m+1}-${k}) of ${g} total lines]`;x=y+P}let O=Date.now()-p;return _.result({toolName:"Read",filePath:l,output:x,success:!0,executionTime:O}),[{type:"text",text:x}]}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 Ze from"fs/promises";import On from"form-data";import $t from"axios";import Ot from"path";var et,ws=F(()=>{"use strict";B();ae();Z();et=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 Ze.access(o)}catch{return[{type:"text",text:`Error: File does not exist at path: ${o}`}]}let a=Ot.extname(o).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let k=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.
42
48
 
43
- Supported file types: ${P}`}]}let l=await vt.stat(n),u=St.basename(n);o.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`);let g=await this.uploadToBatchAPI(n,u);o.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${g}`);let h=await this.pollBatchStatus(g);o.debug("[ReadSpecialFileTool] Conversion completed");let m=h.files[0];if(!m||m.status==="failed"){let P=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${P}`}]}let S=await this.fetchFileContent(m.file_id);if(!S.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let w=l.size/1024,p=w/1024,v=p>=1?`${p.toFixed(2)} MB`:`${w.toFixed(2)} KB`,f=`# File: ${u}
49
+ Supported file types: ${k}`}]}let l=await Ze.stat(o),u=Ot.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 Ze.readFile(o)).toString("base64"),y=this.imageMimeTypes[a]||"application/octet-stream";i.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${E.length} chars)`);let x=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:x}),[{type:"image_url",image_url:{url:`data:${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 k=v?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${k}`}]}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 w=l.size/1024,d=w/1024,g=d>=1?`${d.toFixed(2)} MB`:`${w.toFixed(2)} KB`,m=`# File: ${u}
44
50
  **Type:** ${a.toUpperCase()}
45
- **Size:** ${v}
51
+ **Size:** ${g}
46
52
  **Conversion:** ✅ Successful
47
53
 
48
54
  ---
49
55
 
50
- ${S.markdown_content}`,x=Date.now()-r;return B.result({toolName:"ReadSpecialFile",filePath:n,output:`Successfully converted ${u} (${v})`,success:!0,executionTime:x}),[{type:"text",text:f}]}catch(a){o.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
56
+ ${b.markdown_content}`,T=Date.now()-r;return _.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${g})`,success:!0,executionTime:T}),[{type:"text",text:m}]}catch(a){i.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
51
57
 
52
58
  This could be due to:
53
59
  • File corruption or invalid format
@@ -55,34 +61,93 @@ This could be due to:
55
61
  • Unsupported document structure
56
62
  • File is password-protected or encrypted
57
63
 
58
- For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-r;return B.result({toolName:"ReadSpecialFile",filePath:n,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let s=await vt.readFile(e),i=St.extname(t).substring(1).toLowerCase(),n=new Zs;n.append("files",s,{filename:t,contentType:this.getMimeType(i)});try{let r=await bt.post(`${this.baseEndpoint}/convert-batch`,n,{headers:n.getHeaders(),timeout:3e4});if(r.status!==202)throw new Error(`Upload failed with HTTP ${r.status}`);return r.data.request_id}catch(r){throw r.response?new Error(`Upload failed (HTTP ${r.response.status}): ${JSON.stringify(r.response.data)}`):new Error(`Upload failed: ${r.message}`)}}async pollBatchStatus(e){for(let t=1;t<=this.maxPollAttempts;t++)try{let i=(await bt.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4})).data;if(o.debug(`[ReadSpecialFileTool] Poll ${t} - Status: ${i.files[0]?.status}, Progress: ${i.completed}/${i.total_files}`),i.completed+i.failed>=i.total_files)return i;await this.sleep(this.pollInterval)}catch(s){throw s.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${s.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){try{let t=await bt.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4});if(t.data.status==="failed")throw new Error(t.data.error||"Unknown conversion error");return t.data}catch(t){throw t.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${t.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 He,Yt=F(()=>{"use strict";U();he();He=class{toolNames=["write","Write","write_file"];async execute(e,t,s,i){let n=s.file_path,r=s.content,a=s.edits;if(!n)throw new Error("Missing file_path argument");let l=Date.now();return B.start("Write",s.description,n),r!=null?await this.executeSimpleWrite(n,r,l):await this.executeEditsMode(n,a,l)}async executeSimpleWrite(e,t,s){o.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let i=await import("fs/promises"),r=(await import("path")).dirname(e);await i.mkdir(r,{recursive:!0}),await i.writeFile(e,t,"utf-8");let a=t.split(`
59
- `),l="";for(let h=0;h<Math.min(a.length,8);h++)l+=`+ ${a[h]}
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 Ze.readFile(e),n=Ot.extname(t).substring(1).toLowerCase(),r=await H.getInstance().getFirebaseIdToken(),a=new On;a.append("files",s,{filename:t,contentType:this.getMimeType(n)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await $t.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 $t.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 $t.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 tt,Ts=F(()=>{"use strict";B();ae();Je();tt=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=Ce(o),u=Ee(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
+ `),l="";for(let f=0;f<Math.min(a.length,8);f++)l+=`+ ${a[f]}
60
66
  `;a.length>8&&(l+=`+ ...
61
67
 
62
- (${a.length-8} more lines)`);let u=l.trim();o.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let g=Date.now()-s;return B.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:g}),[{type:"text",text:u}]}catch(i){o.debug(`[WriteFileTool] Failed to write file: ${i.message}`);let n=`Error writing file: ${i.message}`,r=Date.now()-s;return B.result({toolName:"Write",filePath:e,output:n,success:!1,executionTime:r}),[{type:"text",text:n}]}}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.");o.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let i=await import("fs/promises"),n=await import("path");if(!e||typeof e!="string")throw new Error("Invalid file_path parameter");if(e.startsWith("~/"))throw new Error(`Home directory shortcut not allowed ('${e}'). Use full absolute path instead.`);if(!e.startsWith("/")&&!e.includes(":\\"))throw new Error(`File path appears to be relative ('${e}'). Use full absolute path starting from root.`);for(let S=0;S<t.length;S++){let w=t[S];if(!w||typeof w!="object")throw new Error(`Edit operation ${S+1} must be an object with 'search' and 'replace' fields`);if(!w.hasOwnProperty("search")||typeof w.search!="string")throw new Error(`Edit operation ${S+1} missing required 'search' field (must be string)`);if(!w.hasOwnProperty("replace")||typeof w.replace!="string")throw new Error(`Edit operation ${S+1} missing required 'replace' field (must be string)`)}let r=t[0].search==="",a;if(r)if(o.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let S=n.dirname(e);await i.mkdir(S,{recursive:!0}),await i.writeFile(e,a,"utf-8");let w=a.split(`
63
- `),p="";for(let v=0;v<Math.min(w.length,8);v++)p+=`+ ${w[v]}
64
- `;return w.length>8&&(p+=`+ ...
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 w=t[b];if(!w||typeof w!="object")throw new Error(`Edit operation ${b+1} must be an object with 'search' and 'replace' fields`);if(!w.hasOwnProperty("search")||typeof w.search!="string")throw new Error(`Edit operation ${b+1} missing required 'search' field (must be string)`);if(!w.hasOwnProperty("replace")||typeof w.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 w=a.split(`
69
+ `),d="";for(let g=0;g<Math.min(w.length,8);g++)d+=`+ ${w[g]}
70
+ `;return w.length>8&&(d+=`+ ...
65
71
 
66
- (${w.length-8} more lines)`),o.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:p.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{o.debug("[WriteFileTool] Reading existing file");try{a=await i.readFile(e,"utf-8"),o.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(S){throw S.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: ${S.message}`)}}let l=0,u=a,g=[];for(let S=0;S<t.length;S++){let w=t[S];if(o.debug(`[WriteFileTool] Applying edit ${S+1}/${t.length}`),w.search==="")if(r){g.push({index:S+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{o.debug("[WriteFileTool] Rewriting entire existing file"),u=w.replace,g.push({index:S+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let p=u.indexOf(w.search);if(p!==-1)u=u.substring(0,p)+w.replace+u.substring(p+w.search.length),o.debug("[WriteFileTool] Replaced first occurrence"),g.push({index:S+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let v=`Search string not found: '${w.search}'`;return g.push({index:S+1,success:!1,message:v,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${S+1}: '${w.search}'\\n\\nEdit Summary:\\n- Total edits: ${g.length}\\n- Successful: ${g.filter(x=>x.success).length}\\n- Failed: ${g.filter(x=>!x.success).length}\\n\\nIndividual Edit Results:\\n`+g.map(x=>`${x.success?"✅":"❌"} Edit ${x.index}: ${x.message}`).join("\\n")}]}}await i.writeFile(e,u,"utf-8"),o.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let h=u.split(`
67
- `),m="";for(let S=0;S<Math.min(h.length,8);S++)m+=`+ ${h[S]}
68
- `;return h.length>8&&(m+=`+ ...
72
+ (${w.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 w=t[b];if(i.debug(`[WriteFileTool] Applying edit ${b+1}/${t.length}`),w.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=w.replace,p.push({index:b+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let d=u.indexOf(w.search);if(d!==-1)u=u.substring(0,d)+w.replace+u.substring(d+w.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: '${w.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}: '${w.search}'\\n\\nEdit Summary:\\n- Total edits: ${p.length}\\n- Successful: ${p.filter(T=>T.success).length}\\n- Failed: ${p.filter(T=>!T.success).length}\\n\\nIndividual Edit Results:\\n`+p.map(T=>`${T.success?"✅":"❌"} Edit ${T.index}: ${T.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
+ `),v="";for(let b=0;b<Math.min(f.length,8);b++)v+=`+ ${f[b]}
74
+ `;return f.length>8&&(v+=`+ ...
69
75
 
70
- (${h.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(i){return o.debug(`[WriteFileTool] Failed to write file: ${i.message}`),[{type:"text",text:`Error writing file: ${i.message}`}]}}}});var Xe,Zt=F(()=>{"use strict";U();he();Xe=class{toolNames=["edit","Edit"];async execute(e,t,s,i){let n=s.file_path,r=s.old_string,a=s.new_string,l=s.replace_all===!0;if(!n)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");o.debug(`[EditFileTool] Editing file: ${n}`);let u=Date.now();B.start("Edit",s.description,n);try{let g=await import("fs/promises"),h=await g.readFile(n,"utf-8"),m,S=0;if(l)for(m=h;m.includes(r);)m=m.replace(r,a),S++;else h.includes(r)?(m=h.replace(r,a),S=1):m=h;if(S===0){let x=`No matches found for the specified old_string in file: ${n}`,P=Date.now()-u;return B.result({toolName:"Edit",filePath:n,output:x,success:!1,executionTime:P}),[{type:"text",text:x}]}await g.writeFile(n,m,"utf-8");let w=`Successfully edited file: Replaced ${S} occurrence(s)`;o.debug(`[EditFileTool] ${w}`);let p=Date.now()-u,v=(await import("chalk")).default,f=`${v.red("- "+r.split(`
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 st,Ss=F(()=>{"use strict";B();ae();Je();st=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=Ce(o),p=Ee(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"),w,d=0;if(l)for(w=b;w.includes(r);)w=w.replace(r,a),d++;else b.includes(r)?(w=b.replace(r,a),d=1):w=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,w,"utf-8");let g=`Successfully edited file: Replaced ${d} occurrence(s)`;i.debug(`[EditFileTool] ${g}`);let m=Date.now()-f,T=(await import("chalk")).default,k=`${T.red("- "+r.split(`
71
77
  `).slice(0,5).join(`
72
78
  - `))}
73
- ${v.green("+ "+a.split(`
79
+ ${T.green("+ "+a.split(`
74
80
  `).slice(0,5).join(`
75
81
  + `))}
76
82
 
77
- Replaced ${S} occurrence(s)`;return B.result({toolName:"Edit",filePath:n,output:f,success:!0,executionTime:p}),[{type:"text",text:w}]}catch(g){o.debug(`[EditFileTool] Failed to edit file: ${g.message}`);let h=`Error editing file: ${g.message}`,m=Date.now()-u;return B.result({toolName:"Edit",filePath:n,output:h,success:!1,executionTime:m}),[{type:"text",text:h}]}}}});var Ve,es=F(()=>{"use strict";U();Ve=class{toolNames=["upload_file"];async execute(e,t,s,i){let n=s.file_path;if(!n)throw new Error("Missing file_path argument");return o.debug(`[UploadFileTool] Upload file not implemented for CLI: ${n}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${n}`}]}}});var ts=F(()=>{"use strict"});function Re(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"]),i=new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","basename","dirname","stat","file","du","df","free","uptime","ps"]),n=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)||i.has(t)&&c.length<100?Te.fast:n.has(t)?Te.extended:c.length<20?Te.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?Te.default:Te.extended:Te.default}var Te,wt=F(()=>{"use strict";ts();Te={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as en}from"child_process";var Pe,ss=F(()=>{"use strict";wt();Pe=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,s,i,n="new",r){let a=r||Re(e);return this.executeInNewProcess(e,a)}async executeInNewProcess(e,t){return new Promise(s=>{let i=en("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"]}),n="",r="",a=!1,l=setTimeout(()=>{i.killed||(a=!0,console.log("⏰ Timeout reached, sending SIGTERM..."),i.kill("SIGTERM"),setTimeout(()=>{i.killed||(console.log("❌ Process didn't respond to SIGTERM, sending SIGKILL..."),i.kill("SIGKILL"))},5e3))},t.maxTimeout);i.stdout.on("data",u=>{n+=u.toString()}),i.stderr.on("data",u=>{r+=u.toString()}),i.on("close",u=>{clearTimeout(l);let g=(n+r).trim(),h=3e4;if(g.length>h){let m=g.substring(0,h),w=m.split(`
78
- `).length,p=g.length;g=m+`
83
+ Replaced ${d} occurrence(s)`;return _.result({toolName:"Edit",filePath:u,output:k,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}`,w=Date.now()-f;return _.result({toolName:"Edit",filePath:u,output:b,success:!1,executionTime:w}),[{type:"text",text:b}]}}}});var nt,Cs=F(()=>{"use strict";B();nt=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 _t from"fs/promises";import _n from"path";import Mn from"form-data";import Un from"axios";var ot,xs=F(()=>{"use strict";B();ae();Z();ot=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 O=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 ${O} seconds.`)}i.debug(`[DeployZipHTML] Deploying HTML project: ${o}`);try{await _t.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 _t.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 _t.readFile(o),f=_n.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 w=new Mn;w.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 Un.post(d,w,{headers:{...w.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 T=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,k=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let y=`# HTML Project Deployed Successfully!
79
84
 
80
- [Output truncated at `+h+` characters]
81
- [Showing first `+w+` lines of output]
82
- [Total output was `+p+" characters]",console.log("⚠️ Output truncated: "+p+" chars -> "+h+" chars")}a?(console.log("⏰ Command timed out"),s({output:g+`
85
+ **Deployment URL**: ${T}
83
86
 
84
- Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1})):s({output:g,exitCode:u||0,isSuccess:(u||0)===0})}),i.on("error",u=>{clearTimeout(l),s({output:"Process execution failed: "+u.message+`
85
- Command: `+e,exitCode:-1,isSuccess:!1})})})}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}`: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 yt={};te(yt,{ToolCallingService:()=>Oe});import{EventEmitter as tn}from"events";import ns from"axios";import{exec as sn,spawn as os}from"child_process";import{promisify as nn}from"util";import z from"fs/promises";import re from"fs";import Ce from"path";import on from"os";var Pi,Oe,ze=F(()=>{"use strict";ss();wt();Pi=nn(sn),Oe=class _ToolCallingService extends tn{static instance;tools=new Map;executionHistory=[];maxResponseCharacters=87500;shellSessionManager=Pe.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.
87
+ **Project**: ${f}
88
+ **Type**: Static HTML
89
+ ${k?`**Deploy ID**: ${k}
90
+ `:""}${E?`**Site ID**: ${E}
91
+ `:""}
92
+ Your site is now live and accessible!
93
+
94
+ ${m.message||""}`,x=Date.now()-r;return _.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${T}`,success:!0,executionTime:x}),[{type:"text",text:y}]}catch(a){i.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let l=`HTML deployment failed
95
+
96
+ ${a.message}
97
+
98
+ Troubleshooting:
99
+ 1. Ensure you're authenticated with Firebase
100
+ 2. Check if the ZIP file exists and is valid
101
+ 3. Verify the ZIP contains an index.html file
102
+ 4. Check network connectivity
103
+ 5. Ensure ZIP file is under 100MB
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 Mt from"fs/promises";import Ln from"path";import Wn from"form-data";import Bn from"axios";var it,ks=F(()=>{"use strict";B();ae();Z();it=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 O=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 ${O} seconds.`)}i.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await Mt.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 Mt.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 Mt.readFile(o),f=Ln.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 w=new Wn;w.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 Bn.post(d,w,{headers:{...w.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 T=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,k=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let y=`# React Project Deployed Successfully!
106
+
107
+ **Deployment URL**: ${T}
108
+
109
+ **Project**: ${f}
110
+ **Type**: React / SPA
111
+ ${k?`**Deploy ID**: ${k}
112
+ `:""}${E?`**Site ID**: ${E}
113
+ `:""}
114
+ Your React app is now live and accessible!
115
+
116
+ ${m.message||""}`,x=Date.now()-r;return _.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${T}`,success:!0,executionTime:x}),[{type:"text",text:y}]}catch(a){i.error(`[DeployZipReact] Deployment failed: ${a.message}`);let l=`React deployment failed
117
+
118
+ ${a.message}
119
+
120
+ Troubleshooting:
121
+ 1. Ensure you're authenticated with Firebase
122
+ 2. Check if the ZIP file exists and is valid
123
+ 3. Verify the ZIP contains a built React app (build/ or dist/ folder)
124
+ 4. Check network connectivity
125
+ 5. Ensure ZIP file is under 100MB
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 Es=F(()=>{"use strict"});function Ue(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?xe.fast:o.has(t)?xe.extended:c.length<20?xe.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?xe.default:xe.extended:xe.default}var xe,Ut=F(()=>{"use strict";Es();xe={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as Hn,exec as Gn}from"child_process";import{promisify as qn}from"util";function Lt(){return process.platform}function Le(){return process.platform==="win32"}function Xn(){return process.platform==="darwin"}function Is(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(Le()&&(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 jn(){return Le()?"PowerShell or Command Prompt":(Xn(),"Terminal")}function Ps(c,e){let t=jn();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
128
+
129
+ Reason: ${e}
130
+
131
+ The Bash tool cannot execute privileged commands because:
132
+ - It cannot prompt for passwords interactively
133
+ - It runs in a sandboxed environment without sudo access
134
+ - Security best practices prevent automated privilege escalation
135
+
136
+ To run this command:
137
+ 1. Open ${t}
138
+ 2. Run the command manually: ${c}
139
+ 3. Enter your password when prompted
140
+
141
+ Alternative: Break down the task into non-privileged commands if possible.`}var zn,We,Wt=F(()=>{"use strict";Ut();zn=qn(Gn);We=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||Ue(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Le())await zn(`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=Lt(),r,a;Le()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=Hn(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Le()}),u="",p="",f=!1,v=!1,b=null,w=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
+
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(w),b&&clearTimeout(b);let g=Date.now()-n,m=(u+p).trim(),T=3e4;if(m.length>T){let k=m.substring(0,T),y=k.split(`
144
+ `).length,x=m.length;m=k+`
145
+
146
+ [Output truncated at `+T+` characters]
147
+ [Showing first `+y+` lines of output]
148
+ [Total output was `+x+" characters]"}s(f?{output:m+`
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(w),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 Bt={};se(Bt,{ToolCallingService:()=>Be});import{EventEmitter as Vn}from"events";import Ds from"axios";import{exec as Kn,spawn as As}from"child_process";import{promisify as Qn}from"util";import K from"fs/promises";import ue from"fs";import Ie from"path";import Jn from"os";var ta,Be,rt=F(()=>{"use strict";Wt();Ut();ta=Qn(Kn),Be=class _ToolCallingService extends Vn{static instance;tools=new Map;executionHistory=[];maxResponseCharacters=87500;shellSessionManager=We.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.
86
151
 
87
152
  🔧 SESSION MODE SELECTION (REQUIRED):
88
153
  • Use session: "existing" for workflows that need persistent state:
@@ -116,13 +181,13 @@ Command: `+e,exitCode:-1,isSuccess:!1})})})}formatExitCodeInfo(e){let t;switch(e
116
181
  4. LLM receives prompt details and makes decision
117
182
  5. LLM uses provide_input to send appropriate response
118
183
  6. Command execution continues with provided input
119
- 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(n){throw new Error(`Invalid arguments for tool '${t}': ${n}`)}let{ToolDisplay:i}=await Promise.resolve().then(()=>(he(),Qt));i.start(t,s.description,s.command||s.file_path);try{let n=this.tools.get(t);if(!n)throw new Error(`Tool '${t}' not found`);if(!n.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await n.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}),i.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(n){let r=Date.now()-e,a={success:!1,error:n.message};return this.emit("tool_execution_error",{toolName:t,error:n,executionTime:r}),i.error(t,n.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(()=>(ae(),Ee)),s=t.getInstance(),i=this.extractOutputForDisplay(e);s.captureFrontendToolResult(c,i,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 ns.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,i=[];if(s.AbstractText&&i.push({title:s.Heading||"Instant Answer",content:s.AbstractText,url:s.AbstractURL||"",type:"instant_answer"}),s.RelatedTopics&&s.RelatedTopics.length>0)for(let n of s.RelatedTopics.slice(0,c.num_results||5))n.Text&&i.push({title:n.Text.split(" - ")[0]||"Related Topic",content:n.Text,url:n.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:i,total_results:i.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await z.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")&&re.existsSync(e)){let n=await z.readFile(e,"utf-8"),r=JSON.parse(n);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 z.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}re.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let i=Ce.dirname(e);return await z.mkdir(i,{recursive:!0}),s==="append"?await z.appendFile(e,t):await z.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 z.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let i=await z.stat(Ce.join(c.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:i.size,modified:i.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=Pe.parseSessionMode(c.session),t=Re(c.command),s={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},i=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,s);return{success:i.isSuccess,result:{command:c.command,stdout:i.output,stderr:"",exit_code:i.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 ns({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=os("/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",g=>{let h=g.toString();if(h){let m=this.backgroundProcesses.get(r);m&&(m.stdout+=h,this.backgroundProcesses.set(r,m))}}),a.stderr.on("data",g=>{let h=g.toString();if(h){let m=this.backgroundProcesses.get(r);m&&(m.stderr+=h,this.backgroundProcesses.set(r,m))}}),a.on("close",g=>{let h=this.backgroundProcesses.get(r);h&&(h.exitCode=g||0,this.backgroundProcesses.set(r,h),console.log(`✅ Background process ${r} finished with exit code: ${g}`))}),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(()=>(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}
120
185
  PID: ${a.pid}
121
186
  Command: ${e}
122
187
 
123
188
  Note: The process will continue running in the background.
124
- Output will be collected automatically.`;return console.log(`✅ Started background process ${r} (PID: ${a.pid})`),{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let i=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:Re(e),n=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",i);return{success:n.isSuccess,result:{command:e,stdout:n.output,stderr:"",exit_code:n.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:i=!1}=c;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&re.existsSync(e)){let a=await z.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let g=l.cells[u],h=Array.isArray(g.source)?g.source.join(""):g.source;if(h.includes(t)){let m=i?h.replaceAll(t,s):h.replace(t,s);return l.cells[u].source=m,await z.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:i?h.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 n=await z.readFile(e,"utf-8");if(!n.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let r=i?n.replaceAll(t,s):n.replace(t,s);if(r===n)throw new Error("Edit failed: File content unchanged after replacement");return await z.writeFile(e,r,"utf-8"),this.cacheFileState(e,r),{success:!0,result:{file_path:e,replacements:i?n.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:i="files_with_matches",case_insensitive:n=!1}=c,r=[];return n&&r.push("-i"),i==="files_with_matches"?r.push("-l"):i==="count"&&r.push("-c"),s&&r.push("--glob",s),r.push(e,t),new Promise(a=>{let l=os("rg",r,{stdio:["ignore","pipe","pipe"]}),u="",g="";l.stdout.on("data",h=>{u+=h.toString()}),l.stderr.on("data",h=>{g+=h.toString()}),l.on("close",h=>{if(h!==0&&h!==1){a({success:!1,error:`ripgrep failed: ${g||"Unknown error"}`});return}let m=u.trim().split(`
125
- `).filter(w=>w),S=m.length;a({success:!0,result:{pattern:e,num_files:S,files:m,output:u.trim()}})}),l.on("error",h=>{a({success:!1,error:`Failed to execute ripgrep: ${h.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,i=(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),n=[],r=async a=>{try{let l=await z.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let g=Ce.join(a,u.name),h=Ce.relative(t,g);u.isDirectory()?await r(g):(i.test(h)||i.test(u.name))&&n.push(g)}}catch{}};return await r(t),{success:!0,result:{pattern:e,num_files:n.length,files:n}}}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:i="code",edit_mode:n="replace"}=c;if(!re.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 z.readFile(e,"utf-8"),a=JSON.parse(r);switch(n){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(!i)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:i,source:s,metadata:{},execution_count:i==="code"?null:void 0,outputs:i==="code"?[]:void 0};if(t){let u=a.cells.findIndex(g=>g.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: ${n}`)}return await z.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:n,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=re.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(re.existsSync(c)){let s=await z.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(re.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,i=new Map;this.executionHistory.forEach(r=>{i.set(r.toolName,(i.get(r.toolName)||0)+1)});let n=i.size>0?Array.from(i.entries()).reduce((r,a)=>a[1]>r[1]?a:r)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(s),mostUsed:n}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){console.log(`[ToolCalling] Session cleanup not needed for 'new' mode (session: ${c||"none"})`)}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=on.tmpdir(),s=Ce.join(t,"orion_tool_responses");re.existsSync(s)||re.mkdirSync(s,{recursive:!0});let i=Math.floor(Date.now()/1e3),n=Math.random().toString(36).substring(2,10),r=`${e}_${i}_${n}.txt`,a=Ce.join(s,r);return re.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.
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}:Ue(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")&&ue.existsSync(e)){let a=await K.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 K.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 K.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 K.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=As("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(w=>w),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 K.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let p=Ie.join(a,u.name),f=Ie.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(!ue.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 K.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 K.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=ue.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(ue.existsSync(c)){let s=await K.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(ue.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=Jn.tmpdir(),s=Ie.join(t,"orion_tool_responses");ue.existsSync(s)||ue.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=Ie.join(s,r);return ue.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.
126
191
 
127
192
  `;return s+=`📁 TEMP FILE PATH: ${e}
128
193
  `,s+=`🔍 Use read_file, grep, cat, or other tools to access the full content.
@@ -135,19 +200,19 @@ ${"─".repeat(50)}`,s+=`
135
200
 
136
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)+`
137
202
 
138
- ... (truncated due to size limit)`}stopAllRunningTools(){}}});var je,is=F(()=>{"use strict";U();je=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,i){let n=s.command,r=s.session||"new",a=s.description,l=s.timeout,u=s.run_in_background;if(!n)throw new Error("Missing command argument");if(n.trim().length===0)throw new Error("Command cannot be empty");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 g=l||12e4;o.debug(`[RunCommandTool] Executing bash command: ${n.substring(0,50)}${n.length>50?"...":""}`),a&&o.debug(`[RunCommandTool] Description: ${a}`),o.debug(`[RunCommandTool] Session: ${r}, Timeout: ${g}ms, Background: ${u||!1}`);try{let h=(await Promise.resolve().then(()=>(ze(),yt))).ToolCallingService.getInstance(),m={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:n,session:r,timeout:g})}},S=await h.executeTool(m),w="";if(S.success){let p=(S.result?.stdout||"").trim(),v=S.result?.exitCode??0;if(w=`Command: ${n}
139
- `,w+=`Exit Code: ${v}
203
+ ... (truncated due to size limit)`}stopAllRunningTools(){}}});var at,Ns=F(()=>{"use strict";B();Wt();at=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=Is(o);if(p.isPrivileged)return i.debug(`[RunCommandTool] Blocked privileged command: ${p.reason}`),[{type:"text",text:`Error: ${Ps(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=Lt();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(()=>(rt(),Bt))).ToolCallingService.getInstance(),w={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:r,timeout:f})}},d=await b.executeTool(w),g="";if(d.success){let m=(d.result?.stdout||"").trim(),T=d.result?.exitCode??0;if(g=`Command: ${o}
204
+ `,g+=`Exit Code: ${T}
140
205
 
141
- `,p.length>0){let f=p.split(`
142
- `),x=f.slice(0,15);w+=x.join(`
143
- `),f.length>15&&(w+=`
206
+ `,m.length>0){let k=m.split(`
207
+ `),E=k.slice(0,15);g+=E.join(`
208
+ `),k.length>15&&(g+=`
144
209
 
145
- ... (showing first 15 of ${f.length} lines)`)}else w+="(no output)";return[{type:"text",text:w}]}else{let p=S.error||"Unknown error",v=S.result?.exitCode??1;return w=`Command: ${n}
146
- `,w+=`Exit Code: ${v}
210
+ ... (showing first 15 of ${k.length} lines)`)}else g+="(no output)";return[{type:"text",text:g}]}else{let m=d.error||"Unknown error",T=d.result?.exitCode??1;return g=`Command: ${o}
211
+ `,g+=`Exit Code: ${T}
147
212
 
148
- `,w+=`Error:
149
- ${p}`,[{type:"text",text:w}]}}catch(h){return o.debug(`[RunCommandTool] Failed to execute bash command: ${h.message}`),[{type:"text",text:`Command: ${n}
150
- Error: ${h.message}`}]}}ensureMeaningfulOutput(e,t,s){let i=(e||"").trim();return i.length===0?s?`✅ Command '${t}' executed successfully.
213
+ `,g+=`Error:
214
+ ${m}`,[{type:"text",text:g}]}}catch(b){return i.debug(`[RunCommandTool] Failed to execute bash command: ${b.message}`),[{type:"text",text:`Command: ${o}
215
+ Error: ${b.message}`}]}}ensureMeaningfulOutput(e,t,s){let n=(e||"").trim();return n.length===0?s?`✅ Command '${t}' executed successfully.
151
216
 
152
217
  ℹ️ No output was produced, which may be expected for this operation. This typically means:
153
218
  • The command completed without errors
@@ -164,33 +229,126 @@ If you expected output, the command may need different parameters or the operati
164
229
  Consider:
165
230
  • Checking the command syntax and parameters
166
231
  • Verifying file permissions and paths
167
- • Running the command with verbose flags for more details`:i}}});var Qe,rs=F(()=>{"use strict";U();Qe=class{toolNames=["grep","Grep"];async execute(e,t,s,i){let n=s.pattern,r=s.output_mode||"files_with_matches",a=s.path||process.cwd(),l=s.glob,u=s.type,g=s["-i"]===!0,h=s["-n"]===!0,m=s["-A"],S=s["-B"],w=s["-C"],p=s.multiline===!0,v=s.head_limit;if(!n)throw new Error("Missing pattern argument");if(n.trim().length===0)throw new Error("Pattern cannot be empty");o.debug(`[GrepTool] Grep search: pattern="${n}", path="${a}", output_mode="${r}"`);try{let{exec:f}=await import("child_process"),{promisify:x}=await import("util"),P=x(f),D="rg",C=!0;try{await P("which rg")}catch{o.debug("[GrepTool] ripgrep not found, falling back to grep"),D="grep -r",C=!1}if(C){switch(g&&(D+=" -i"),h&&(D+=" -n"),r){case"files_with_matches":D+=" -l";break;case"count":D+=" -c";break;case"content":default:break}w!==void 0?D+=` -C ${w}`:(m!==void 0&&(D+=` -A ${m}`),S!==void 0&&(D+=` -B ${S}`)),p&&(D+=" -U --multiline-dotall"),D+=` "${n.replace(/"/g,'\\"')}"`,l&&(D+=` --glob="${l}"`),u&&(D+=` --type=${u}`),D+=` "${a}"`}else{switch(g&&(D+=" -i"),h&&(D+=" -n"),r){case"files_with_matches":D+=" -l";break;case"count":D+=" -c";break}w!==void 0?D+=` -C ${w}`:(m!==void 0&&(D+=` -A ${m}`),S!==void 0&&(D+=` -B ${S}`)),D+=` "${n.replace(/"/g,'\\"')}"`,l&&(D+=` --include="${l}"`),D+=` "${a}"`}v!==void 0&&v>0&&(D+=` | head -n ${v}`),o.debug(`[GrepTool] Executing: ${D}`);let{stdout:E,stderr:_}=await P(D,{maxBuffer:10*1024*1024});if(!E&&!_)return[{type:"text",text:"No matches found"}];let A=E||_;if(r==="content"&&A){let k=`
232
+ • Running the command with verbose flags for more details`:n}}});var ct,Rs=F(()=>{"use strict";B();ct=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"],w=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:T}=await import("util"),k=T(m),E="rg",y=!0;try{await k("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}w!==void 0?E+=` -C ${w}`:(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}w!==void 0?E+=` -C ${w}`:(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:x,stderr:O}=await k(E,{maxBuffer:10*1024*1024});if(!x&&!O)return[{type:"text",text:"No matches found"}];let P=x||O;if(r==="content"&&P){let D=`
233
+
234
+ [Found ${P.trim().split(`
235
+ `).length} matching line(s)]`;return[{type:"text",text:P+D}]}return[{type:"text",text:P}]}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 lt,Fs=F(()=>{"use strict";B();lt=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
+ `);return[{type:"text",text:`Found ${b.length} file(s):
237
+ ${b.join(`
238
+ `)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var ut,$s=F(()=>{"use strict";B();ut=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 Yn,execSync as pa}from"child_process";import{promisify as Zn}from"util";function De(){return process.platform==="win32"}function dt(){return process.platform==="darwin"}function pt(){return process.platform==="linux"}function Ht(){return De()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var ga,Os=F(()=>{"use strict";ga=Zn(Yn)});import*as U from"fs";import*as V from"path";import*as W from"os";import{exec as _s}from"child_process";import{promisify as eo}from"util";var mt,Gt,ee,Ms=F(()=>{"use strict";Os();mt=eo(_s),Gt=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 V.join(W.homedir(),".orion")}getKnowledgeFilePath(){return V.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!U.existsSync(this.orionDirectory))try{U.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),De()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{_s(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return U.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return U.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),U.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let s=(this.readDeviceKnowledge()||"")+`
239
+
240
+ `+e;return this.writeDeviceKnowledge(s)}getKnowledgeFileSize(){try{return U.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
241
+
242
+ `;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
243
+
244
+ `,e+=`## System Information
245
+ `,e+=`- **OS**: ${W.type()} ${W.release()}
246
+ `,e+=`- **Platform**: ${W.platform()}
247
+ `,e+=`- **Hostname**: ${W.hostname()}
248
+ `,e+=`- **Architecture**: ${W.arch()}
249
+ `,e+=`- **CPU Cores**: ${W.cpus().length}
250
+ `,e+=`- **Memory**: ${this.formatBytes(W.totalmem())}
251
+ `,e+=`- **Username**: ${W.userInfo().username}
252
+ `,e+=`- **Home Directory**: ${W.homedir()}
253
+
254
+ `;let t=Ht();e+=`## Shell Environment
255
+ `,e+=`- **Default Shell**: ${t}
256
+ `,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
257
+ `),e+=`
258
+ `;let s=[{command:"python3 --version",name:"Python 3"},{command:"python --version",name:"Python"},{command:"node --version",name:"Node.js"},{command:"npm --version",name:"npm"},{command:"pnpm --version",name:"pnpm"},{command:"yarn --version",name:"Yarn"},{command:"brew --version",name:"Homebrew"},{command:"git --version",name:"Git"},{command:"docker --version",name:"Docker"},{command:"java -version",name:"Java"},{command:"ruby --version",name:"Ruby"},{command:"php --version",name:"PHP"},{command:"go version",name:"Go"},{command:"rustc --version",name:"Rust"},{command:"cargo --version",name:"Cargo"},{command:"apt --version",name:"APT"},{command:"snap --version",name:"Snap"},{command:"flatpak --version",name:"Flatpak"},{command:"dnf --version",name:"DNF"},{command:"yum --version",name:"YUM"},{command:"pacman --version",name:"Pacman"},{command:"kubectl version --client",name:"kubectl"},{command:"podman --version",name:"Podman"},{command:"vagrant --version",name:"Vagrant"}],n=[];for(let u of s){let p=await this.getCommandVersion(u.command);p&&n.push(`- **${u.name}**: ${p}`)}n.length>0&&(e+=`## Development Tools
259
+ `,e+=n.join(`
260
+ `),e+=`
261
+
262
+ `);let o=[];if(dt()){let u=["/Applications/Xcode.app","/Applications/Visual Studio Code.app","/Applications/Sublime Text.app","/Applications/Atom.app","/Applications/IntelliJ IDEA.app","/Applications/PyCharm.app","/Applications/Android Studio.app","/Applications/Docker.app","/Applications/Postman.app","/Applications/Terminal.app","/Applications/iTerm.app"];for(let p of u)if(U.existsSync(p)){let f=V.basename(p,".app");o.push(`- ${f}`)}}else if(De()){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",V.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",V.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let p of u)if(U.existsSync(p)){let f=V.basename(p).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");o.push(`- ${f}`)}}else if(pt()){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:V.join(W.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let v of u)U.existsSync(v.path)&&o.push(`- ${v.name}`);let p=["/usr/share/applications",V.join(W.homedir(),".local/share/applications")],f=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let v of p)if(U.existsSync(v))try{let b=U.readdirSync(v);for(let w of b){let d=w.toLowerCase();for(let g of f)d.includes(g)&&!o.some(m=>m.toLowerCase().includes(g))&&o.push(`- ${w.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
263
+ `,e+=o.join(`
264
+ `),e+=`
265
+
266
+ `),e+=`## Important Directories
267
+ `,e+=`- **Home**: ${W.homedir()}
268
+ `,e+=`- **Desktop**: ${V.join(W.homedir(),"Desktop")}
269
+ `,e+=`- **Documents**: ${V.join(W.homedir(),"Documents")}
270
+ `,e+=`- **Downloads**: ${V.join(W.homedir(),"Downloads")}
271
+ `,dt()?(e+=`- **Applications**: /Applications
272
+ `,e+=`- **usr/local/bin**: /usr/local/bin
273
+ `):De()?(e+=`- **Program Files**: C:\\Program Files
274
+ `,e+=`- **Program Files (x86)**: C:\\Program Files (x86)
275
+ `,e+=`- **AppData**: ${V.join(W.homedir(),"AppData")}
276
+ `,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||V.join(W.homedir(),"AppData","Local")}
277
+ `):pt()&&(e+=`- **/usr/bin**: /usr/bin
278
+ `,e+=`- **/usr/local/bin**: /usr/local/bin
279
+ `,e+=`- **/opt**: /opt
280
+ `,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||V.join(W.homedir(),".config")}
281
+ `,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||V.join(W.homedir(),".local/share")}
282
+ `,U.existsSync("/snap")&&(e+=`- **Snap**: /snap
283
+ `),U.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
284
+ `)),e+=`
285
+ `,e+=`## Network
286
+ `,e+=`- **Hostname**: ${W.hostname()}
287
+ `;let r=W.networkInterfaces(),a=Object.values(r).flat().find(u=>u&&!u.internal&&u.family==="IPv4");a&&(e+=`- **IP Address**: ${a.address}
288
+ `),e+=`
289
+ `;let l=await this.detectEnvironment();return l&&(e+=`## Environment
290
+ `,e+=l,e+=`
291
+ `),e+=`## URL Handling Rules
292
+ `,e+=`- **Redirect URLs**: Any shortened URL should be resolved to get the actual destination URL.
293
+ `,e+=`- **File Downloads**: Always follow redirects to ensure proper file access and downloads.
294
+
295
+ `,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let n=(this.readDeviceKnowledge()||"").split(`
296
+ `),o=[],r=!1,a=!1;for(let u of n)u.startsWith(`## ${e}`)?(r=!0,a=!0,o.push(u),o.push(t)):u.startsWith("## ")&&r?(r=!1,o.push(u)):r||o.push(u);a||(o.push(""),o.push(`## ${e}`),o.push(t));let l=o.join(`
297
+ `);return this.writeDeviceKnowledge(l)}addNote(e,t,s="Notes"){let n=new Date().toLocaleString(),o=`### ${e} (${n})
298
+ ${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${s}`)){let a=r.split(`
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 U.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return U.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=U.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(pt()){try{let{stdout:s}=await mt("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),n=s.trim();n&&n!=="none"&&e.push(`- **Virtualization**: ${n}`)}catch{}if(U.existsSync("/proc/cpuinfo"))try{U.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(U.existsSync(s))try{let n=U.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(U.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),U.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),U.existsSync("/proc/version"))try{let s=U.readFileSync("/proc/version","utf8");(s.toLowerCase().includes("microsoft")||s.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(U.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),U.existsSync("/etc/os-release"))try{let n=U.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);n&&e.push(`- **Distribution**: ${n[1]}`)}catch{}}else if(dt())try{let{stdout:t}=await mt('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(De())try{let{stdout:t}=await mt('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=Ht(),{stdout:s,stderr:n}=await mt(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]}},ee=Gt.shared()});var gt,Us=F(()=>{"use strict";B();ae();Ms();gt=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=ee.readDeviceKnowledge();p?a=p:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await ee.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${ee.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let p=s.content;p?ee.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?ee.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):ee.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):ee.addNote(p,f,v)?a=`Note "${p}" added to ${v} successfully.`:(a=`Failed to add note "${p}".`,l=!1);break}case"delete":{ee.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=ee.getKnowledgeFilePath();break}case"exists":{a=ee.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${ee.getKnowledgeFileSize()} bytes`;break}case"export":{let p=s.destination;p?ee.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?ee.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 ht,Ls=F(()=>{"use strict";B();ht=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 ft,Ws=F(()=>{"use strict";B();ft=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(()=>(rt(),Bt))).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 to}from"child_process";import{promisify as so}from"util";import*as vt from"fs/promises";import*as Bs from"path";import*as Hs from"os";var no,Ae,qt=F(()=>{"use strict";B();no=so(to),Ae=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=Bs.join(Hs.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
+ [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
304
+ Start-Sleep -Milliseconds 100;
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 no(t);let s=await vt.readFile(e),n=s.toString("base64");return await vt.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
+ ⚠️ 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
+ `)):process.platform==="darwin"&&(console.log(`
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:`
311
+
312
+ UPDATE DEVICE KNOWLEDGE: ${ro.join(js.homedir(),".orion","device-knowledge.md")}
313
+ Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
314
+ Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,s){let n=e.trim();n.length===0&&(t?n=`Command '${s}' executed successfully.
315
+
316
+ No output was produced, which may be expected for this operation.`:n=`Command '${s}' failed but no error message was provided.`);try{let o=JSON.parse(n);if(Array.isArray(o)){let r=[];for(let a of o)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?r.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&r.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(r.length>0)return r}}catch{}return[{type:"text",text:n}]}async handleLargeResponse(e,t,s,n,o,r){let a;if(typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),s==="take_screenshot"||s==="take_current_screenshot"){await this.sendToolResult(e,t,s,n,o);return}if(a.length>this.maxResponseCharacters){if(i.debug(`[FRONTEND WS] Response too large (${a.length} chars), creating temp file`),s.toLowerCase()==="read"&&r?.file_path){let f=r.file_path,v=a.substring(0,5e3),b=`File too large (${a.length} characters > 87,500 limit).
317
+
318
+ FILE PATH: ${f}
319
+
320
+ This file is already on disk. Use Read tool with offset and limit parameters.
168
321
 
169
- [Found ${A.trim().split(`
170
- `).length} matching line(s)]`;return[{type:"text",text:A+k}]}return[{type:"text",text:A}]}catch(f){return f.code===1?[{type:"text",text:"No matches found"}]:(o.debug(`[GrepTool] Grep failed: ${f.message}`),f.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 Je,as=F(()=>{"use strict";U();Je=class{toolNames=["glob","Glob"];async execute(e,t,s,i){let n=s.pattern,r=s.path||process.cwd();if(!n)throw new Error("Missing pattern argument");o.debug(`[GlobTool] Glob search: pattern="${n}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),g=n.replace(/\*\*/g,"*"),h=process.platform==="win32"?`dir /s /b "${r}\\${g}"`:`find "${r}" -name "${g}" 2>/dev/null`,{stdout:m}=await u(h);if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let S=m.trim().split(`
171
- `);return[{type:"text",text:`Found ${S.length} file(s):
172
- ${S.join(`
173
- `)}`}]}catch(a){return o.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Ke,cs=F(()=>{"use strict";U();Ke=class{toolNames=["open_url"];async execute(e,t,s,i){let n=s.url;if(!n)throw new Error("Missing url argument");o.debug(`[OpenUrlTool] Opening URL: ${n}`),i.activeWebViewURLs.includes(n)||(i.activeWebViewURLs.push(n),o.debug(`[OpenUrlTool] Added to active URLs: ${n}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${n}"`,l=>{l?o.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):o.debug(`[OpenUrlTool] URL opened in default browser: ${n}`)}),[{type:"text",text:`✅ URL opened in default browser: ${n}`}]}catch(r){return o.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});var Ye,ls=F(()=>{"use strict";U();Ye=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,i){let n=s.action;return o.debug(`[ManageDeviceKnowledgeTool] Device knowledge management not implemented: ${n}`),[{type:"text",text:`Device knowledge management not available in CLI version: ${n}`}]}}});var Ze,us=F(()=>{"use strict";U();Ze=class{toolNames=["operator_status"];async execute(e,t,s,i){let n=s.taskId,r=s.status,a=s.message;return o.debug(`[OperatorStatusTool] Operator status - Task ${n}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var et,ds=F(()=>{"use strict";U();et=class{toolNames=["provide_input"];async execute(e,t,s,i){let n=s.input;if(!n)throw new Error("Missing input argument");o.debug(`[ProvideInputTool] Delegating provide_input to backend: ${n.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>(ze(),yt))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:n})}},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 o.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});function ps(c){c.register(new Ge),c.register(new qe),c.register(new He),c.register(new Xe),c.register(new Ve),c.register(new je),c.register(new Qe),c.register(new Je),c.register(new Ke),c.register(new Ye),c.register(new Ze),c.register(new et)}var gs=F(()=>{"use strict";Jt();Kt();Yt();Zt();es();is();rs();as();cs();ls();us();ds()});var tt,ms=F(()=>{"use strict";tt=class{constructor(e,t,s,i,n){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=i;this.activeWebViewURLs=n}}});var hs={};te(hs,{FrontendWebSocketService:()=>V});import{EventEmitter as rn}from"events";import an from"ws";var V,Fe=F(()=>{"use strict";U();ue();se();Le();jt();gs();ms();V=class c extends rn{static instance;webSocket=null;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;isConnected=!1;connectionError=null;isConnecting=!1;runningProcesses=new Map;activeWebViewURLs=[];isConversationActive=!1;heartbeatTimer=null;constructor(e="ws.snowx.ai",t,s="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=ne.getInstance(),this.authService=q.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new Be,ps(this.toolRegistry),o.debug("[FRONTEND WS] Tool registry initialized with 11 frontend tools"),this.deviceId?o.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):o.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication")}static getInstance(){return c.instance||(c.instance=new c),c.instance}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return o.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(e&&e!==this.userId&&(this.userId=e),this.userId){let i=this.generateUniqueDeviceId(this.userId,"node");if(i&&this.deviceId!==i)o.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${i} (using consistent ID from DeviceRegistrationService)`),this.deviceId=i;else if(i)o.debug(`[FRONTEND WS] Using existing consistent device ID: ${this.deviceId}`);else return o.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}if(t)this.sessionId=t,o.debug(`[FRONTEND WS] 🔐 Session ID updated: ${t}`);else return o.error("[FRONTEND WS] ❌ No sessionId provided! Connection will fail."),!1;if(!this.deviceId)return o.error("[FRONTEND WS] Cannot connect - no device ID set"),!1;if(this.isConversationActive=!0,this.isConnected)return o.debug("[FRONTEND WS] Already connected for conversation"),!0;o.debug("[FRONTEND WS] Connecting for new conversation with deviceId_sessionId composite key"),this.connect(e);let s=await this.waitForConnection(3e4);return s?o.debug("[FRONTEND WS] Connected for conversation with secure composite key"):(o.debug("[FRONTEND WS] Failed to connect for conversation"),this.isConversationActive=!1),s}disconnectAfterConversation(){o.debug("[FRONTEND WS] Conversation ended, disconnecting immediately"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],o.debug("[FRONTEND WS] Cleared active WebView URLs"),this.disconnect()}handleConversationComplete(){o.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}connect(e){if(this.isConnected||this.isConnecting){o.debug("[FRONTEND WS] Already connected or connecting");return}o.debug("[FRONTEND WS] === CONNECTION ATTEMPT ==="),o.debug(`[FRONTEND WS] Current state - Connected: ${this.isConnected}, Connecting: ${this.isConnecting}`),this.isConnecting=!0,this.connectionError=null;try{if(!this.sessionId){o.error("[FRONTEND WS] ❌ CRITICAL: No sessionId available for WebSocket URL!"),this.isConnecting=!1;return}let t=`wss://${this.serverHost}/frontend-tools?deviceId=${encodeURIComponent(this.deviceId||"")}&sessionId=${encodeURIComponent(this.sessionId)}`;o.debug(`[FRONTEND WS] Attempting connection to ${t}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),o.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),o.debug(`[FRONTEND WS] User ID: ${e||this.userId||"anonymous"}`),this.webSocket=new an(t,{headers:{"User-Agent":"SnowX-CLI/1.0.1 (direct-websocket)"},protocolVersion:13,handshakeTimeout:3e4,perMessageDeflate:!1}),this.setupWebSocketHandlers()}catch(t){o.debug(`[FRONTEND WS] Connection failed: ${t.message}`),this.connectionError=t.message,this.isConnecting=!1,this.emit("connectionFailed",t)}}disconnect(){o.debug("[FRONTEND WS] === DISCONNECTING WEBSOCKET ==="),o.debug(`[FRONTEND WS] Current state - Connected: ${this.isConnected}, Connecting: ${this.isConnecting}`),this.stopHeartbeat(),this.webSocket&&(this.webSocket.close(),this.webSocket=null),this.isConnected=!1,this.isConnecting=!1,this.connectionError=null,o.debug("[FRONTEND WS] Disconnected successfully"),this.emit("disconnected")}async waitForConnection(e){return new Promise(t=>{if(this.isConnected){t(!0);return}let s=setTimeout(()=>{t(!1)},e),i=()=>{clearTimeout(s),this.off("connected",i),this.off("connectionFailed",n),t(!0)},n=()=>{clearTimeout(s),this.off("connected",i),this.off("connectionFailed",n),t(!1)};this.once("connected",i),this.once("connectionFailed",n)})}setupWebSocketHandlers(){this.webSocket&&(this.webSocket.on("open",()=>{o.debug("[FRONTEND WS] === CONNECTION OPENED ==="),o.debug(`[FRONTEND WS] WebSocket successfully connected to ${this.serverHost}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId}`),this.isConnected=!0,this.isConnecting=!1,this.connectionError=null,this.startHeartbeat(),setTimeout(()=>{this.registerDevice()},1e3),this.emit("connected")}),this.webSocket.on("close",(e,t)=>{o.debug("[FRONTEND WS] === CONNECTION CLOSED ==="),o.debug(`[FRONTEND WS] Close code: ${e}`),o.debug(`[FRONTEND WS] Close reason: ${t}`),o.debug(`[FRONTEND WS] Was connected: ${this.isConnected}`),o.debug(`[FRONTEND WS] Conversation active: ${this.isConversationActive}`),this.isConnected=!1,this.isConnecting=!1,this.stopHeartbeat(),this.emit("disconnected")}),this.webSocket.on("error",e=>{o.debug("[FRONTEND WS] === WEBSOCKET ERROR ==="),o.debug(`[FRONTEND WS] Error: ${e.message}`),o.debug("[FRONTEND WS] Error details:",e),this.connectionError=e.message,this.isConnecting=!1,this.emit("connectionFailed",e)}),this.webSocket.on("message",e=>{try{let t=JSON.parse(e.toString());o.debug("[FRONTEND WS] === RECEIVED MESSAGE ==="),o.debug(`[FRONTEND WS] Message type: ${t.type}`),o.debug("[FRONTEND WS] Message:",JSON.stringify(t,null,2)),this.handleWebSocketMessage(t)}catch(t){o.debug(`[FRONTEND WS] Failed to parse message: ${t.message}`),o.debug("[FRONTEND WS] Raw data:",e.toString())}}))}handleWebSocketMessage(e){o.debug("[FRONTEND WS] === HANDLING MESSAGE ==="),o.debug(`[FRONTEND WS] Processing message type: ${e.type}`);let t=JSON.stringify(e),s=["prompt","instruction","system_prompt","user_prompt","template","claude","gpt","ai_model"];switch(s.some(n=>t.toLowerCase().includes(n))&&o.debug("PROMPT-BASED MESSAGE DETECTED:",{type:e.type,messageSize:t.length,promptKeywordsFound:s.filter(n=>t.toLowerCase().includes(n)),timestamp:new Date().toISOString()}),e.type){case"connection_established":o.debug("[FRONTEND WS] Connection established by server"),this.handleConnectionEstablished(e);break;case"tool_execution_request":o.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e);break;case"stop_signal":o.debug("[FRONTEND WS] Stop signal received"),this.handleStopSignal(e);break;case"stop_all_tools":o.debug("[FRONTEND WS] Stop all tools signal received"),this.handleStopAllTools(e);break;case"checkpoint_request":o.debug("[FRONTEND WS] Checkpoint request received"),this.handleCheckpointRequest(e);break;case"shell_cleanup":o.debug("[FRONTEND WS] Shell cleanup signal received"),this.handleShellCleanup(e.data);break;case"ping":o.debug("[FRONTEND WS] Ping received, sending pong"),this.handlePing();break;case"pong":o.debug("[FRONTEND WS] Heartbeat pong received");break;default:o.debug(`[FRONTEND WS] Unknown message type: ${e.type}`),o.debug("[FRONTEND WS] Full message:",e)}}async handleToolExecutionRequest(e){let{data:t,metadata:s}=e,{id:i,tool_name:n,arguments:r}=t;o.debug("[FRONTEND WS] === EXECUTING TOOL ==="),o.debug(`[FRONTEND WS] Tool name: ${n}`),o.debug(`[FRONTEND WS] Tool ID: ${i}`),o.debug(`[FRONTEND WS] Tool call ID: ${s?.tool_call_id}`),o.debug("[FRONTEND WS] Arguments:",JSON.stringify(r,null,2)),o.debug(`[FRONTEND WS] Connection status: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`);let a=JSON.stringify(r),l=JSON.stringify(e),u=["prompt","instruction","system_prompt","user_prompt","template","claude","gpt","execute_model","ai_model","completion"];u.some(m=>a.toLowerCase().includes(m)||l.toLowerCase().includes(m))&&o.debug("SUSPICIOUS TOOL EXECUTION DETECTED:",{toolName:n,toolId:i,promptKeywordsFound:u.filter(m=>a.toLowerCase().includes(m)||l.toLowerCase().includes(m)),argsSize:a.length,timestamp:new Date().toISOString()}),["execute_prompt","run_ai","claude_execute","gpt_run","ai_completion","prompt_exec"].includes(n.toLowerCase())&&o.debug("SUSPICIOUS TOOL NAME DETECTED:",{toolName:n,toolId:i,timestamp:new Date().toISOString()});try{let m,S=!0,w,p=new tt(this.userId,this.sessionId,s?.tool_call_id||i,this.runningProcesses,this.activeWebViewURLs);try{m=await this.toolRegistry.executeTool(n,i,r,p),o.debug(`[FRONTEND WS] Tool executed successfully via registry: ${n}`)}catch(f){o.debug(`[FRONTEND WS] Tool execution failed: ${f.message}`),m=[{type:"text",text:`Error: ${f.message}`}],S=!1,w=f.message}let v={type:"tool_execution_response",data:{id:i,tool_call_id:s?.tool_call_id||i,tool_name:n,content:m,success:S,error:w}};o.debug("[FRONTEND WS] === SENDING TOOL RESPONSE ==="),o.debug(`[FRONTEND WS] Tool: ${n}`),o.debug(`[FRONTEND WS] Success: ${S}`),o.debug(`[FRONTEND WS] Response length: ${m.length} blocks`),o.debug(`[FRONTEND WS] Connection status before send: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`),this.sendMessage(v),this.emit("tool_completed",{toolName:n,toolId:i,result:m.map(f=>f.text||"").join(`
174
- `),success:S}),await this.captureFrontendToolResultForHistory(n,m,S,w)}catch(m){o.debug("[FRONTEND WS] === TOOL EXECUTION FAILED ==="),o.debug(`[FRONTEND WS] Tool: ${n}`),o.debug(`[FRONTEND WS] Error: ${m.message}`),o.debug("[FRONTEND WS] Error stack:",m.stack),o.debug(`[FRONTEND WS] Connection status: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`);let S=`Error: ${m.message}`;m.code&&(S+=`
175
- Error Code: ${m.code}`),m.errno&&(S+=`
176
- Errno: ${m.errno}`),m.syscall&&(S+=`
177
- System Call: ${m.syscall}`),m.path&&(S+=`
178
- Path: ${m.path}`),m.stack&&(S+=`
322
+ PREVIEW (first 5,000 characters):
323
+ ${"".repeat(50)}
324
+ `+v+(a.length>5e3?`
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=js.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.
179
327
 
180
- Stack Trace:
181
- ${m.stack}`);let w={type:"tool_execution_response",data:{id:i,tool_call_id:s?.tool_call_id||i,tool_name:n,content:[{type:"text",text:S}],success:!1,error:m.message}};o.debug("[FRONTEND WS] Sending error response"),this.sendMessage(w),this.emit("tool_completed",{toolName:n,toolId:i,result:S,success:!1,error:m.message}),await this.captureFrontendToolResultForHistory(n,[{type:"text",text:S}],!1,m.message)}}terminateAllRunningProcesses(){o.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),o.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(s){o.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.message}`)}this.runningProcesses.clear()}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.isConnected&&this.sendMessage({type:"pong",timestamp:Date.now()})},3e4)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}handleConnectionEstablished(e){o.debug("[FRONTEND WS] Connection established by server"),this.registerDevice()}handleStopSignal(e){let s=e.data?.type;switch(o.debug(`[FRONTEND WS] Received stop signal: ${s}`),s){case"all":this.handleStopAll();break;case"tools":this.handleStopTools();break;default:o.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",s=e.reason||"backend_stop_request";o.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${s}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){o.debug("[FRONTEND WS] Handling checkpoint request");let{data:t}=e;if(!t){o.error("[FRONTEND WS] Missing data in checkpoint request");return}let{checkpoint_id:s,session_id:i}=t;if(!s||!i){o.error("[FRONTEND WS] Missing required checkpoint fields");return}o.debug(`[FRONTEND WS] Checkpoint ID: ${s}, Session ID: ${i}`);let n=me.getInstance(),r=n.getQueuedMessages(),a=r.map(g=>({content:g.content,timestamp:Math.floor(g.timestamp.getTime())})),l=a.length>0;o.debug(`[FRONTEND WS] Sending checkpoint response - Has feedback: ${l}, Count: ${a.length}`);let u={type:"checkpoint_response",data:{checkpoint_id:s,session_id:i,has_feedback:l,feedback:a}};this.sendMessage(u),l&&(o.info(`⚡ Sent ${a.length} feedback message(s) to AI`),this.emit("feedback:sent",r),n.clearQueue())}handleShellCleanup(e){o.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){o.info('[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring (only "new" mode is supported, no cleanup needed)');return}o.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),o.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}handleStopAll(){o.debug("[FRONTEND WS] Stopping all operations"),this.terminateAllRunningProcesses()}handleStopTools(){o.debug("[FRONTEND WS] Stopping running tools"),this.terminateAllRunningProcesses()}handlePing(){this.sendMessage({type:"pong",timestamp:Date.now()})}async registerSession(e,t){if(!this.isConnected){o.debug("[FRONTEND WS] Not connected, cannot register session");return}o.debug(`[FRONTEND WS] Registering session: ${e}`);let s={type:"register",traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()};this.sendMessage(s),o.debug(`[FRONTEND WS] Session registered: ${e}`)}registerDevice(){let e={type:"device_registration",data:{deviceId:this.deviceId||"",userId:this.userId||"",deviceType:"node-cli",timestamp:new Date().toISOString()}};this.sendMessage(e),o.debug("[FRONTEND WS] Device registration sent")}sendMessage(e){if(o.debug("[FRONTEND WS] === SENDING MESSAGE ==="),o.debug(`[FRONTEND WS] Message type: ${e.type}`),o.debug(`[FRONTEND WS] WebSocket exists: ${!!this.webSocket}`),o.debug(`[FRONTEND WS] Is connected: ${this.isConnected}`),!this.webSocket||!this.isConnected){o.debug("[FRONTEND WS] ❌ Cannot send message - not connected"),o.debug(`[FRONTEND WS] WebSocket state: ${this.webSocket?this.webSocket.readyState:"null"}`);return}try{let t=JSON.stringify(e);o.debug(`[FRONTEND WS] Sending message (${t.length} chars):`,t.substring(0,200)+"..."),this.webSocket.send(t),o.debug("[FRONTEND WS] ✅ Message sent successfully")}catch(t){o.debug(`[FRONTEND WS] ❌ Failed to send message: ${t.message}`),o.debug(`[FRONTEND WS] WebSocket state: ${this.webSocket?this.webSocket.readyState:"null"}`)}}async sendStopSignal(e,t="all"){if(!this.isConnected){o.debug("[FRONTEND WS] Not connected, cannot send stop signal");return}let s={type:"stop_request",data:{user_id:e,stop_type:t,timestamp:new Date().toISOString()}};this.sendMessage(s),o.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async sendToolRequest(e){if(!this.isConnected)throw o.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()}};o.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),o.debug(`[FRONTEND WS] Tool ID: ${e.id}`),o.debug("[FRONTEND WS] Arguments:",e.arguments),this.sendMessage(t)}get currentDeviceId(){return this.deviceId}isWebSocketConnected(){return this.isConnected}isConversationInProgress(){return this.isConversationActive&&this.isConnected}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}async captureFrontendToolResultForHistory(e,t,s,i){let n=t.map(u=>u.text||"").join(`
182
- `),{PersonalAgentService:r}=await Promise.resolve().then(()=>(ae(),Ee)),a=r.getInstance(),l=i?`Error: ${i}`:n;a.captureFrontendToolResult(e,l,s),o.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}destroy(){o.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.disconnect(),this.removeAllListeners()}}});var fe,fs=F(()=>{"use strict";fe=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,`
328
+ `;return n+=`TEMP FILE PATH: ${t}
329
+ `,n+=`Use read_file, grep, cat, or other tools to access the full content.
183
330
 
184
- `),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var Ee={};te(Ee,{PersonalAgentService:()=>K});import{EventEmitter as cn}from"events";import Tt from"axios";import ln from"http";import un from"https";import{v4 as ve}from"uuid";import oe from"fs";import $e from"path";import ke from"os";var _e,K,ae=F(()=>{"use strict";we();se();Fe();U();fs();_e=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code;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":s==="ECONNREFUSED"||s==="ENOTFOUND"||s==="ETIMEDOUT"||s==="ECONNRESET"||s==="ERR_NETWORK"||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||s===401||s===403?"critical":"parsing"}},K=class c extends cn{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=q.getInstance(),this.httpAgent=new ln.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new un.Agent({keepAlive:!0,timeout:36e5}),o.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),V.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){return this.authService.getAuthToken()?.token||"Bo1vmos7jlVT7aDYODhMxcaGc8E3"}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform,t=process.arch,s=process.version;return`${e} ${s} (CLI, ${t})`}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return oe.existsSync(e)?t=oe.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge: ${t}
331
+ `,n+=`PREVIEW (first 5,000 characters):
332
+ `,n+=`${"─".repeat(50)}
333
+ `,n+=s,e.length>5e3&&(n+=`
334
+ ${"─".repeat(50)}`,n+=`
335
+ ... (${e.length-5e3} more characters available in temp file)`),n+=`
185
336
 
186
- Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge: No specific device knowledge available.
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)+`
187
338
 
188
- Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=$e.join(ke.homedir(),".orion-cli");return $e.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(oe.existsSync(e))return;let t=$e.join(ke.homedir(),"Documents","orion","orion-device-knowledge.md");if(oe.existsSync(t)){o.info("📦 Migrating device knowledge to cross-platform location...");let s=$e.dirname(e);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let i=oe.readFileSync(t,"utf8");oe.writeFileSync(e,i,"utf8"),o.info(`✅ Device knowledge migrated to: ${e}`),o.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){o.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=$e.dirname(e);oe.existsSync(t)||oe.mkdirSync(t,{recursive:!0});let s=ke.platform(),i=ke.arch(),n=ke.hostname(),r=ke.userInfo(),a=`# Device Knowledge
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(()=>(de(),Pe)),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 be,Ks=F(()=>{"use strict";be=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
+
342
+ `),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var Pe={};se(Pe,{PersonalAgentService:()=>J});import{EventEmitter as ao}from"events";import zt from"axios";import co from"http";import lo from"https";import{v4 as we}from"uuid";import ce from"fs";import Ge from"path";import Ne from"os";var qe,J,de=F(()=>{"use strict";Se();Z();He();ke();B();Ks();qe=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"}},J=class c extends ao{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 co.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new lo.Agent({keepAlive:!0,timeout:36e5}),i.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),j.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=fn("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 ce.existsSync(e)?t=ce.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
343
+
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
+
346
+ Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=Ge.join(Ne.homedir(),".orion");return Ge.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(ce.existsSync(e))return;let t=Ge.join(Ne.homedir(),"Documents","orion","orion-device-knowledge.md");if(ce.existsSync(t)){i.info("📦 Migrating device knowledge to cross-platform location...");let s=Ge.dirname(e);ce.existsSync(s)||ce.mkdirSync(s,{recursive:!0});let n=ce.readFileSync(t,"utf8");ce.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=Ge.dirname(e);ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0});let s=Ne.platform(),n=Ne.arch(),o=Ne.hostname(),r=Ne.userInfo(),a=`# Device Knowledge
189
347
 
190
348
  ## System Information
191
349
  - **Platform**: ${s}
192
- - **Architecture**: ${i}
193
- - **Hostname**: ${n}
350
+ - **Architecture**: ${n}
351
+ - **Hostname**: ${o}
194
352
  - **Username**: ${r.username}
195
353
  - **Home Directory**: ${r.homedir}
196
354
 
@@ -205,123 +363,84 @@ Remember to update memory about device if any new information is learned during
205
363
 
206
364
  ---
207
365
  *Last updated: ${new Date().toISOString()}*
208
- `;return oe.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,i=.7,n=!0,r,a,l){this.currentPromptId=ve(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=s;let u=l?.crossDeviceTaskId;u&&o.debug(`[PERSONAL AGENT] Executing cross-device task: ${u}`),l?.mode==="new"&&(t=[],o.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let g=r||this.authService.getUserId();o.debug("🔌 WebSocket will connect after receiving sessionId from API...");let m=(await Promise.resolve().then(()=>(ue(),Ae))).DeviceRegistrationService.getInstance().getCurrentDeviceId();if(!m)throw o.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let S={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:e},...a.map(w=>({type:"image_url",image_url:{url:w}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:s.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction()};if(l?.conversationId)S.conversationId=l.conversationId,o.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),o.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let w=t.map(p=>{let v,f=p;f.metadata?.toolResults?v=f.metadata.toolResults:f.originalContent?v=f.originalContent:v=typeof p.content=="string"?p.content:JSON.stringify(p.content);let x=[{type:"text",text:v}];return f.imageUrls&&f.imageUrls.length>0&&x.push(...f.imageUrls.map(P=>({type:"image_url",image_url:{url:P}}))),{role:p.role,content:x}});for(let p=0;p<w.length;p++)w[p].role;S.messages=w,o.debug(`[PERSONAL AGENT] Sending request with ${w.length} messages (new conversation)`)}else o.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return n?this.performStreamingToolCall(S):this.performNonStreamingToolCall(S)}async performStreamingToolCall(e){let t=await this.getFirebaseIdToken();return t||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((s,i)=>{this.currentAbortController=new AbortController;let n="",r=Buffer.alloc(0),a="",l="",u=[],g=null,h=!1,m="";this.currentOutput="",this.completeOutputWithToolResults="";let S=new Map,w=new Set,p=this.authService.getUserId();Tt.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 v=>{let f=v.data,x=v.headers["x-session-id"]||v.headers["session-id"];if(x){g=x,this.currentSessionId=x,o.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${x}`);let P=(await Promise.resolve().then(()=>(Fe(),hs))).FrontendWebSocketService.getInstance();o.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await P.connectForConversation(p||void 0,x)?o.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):o.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else o.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");f.on("data",P=>{try{r=Buffer.concat([r,P]);let _="",A=0;for(let R=0;R<r.length;R++)try{_=r.slice(0,R+1).toString("utf8"),A=R+1}catch{break}if(A>0){let R=r.slice(0,A);r=r.slice(A),n+=R.toString("utf8")}}catch{n+=P.toString()}let D=[/\r?\n/,/\r/],C=[],E=n;C=E.split(/\r?\n/),E=C.pop()||"",n=E;for(let _ of C){let A=_.trim();if(A.startsWith("data: ")){let R=A.slice(6).trim();if(R==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),s(a);return}try{let k=JSON.parse(R);if(k.type==="session_start"&&k.conversationId){let T=k.conversationId,y=k.isNewConversation||!1,$=k.title;o.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),o.debug(`[PERSONAL AGENT] conversationId: ${T}`),o.debug(`[PERSONAL AGENT] isNewConversation: ${y}`),$&&o.debug(`[PERSONAL AGENT] title: "${$}"`),this.emit("conversation_id_received",{conversationId:T,isNew:y,title:$||void 0});continue}if(k.type==="title_generated"&&k.title&&k.conversationId){let T=k.title,y=k.conversationId;o.debug("[PERSONAL AGENT] Received title_generated event!"),o.debug(`[PERSONAL AGENT] conversationId: ${y}`),o.debug(`[PERSONAL AGENT] title: "${T}"`),this.emit("conversation_title_updated",{conversationId:y,title:T});continue}if(k.tool_response&&k.tool_response.content){let T=k.tool_response.content,y=k.tool_response.id||"unknown",$=k.tool_response.name||"unknown";this.emit("tool_completed",{toolName:$,toolId:y,result:T,todos:k.tool_response.todos||null}),this.emit("toolComplete",$);let I="";Array.isArray(T)?I=T.map(W=>typeof W=="string"?W:W&&typeof W=="object"&&(W.text||W.content)||"").join(""):typeof T=="string"?I=T:I=JSON.stringify(T),(!I||I.trim().length===0)&&(I="(empty tool result)");let O=`<context>
366
+ `;return ce.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=we(),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(()=>(pe(),Me))).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(w=>({type:"image_url",image_url:{url:w}}))]:[{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 w=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 T=[{type:"text",text:g}];return m.imageUrls&&m.imageUrls.length>0&&T.push(...m.imageUrls.map(k=>({type:"image_url",image_url:{url:k}}))),{role:d.role,content:T}});for(let d=0;d<w.length;d++)w[d].role;b.messages=w,i.debug(`[PERSONAL AGENT] Sending request with ${w.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,w=new Set,d=this.authService.getUserId();zt.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,T=g.headers["x-session-id"]||g.headers["session-id"];if(T){p=T,this.currentSessionId=T,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${T}`);let k=(await Promise.resolve().then(()=>(He(),Vs))).FrontendWebSocketService.getInstance();i.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await k.connectForConversation(d||void 0,T)?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",k=>{try{r=Buffer.concat([r,k]);let O="",P=0;for(let $=0;$<r.length;$++)try{O=r.slice(0,$+1).toString("utf8"),P=$+1}catch{break}if(P>0){let $=r.slice(0,P);r=r.slice(P),o+=$.toString("utf8")}}catch{o+=k.toString()}let E=[/\r?\n/,/\r/],y=[],x=o;y=x.split(/\r?\n/),x=y.pop()||"",o=x;for(let O of y){let P=O.trim();if(P.startsWith("data: ")){let $=P.slice(6).trim();if($==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),s(a);return}try{let D=JSON.parse($);if(D.type==="session_start"&&D.conversationId){let I=D.conversationId,S=D.isNewConversation||!1,N=D.title;i.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),i.debug(`[PERSONAL AGENT] conversationId: ${I}`),i.debug(`[PERSONAL AGENT] isNewConversation: ${S}`),N&&i.debug(`[PERSONAL AGENT] title: "${N}"`),this.emit("conversation_id_received",{conversationId:I,isNew:S,title:N||void 0});continue}if(D.type==="title_generated"&&D.title&&D.conversationId){let I=D.title,S=D.conversationId;i.debug("[PERSONAL AGENT] Received title_generated event!"),i.debug(`[PERSONAL AGENT] conversationId: ${S}`),i.debug(`[PERSONAL AGENT] title: "${I}"`),this.emit("conversation_title_updated",{conversationId:S,title:I});continue}if(D.tool_response&&D.tool_response.content){let I=D.tool_response.content,S=D.tool_response.id||"unknown",N=D.tool_response.name||"unknown";this.emit("tool_completed",{toolName:N,toolId:S,result:I,todos:D.tool_response.todos||null}),this.emit("toolComplete",N);let A="";Array.isArray(I)?A=I.map(z=>typeof z=="string"?z:z&&typeof z=="object"&&(z.text||z.content)||"").join(""):typeof I=="string"?A=I:A=JSON.stringify(I),(!A||A.trim().length===0)&&(A="(empty tool result)");let M=`<context>
367
+ ${A}
368
+ </context>`;u.push(M),a+=M+`
369
+ `,this.completeOutputWithToolResults+=M+`
370
+ `,this.currentOutput+=M+`
371
+ `;continue}if(D.tool_calls){i.debug("Processing tool calls:",D.tool_calls.length,"items");for(let[I,S]of D.tool_calls.entries())if(i.debug("Tool call ["+I+"]:"),S.id){i.debug("Processing tool call ID:",S.id);let N=b.get(S.id)||{};for(let[A,M]of Object.entries(S))if(A==="function"&&typeof M=="object"&&M!==null){let z=N.function||{};N.function={...z,...M}}else N[A]=M;if(b.set(S.id,N),N.function?.name&&!w.has(S.id)){let A=N.function.name;i.debug("[TOOL-DISPLAY] Showing tool call:",A,"ID:",S.id),this.emit("toolExecuting",A)}if(N.function?.arguments&&N.function?.name){let A=N.function.arguments;A.endsWith("}")||A.endsWith('"}')?(i.debug("Complete tool call accumulated:",S.id,"-",N.function.name),i.debug("Arguments:",A.substring(0,100)+(A.length>100?"...":"")),w.has(S.id)||(w.add(S.id),this.handleCompleteToolCall(N))):i.debug("Partial tool call:",S.id,"-",N.function.name)}}}else if(D.tool_response&&D.tool_response.content){let I=D.tool_response.content,S=D.tool_response.id||"unknown",N=D.tool_response.name||"unknown",A=D.tool_response.role||"unknown";i.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),i.debug(" Tool ID:",S),i.debug(" Tool Name:",N),i.debug(" Tool Role:",A),i.debug(" Content Length:",I.length),i.debug(" Content Preview:",I.substring(0,200)+"..."),this.emit("tool_completed",{toolName:N,toolId:S,result:I,todos:D.tool_response.todos||null}),this.emit("toolComplete",N),D.tool_response.todos&&Array.isArray(D.tool_response.todos)&&(i.debug("[PERSONAL AGENT] Tool response contains",D.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:D.tool_response.todos}));let M=`<context>
209
372
  ${I}
210
- </context>`;u.push(O),a+=O+`
211
- `,this.completeOutputWithToolResults+=O+`
212
- `,this.currentOutput+=O+`
213
- `;continue}if(k.tool_calls){o.debug("Processing tool calls:",k.tool_calls.length,"items");for(let[T,y]of k.tool_calls.entries())if(o.debug("Tool call ["+T+"]:"),y.id){o.debug("Processing tool call ID:",y.id);let $=S.get(y.id)||{};for(let[I,O]of Object.entries(y))if(I==="function"&&typeof O=="object"&&O!==null){let W=$.function||{};$.function={...W,...O}}else $[I]=O;if(S.set(y.id,$),$.function?.name&&!w.has(y.id)){let I=$.function.name;o.debug("[TOOL-DISPLAY] Showing tool call:",I,"ID:",y.id),this.emit("toolExecuting",I)}if($.function?.arguments&&$.function?.name){let I=$.function.arguments;I.endsWith("}")||I.endsWith('"}')?(o.debug("Complete tool call accumulated:",y.id,"-",$.function.name),o.debug("Arguments:",I.substring(0,100)+(I.length>100?"...":"")),w.has(y.id)||(w.add(y.id),this.handleCompleteToolCall($))):o.debug("Partial tool call:",y.id,"-",$.function.name)}}}else if(k.tool_response&&k.tool_response.content){let T=k.tool_response.content,y=k.tool_response.id||"unknown",$=k.tool_response.name||"unknown",I=k.tool_response.role||"unknown";o.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),o.debug(" Tool ID:",y),o.debug(" Tool Name:",$),o.debug(" Tool Role:",I),o.debug(" Content Length:",T.length),o.debug(" Content Preview:",T.substring(0,200)+"..."),this.emit("tool_completed",{toolName:$,toolId:y,result:T,todos:k.tool_response.todos||null}),this.emit("toolComplete",$),k.tool_response.todos&&Array.isArray(k.tool_response.todos)&&(o.debug("[PERSONAL AGENT] Tool response contains",k.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:k.tool_response.todos}));let O=`<context>
214
- ${T}
215
- </context>`;u.push(O),a+=O+`
216
- `,this.completeOutputWithToolResults+=O+`
217
- `,this.currentOutput+=O+`
218
- `,o.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(k.content!==void 0){let T=k.content;if(T&&T.length>0&&o.debug(`[STREAMING] Received content chunk: "${T}" (length: ${T.length})`),T&&T.includes('{"tool_response"'))try{let y,$=!1;try{y=JSON.parse(T),$=!0}catch{let I=T.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(I){let O=I[0];y=JSON.parse(O),$=!1}}if(y&&y.tool_response&&y.tool_response.content){let I=y.tool_response.content,O=y.tool_response.id||"unknown",W=y.tool_response.name||"unknown";this.emit("tool_completed",{toolName:W,toolId:O,result:I,todos:y.tool_response.todos||null}),this.emit("toolComplete",W),y.tool_response.todos&&Array.isArray(y.tool_response.todos)&&this.handleTodoUpdate({items:y.tool_response.todos});let J="";Array.isArray(I)?J=I.map(ee=>ee.text||"").join(""):typeof I=="string"?J=I:J=JSON.stringify(I);let j=`<context>
219
- ${J}
220
- </context>`;if(u.push(j),a+=j+`
221
- `,this.completeOutputWithToolResults+=j+`
222
- `,this.currentOutput+=j+`
223
- `,!$){let ee=T.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(ee){let G=T.replace(ee[0],"").trim();if(G.length>0){a+=G,l+=G,this.currentOutput+=G,this.completeOutputWithToolResults+=G;let X=fe.remove(G);this.emit("data",X)}}}continue}}catch{}if(T.includes("<think>")){h=!0;let y=T.split("<think>")[0];if(y){a+=y,l+=y,this.currentOutput+=y,this.completeOutputWithToolResults+=y;let $=fe.remove(y);this.emit("data",$)}}else if(T.includes("</think>")){h=!1,m+=T.split("</think>")[0],this.emit("thinking",m),m="";let y=T.split("</think>")[1]||"";if(y){a+=y,l+=y,this.currentOutput+=y,this.completeOutputWithToolResults+=y;let $=fe.remove(y);this.emit("data",$)}}else if(h)m+=T,this.emit("thinking",m);else{a+=T,l+=T,this.currentOutput+=T,this.completeOutputWithToolResults+=T;let y=fe.remove(T);this.emit("data",y)}}else if(k.type==="todo_update")this.handleTodoUpdate(k.data);else if(k.type==="webview_update")this.handleWebViewUpdate(k.data);else if(k.type==="operator_progress")this.handleOperatorProgress(k.data);else if(k.type==="stop"){this.handleStop(k.data),s(a);return}}catch{o.debug("Treating as plain text"),a+=R,l+=R,this.currentOutput+=R,this.completeOutputWithToolResults+=R;let T=fe.remove(R);this.emit("data",T)}}}}),f.on("end",()=>{this.emit("done"),s(a)}),f.on("error",P=>{switch(o.debug("Streaming error, disconnecting WebSocket and cleaning up"),_e.classify(P)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${ve()}`,error:!0,content:`Streaming parsing error occurred: ${P.message}. Please check response format and retry.`};o.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(C)),V.getInstance().handleConversationComplete(),s(a);return;case"critical":V.getInstance().handleConversationComplete(),this.emit("error",P),i(P);break}})}).catch(v=>{if(v.code==="ERR_CANCELED")o.debug("Task was cancelled, disconnecting WebSocket"),V.getInstance().handleConversationComplete(),this.emit("canceled"),s(a);else switch(_e.classify(v)){case"parsing":let x={type:"tool_result",tool_call_id:`error_${ve()}`,error:!0,content:`Request parsing error: ${v.message}. Please check request format and retry.`};o.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(x)),V.getInstance().handleConversationComplete(),s(a);break;case"critical":o.debug("Request failed, disconnecting WebSocket"),V.getInstance().handleConversationComplete(),i(v);break}})})}async performNonStreamingToolCall(e){try{let t=await this.getFirebaseIdToken();t||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let s=await Tt.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 i of s.data.toolResults)this.handleToolResult(i.tool,i.result);return s.data.content}throw new Error("No response content received")}catch(t){switch(_e.classify(t)){case"parsing":let i={type:"tool_result",tool_call_id:`error_${ve()}`,error:!0,content:`Non-streaming API parsing error: ${t.message}. Please check request format and retry.`};return o.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(i)),"";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{o.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 i=V.getInstance(),n={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await i.sendToolRequest(n)}catch(i){o.debug(`Failed to execute tool via WebSocket: ${i.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),o.debug(`Tool Result: ${e.name}`),t&&o.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:s,success:i,error:n}=e;if(o.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",i),i&&s){let a=`<context>
373
+ </context>`;u.push(M),a+=M+`
374
+ `,this.completeOutputWithToolResults+=M+`
375
+ `,this.currentOutput+=M+`
376
+ `,i.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(D.content!==void 0){let I=D.content;if(I&&I.length>0&&i.debug(`[STREAMING] Received content chunk: "${I}" (length: ${I.length})`),I&&I.includes('{"tool_response"'))try{let S,N=!1;try{S=JSON.parse(I),N=!0}catch{let A=I.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(A){let M=A[0];S=JSON.parse(M),N=!1}}if(S&&S.tool_response&&S.tool_response.content){let A=S.tool_response.content,M=S.tool_response.id||"unknown",z=S.tool_response.name||"unknown";this.emit("tool_completed",{toolName:z,toolId:M,result:A,todos:S.tool_response.todos||null}),this.emit("toolComplete",z),S.tool_response.todos&&Array.isArray(S.tool_response.todos)&&this.handleTodoUpdate({items:S.tool_response.todos});let q="";Array.isArray(A)?q=A.map(ge=>ge.text||"").join(""):typeof A=="string"?q=A:q=JSON.stringify(A);let me=`<context>
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>
224
382
  ${s.map(l=>l.text||"").join("")}
225
383
  </context>`;this.completeOutputWithToolResults+=a+`
226
384
  `,this.currentOutput+=a+`
227
- `,o.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(n){o.debug("[PERSONAL AGENT] WebSocket tool error:",n);let r=`<context>
228
- Error: ${n}
385
+ `,i.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(o){i.debug("[PERSONAL AGENT] WebSocket tool error:",o);let r=`<context>
386
+ Error: ${o}
229
387
  </context>`;this.completeOutputWithToolResults+=r+`
230
- `}}captureFrontendToolResult(e,t,s,i){let n=`<context>
388
+ `}}captureFrontendToolResult(e,t,s,n){let o=`<context>
231
389
  Tool: ${e}
232
390
  Success: ${s}
233
391
  Output:
234
392
  ${t}
235
- </context>`;this.completeOutputWithToolResults+=n+`
236
- `,this.currentOutput+=n+`
237
- `,o.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),o.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:i,wrappedContent:n})}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||ve(),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||ve(),taskId:e.taskId||e.id||ve(),sessionId:e.sessionId||ve(),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(o.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),V.getInstance().handleConversationComplete(),o.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};o.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),o.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),o.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-h4",{SNOWX_MODELS:i}=await Promise.resolve().then(()=>(we(),qt)),n=i.find(a=>a.name===s)||{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},r=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,r,n,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){o.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),V.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
238
-
239
- [STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{o.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(i){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",i)}await this.completeConversation(s,"STOP"),o.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),o.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,o.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):o.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let n=(await Promise.resolve().then(()=>(ue(),Ae))).DeviceRegistrationService.getInstance().getCurrentDeviceId();n?(s.device_id=n,o.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):o.debug("[PERSONAL AGENT] No device_id available for stop request"),o.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Tt.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(o.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&o.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&o.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){o.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){o.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),V.getInstance().handleConversationComplete();let i={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",i),this.resetState(),o.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 Ss={};te(Ss,{FirebaseNativeService:()=>Me,TaskMode:()=>kt,TaskStatus:()=>It});import{getDatabase as fn,ref as Et,onValue as vn,update as bn,set as Sn,serverTimestamp as wn}from"firebase/database";import{EventEmitter as yn}from"events";var kt,It,Me,xt=F(()=>{"use strict";U();Ue();kt=(t=>(t.NEW="new",t.EXISTING="existing",t))(kt||{}),It=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s))(It||{}),Me=class c extends yn{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),o.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=pe.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=fn(e),o.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(o.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(o.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){o.error("[Firebase Native] Firebase not initialized properly");return}o.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;o.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let i=Et(this.database,s),n=this.auth?.currentUser;o.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!n,uid:n?.uid||"none",email:n?.email||"none"}),this.listenerHandle=vn(i,r=>{o.debug("[Firebase Native] Data change event received",{exists:r.exists(),key:r.key,taskCount:r.val()?Object.keys(r.val()).length:0}),this.handleTasksSnapshot(r)},r=>{o.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),o.debug("[Firebase Native] Firebase listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}handleTasksSnapshot(e){let t=e.val();if(!t){o.debug("[Firebase Native] No tasks in snapshot");return}let s=Object.entries(t);o.debug("[Firebase Native] Processing tasks from snapshot",{taskCount:s.length});for(let[i,n]of s){let r=n;if(o.debug("[Firebase Native] Checking task",{taskId:i,status:r.status,mode:r.mode,fromDevice:r.fromDeviceId,toDevice:r.toDeviceId}),r.status==="pending"){if(this.currentTaskId===i){o.debug("[Firebase Native] Already processing task - skipping",{taskId:i});continue}o.debug("[Firebase Native] Found PENDING task - processing",{taskId:i}),this.handleIncomingTask(i,r)}else o.debug("[Firebase Native] Task not pending - skipping",{taskId:i,status:r.status})}}async handleIncomingTask(e,t){o.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,o.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),o.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),o.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){o.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){o.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),o.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),o.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(ae(),Ee))).PersonalAgentService.getInstance()){o.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}o.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?o.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):o.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),o.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),o.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(i){o.error("[FIREBASE-NATIVE] Task execution failed:",i.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ae(),Ee)),s=t.getInstance();this.completedObserver=i=>{this.currentTaskId===e&&(o.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.message||i||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${n}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.reason;o.debug(`[RESULT MONITOR] Task ${e} stopped: ${n}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),o.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(ae(),Ee)),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),o.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){o.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let i=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,n={status:t,updatedAt:"firebase_timestamp"};s&&(n.result=s),o.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:i,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(i,n),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:i,error:r.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Et(this.database,i),l={status:t,updatedAt:wn()};s&&(l.result=s),await bn(a,l),o.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else o.error("[Firebase Native] Database not available for fallback")}catch(a){o.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,i){let n=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;o.debug("[Firebase Native] Sending task to device",{taskId:n,targetDeviceId:t,mode:i});try{let r=Et(this.database,`users/${e}/devices/${t}/tasks/${n}`),a={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:i,timestamp:Date.now(),status:"pending"};return await Sn(r,a),o.debug("[Firebase Native] Task sent successfully",{taskId:n,targetDeviceId:t}),n}catch(r){throw r}}stopListening(){if(o.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,o.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){o.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,o.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Tn}from"events";var Ie,Dt=F(()=>{"use strict";ue();se();Ue();xt();ae();U();Ie=class c extends Tn{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];overlayManager=null;constructor(){super(),this.deviceRegistrationService=ne.getInstance(),this.authService=q.getInstance(),this.firebaseAPI=pe.getInstance(),this.firebaseNative=Me.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=K.getInstance();e.on("BotResponseCompleted",()=>{this.processNextQueuedTask()}),e.on("BotResponseStopped",()=>{this.processNextQueuedTask()}),e.on("BotResponseError",()=>{this.processNextQueuedTask()})}processNextQueuedTask(){setTimeout(()=>{if(K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)||this.pendingTasksQueue.length===0)return;let s=this.pendingTasksQueue.shift();this.executeTaskImmediately(s.taskId,s.prompt,s.mode)},500)}async startListening(e,t){let s=t||this.deviceRegistrationService.getCurrentDeviceId();if(!s){o.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,o.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let i=this.authService.getFirebaseAuth();if(!i?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(i.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",i.currentUser.uid,"Requested:",e),o.error("Refusing to start listener for different user");return}o.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(i){throw o.error("Failed to start listener:",i.message),i}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),o.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){o.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){o.error("No stored user ID found - cannot authenticate Firebase for listeners");return}o.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let i=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",i.user.uid)}}catch(s){o.warn("Firebase authentication failed:",s.message),o.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){o.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e.taskId),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,o.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}),o.debug("Cross-device task UI flow triggered successfully")}catch(t){o.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){o.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){o.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),o.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 i=s[1],n=s[2];return i.length!==13||!Number.isInteger(Number(i))||n.length!==9?!1:/^[a-z0-9]+$/.test(n)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,i=t.prompt,n=t.mode,r=t.status;if(!s||!i||!n||r!=="pending")return;if(!this.validateTaskId(s)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",s),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",s);let a="existing";this.currentTaskId=s,await this.updateTaskStatus(s,"processing"),await this.executeTask(s,i,a)}catch(t){o.error("Error handling incoming task:",t.message)}}async executeTask(e,t,s){if(o.debug(`Executing task: ${e} with mode: ${s}`),o.debug(`Prompt to execute: ${t}`),K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),o.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}o.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(()=>{o.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(i){o.error("Task execution failed:",i.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,i={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,i)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING ====="),console.log("🔔 [CROSS-DEVICE] Setting up monitoring for task:",e);let t=()=>{console.log("✅ [CROSS-DEVICE] BotResponseCompleted event received"),console.log("✅ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("✅ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("✅ [CROSS-DEVICE] Task IDs match - processing completion"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring completion")},s=n=>{console.log("❌ [CROSS-DEVICE] BotResponseError event received:",n),console.log("❌ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("❌ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("❌ [CROSS-DEVICE] Task IDs match - processing error"),this.cleanupObservers()):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring error")},i=n=>{console.log("🛑 [CROSS-DEVICE] BotResponseStopped event received:",n),console.log("🛑 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("🛑 [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("🛑 [CROSS-DEVICE] Task IDs match - processing stop"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring stop")};console.log("👂 [CROSS-DEVICE] Setting up event listeners..."),this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",i),console.log("✅ [CROSS-DEVICE] Result monitoring setup complete for task:",e),console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING END =====")}cleanupObservers(){console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS ====="),console.log("🧹 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("👂 [CROSS-DEVICE] Removing event listeners..."),this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),console.log("✅ [CROSS-DEVICE] Event listeners removed"),console.log("🧹 [CROSS-DEVICE] Clearing current task ID"),this.currentTaskId=null,console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS END =====")}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 i=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={taskId:i,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:ge,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${i}`;try{await this.firebaseAPI.writeRealtimeData(r,n),o.debug("Task submitted to device:",e)}catch(a){throw o.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,i])=>({id:s,...i})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return o.error("Failed to get available devices:",e.message),[]}}enable(){o.debug("[CROSS DEVICE] Service enabled")}disable(){o.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){o.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Es={};te(Es,{SnowXStreamHandlerService:()=>Pt});import{EventEmitter as An}from"events";var Pt,ks=F(()=>{"use strict";Pt=class extends An{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,i,n){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 g=this.byteBuffer.toString("utf8");this.buffer+=g,this.rawDataReceived+=g,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,i,n)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,i,n),this.printFinalStatistics(),!this.fullResponse&&!n){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let i,n=this.buffer.indexOf(`\r
240
- `);if(n!==-1)i=n;else{let r=this.buffer.indexOf(`
241
- `);if(r!==-1)i=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)i=a;else return}}for(;i!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,i);this.linesProcessed++,this.buffer.substring(i,i+2)===`\r
242
- `?this.buffer=this.buffer.substring(i+2):this.buffer=this.buffer.substring(i+1);let a=r.trim();if(!a){i=this.findNextLineEnd();continue}if(a.startsWith(":")){i=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),i=this.findNextLineEnd()}}processDataLine(e,t,s,i){if(this.isCancelled)return;this.dataLinesFound++;let n=e.substring(6).trim();if(n==="[DONE]"){this.emit("streamEnd");return}if(n)try{let r=JSON.parse(n);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)i?.(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 i=this.thinkingBuffer.indexOf("</think>");if(i!==-1){let n=this.thinkingBuffer.substring(0,i);n&&(this.thinkingContent+=n,s?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(i+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",s?.(this.thinkingContent));break}else{let i=this.thinkingBuffer.indexOf("<think>");if(i!==-1){let n=this.thinkingBuffer.substring(0,i);n&&(this.regularContent+=n,this.fullResponse+=n,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(i+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 i=this.rawDataReceived.substring(6).trim();try{let n=JSON.parse(i);n.choices&&n.choices.length>0&&n.choices[0].delta.content&&this.processThinkingContent(n.choices[0].delta.content,e,t)}catch{}}else try{let i=JSON.parse(this.rawDataReceived);i.choices?.[0]?.message?.content&&this.processThinkingContent(i.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
393
+ </context>`;this.completeOutputWithToolResults+=o+`
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=re.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||we(),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||we(),taskId:e.taskId||e.id||we(),sessionId:e.sessionId||we(),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..."),j.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(()=>(Se(),ls)),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(),j.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
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
398
+ `);if(o!==-1)n=o;else{let r=this.buffer.indexOf(`
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
+ `?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
243
401
  `);if(e!==-1)return e;let t=this.buffer.indexOf(`
244
- `);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 Rn from"axios";import{EventEmitter as Pn}from"events";import On from"http";import Fn from"https";var rt,Is=F(()=>{"use strict";se();rt=class extends Pn{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new On.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Fn.Agent({keepAlive:!0,timeout:36e5}),this.client=Rn.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=q.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(i){if(i.response?.status===429){if(s===t-1)throw new Error("Rate limit exceeded");let n=Math.pow(2,s);await new Promise(r=>setTimeout(r,n*1e3))}else throw i}throw new Error("Max retries exceeded")}buildRequest(e,t,s,i=.7,n=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:i,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:n,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,i=.9,n,r){let a=this.buildRequest(e,t,!1,s,i,n,r);try{let u=(await this.executeWithRetry(async()=>{let{data:g}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return g})).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,i=.9,n,r,a,l,u){let{SnowXStreamHandlerService:g}=await Promise.resolve().then(()=>(ks(),Es)),h=this.buildRequest(e,t,!0,s,i,n,r);return new Promise((m,S)=>{this.currentAbortController=new AbortController;let w=[],p=new Map,v=new g;this.client.post("/chat/completions",h,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async f=>{let x=f.data,P=f.headers["content-type"]||"",D=C=>{if(C?.index!==void 0){let E=C.index;p.has(E)||p.set(E,{});let _=p.get(E);C.id&&(_.id=C.id,_.type="function"),C.function&&(_.function||(_.function={name:"",arguments:""}),C.function.name&&(_.function.name=C.function.name),C.function.arguments&&(_.function.arguments+=C.function.arguments))}u?.(C),this.emit("tool_call_delta",C)};v.on("streamEnd",()=>{p.forEach((C,E)=>{C.id&&C.function?.name&&w.push(C)}),this.emit("done"),m({content:v.getFinalResponse(),toolCalls:w.length>0?w:void 0})}),v.on("cancelled",()=>{this.emit("canceled"),m({content:v.getFinalResponse(),toolCalls:w.length>0?w:void 0})});try{await v.processStreamingResponse(x,P,a||(()=>{}),l,D),p.forEach((C,E)=>{C.id&&C.function?.name&&w.push(C)}),this.emit("done"),m({content:v.getFinalResponse(),toolCalls:w.length>0?w:void 0})}catch(C){this.emit("error",C),S(C)}}).catch(f=>{f.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:w.length>0?w:void 0})):S(f)})})}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 $n}from"socket.io-client";import{EventEmitter as _n}from"events";var at,xs=F(()=>{"use strict";ue();at=class c extends _n{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=ne.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){let s=new Error().stack,i=s?.split(`
245
- `)[2]?.trim()||"unknown caller";if(console.log("🔌 [WebSocket] === MAIN WEBSOCKET CONNECTION INITIATED ==="),console.log("🔌 [WebSocket] Called from:",i),console.log("🔌 [WebSocket] Call timestamp:",new Date().toISOString()),console.log("🔌 [WebSocket] Input userId:",e),console.log("🔌 [WebSocket] Input serverUrl:",t),console.log("🔌 [WebSocket] Current state:",{isConnected:this.isConnected,reconnectAttempts:this.reconnectAttempts,currentUserId:this.userId,currentDeviceId:this.deviceId}),console.log("🔌 [WebSocket] Full call stack:"),s?.split(`
246
- `).slice(1,6).forEach((n,r)=>{console.log(`🔌 [WebSocket] ${r+1}. ${n.trim()}`)}),this.isConnected)return console.log("✅ [WebSocket] Already connected, returning true"),!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),console.log("🔌 [WebSocket] DeviceId:",this.deviceId),!this.deviceId)return console.error("❌ WebSocket: No device ID available from DeviceRegistrationService"),!1;try{console.log("🔌 [WebSocket] Creating socket.io connection...");let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return console.log("🔌 [WebSocket] Connection options:",JSON.stringify(n,null,2)),this.socket=$n(t,n),this.setupEventHandlers(),new Promise((r,a)=>{let l=setTimeout(()=>{a(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(l),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),r(!0)}),this.socket?.on("connect_error",u=>{clearTimeout(l),console.error("❌ WebSocket connection error:",u),a(u)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{console.log("🔧 [WebSocket] Tool execution event:",{toolName:e.toolName,status:e.status,deviceId:e.deviceId,hasResult:!!e.result,timestamp:new Date().toISOString()}),this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{console.log("⚙️ [WebSocket] Operator progress event:",{operatorId:e.operatorId,progress:e.progress,status:e.status,hasPromptData:!!(e.prompt||e.promptTemplate),timestamp:new Date().toISOString()}),(e.prompt||e.promptTemplate)&&console.log("🚨 [WebSocket] PROMPT-BASED OPERATOR DETECTED:",{hasPrompt:!!e.prompt,hasPromptTemplate:!!e.promptTemplate,promptPreview:(e.prompt||e.promptTemplate||"").substring(0,100)+"..."}),this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{console.log("🌐 [WebSocket] Webview update event:",{type:e.type,url:e.url,hasContent:!!e.content,timestamp:new Date().toISOString()}),this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{console.log("📝 [WebSocket] Todo update event:",{action:e.action,todoId:e.todoId,hasContent:!!e.content,timestamp:new Date().toISOString()}),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){switch(console.log("📱 [WebSocket] Cross-device message received:",{type:e.type,sourceDevice:e.sourceDevice,targetDeviceId:e.targetDeviceId,dataKeys:Object.keys(e.data||{}),timestamp:new Date().toISOString()}),e.type){case"conversation_shared":console.log("💬 [WebSocket] Conversation shared:",e.data);break;case"model_sync":console.log("🤖 [WebSocket] Model sync received:",e.data);break;case"clipboard_sync":console.log("📋 [WebSocket] Clipboard sync received:",e.data);break;default:console.log("❓ [WebSocket] Unknown cross-device message type:",e.type)}}handleConversationSync(e){console.log("🔄 [WebSocket] Conversation sync received:",{action:e.action,conversationId:e.conversationId,timestamp:e.timestamp,dataSize:JSON.stringify(e.data||{}).length,deviceSource:this.deviceId}),e.action==="update"?console.log("✏️ [WebSocket] Conversation update sync processed"):e.action==="delete"?console.log("🗑️ [WebSocket] Conversation delete sync processed"):e.action==="create"&&console.log("➕ [WebSocket] Conversation create sync processed")}handleDeviceStatusUpdate(e){console.log("📱 [WebSocket] Device status update:",{deviceId:e.deviceId,status:e.status,deviceType:e.deviceType,platform:e.platform,timestamp:new Date().toISOString()})}handleNotification(e){console.log("🔔 [WebSocket] Notification received:",{type:e.type,title:e.title,message:e.message,priority:e.priority,timestamp:new Date().toISOString()})}send(e,t){if(!this.isConnected||!this.socket){console.warn("⚠️ WebSocket not connected, message not sent:",e);return}let s={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};console.log("📤 [WebSocket] Sending message:",{type:e,dataSize:JSON.stringify(t).length,userId:this.userId,deviceId:this.deviceId,timestamp:new Date().toISOString()}),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 Ds,Ns=F(()=>{"use strict";Ds={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 Rs={};te(Rs,{ServiceManager:()=>We});import{EventEmitter as Mn}from"events";import{initializeApp as Wn,getApps as As}from"firebase/app";import{getAuth as Un}from"firebase/auth";var We,Ot=F(()=>{"use strict";ae();Is();se();ue();xs();Fe();Dt();ze();we();U();Ns();We=class c extends Mn{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=K.getInstance(),this.networkClient=new rt,this.authService=q.getInstance(),this.deviceRegistration=ne.getInstance(),this.webSocketService=at.getInstance(),this.frontendWebSocketService=V.getInstance(),this.crossDeviceService=Ie.getInstance(),this.toolCalling=Oe.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||Ds;if(As().length===0?(this.firebaseApp=Wn(e),o.debug("Firebase app initialized")):(this.firebaseApp=As()[0],o.debug("Using existing Firebase app")),this.firebaseAuth=Un(this.firebaseApp),o.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),o.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(xt(),Ss));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),o.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{o.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){o.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){let t=new Error().stack?.split(`
247
- `)[2]?.trim()||"unknown caller";if(console.log("🎯 [SERVICE MANAGER] === WEBSOCKET CONNECTION REQUEST ==="),console.log("🎯 [SERVICE MANAGER] Called from:",t),console.log("🎯 [SERVICE MANAGER] Call timestamp:",new Date().toISOString()),console.log("🎯 [SERVICE MANAGER] Current WebSocket status:",this.webSocketService.isWebSocketConnected()),this.webSocketService.isWebSocketConnected())return console.log("✅ [SERVICE MANAGER] WebSocket already connected, returning true"),!0;let s=this.authService.getUserId();if(console.log("🎯 [SERVICE MANAGER] Retrieved userId:",s),!s)return console.warn("⚠️ [SERVICE MANAGER] No user ID available, cannot connect WebSocket"),!1;try{console.log("🎯 [SERVICE MANAGER] Calling webSocketService.connect() with userId:",s);let i=await this.webSocketService.connect(s);return console.log("🎯 [SERVICE MANAGER] WebSocket connection result:",i),!!i}catch(i){return console.log("❌ [SERVICE MANAGER] WebSocket connection failed:",i),!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=H[0],s={}){let{usePersonalAgent:i=!0,enableToolCalling:n=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=s;try{let l=[];if(i)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=n?this.toolCalling.getAvailableTools():void 0;return a?new Promise((g,h)=>{let m="";this.networkClient.on("data",S=>{m+=S}),this.networkClient.on("done",()=>{g(m)}),this.networkClient.on("error",h),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 H.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(){console.log("🛑 ServiceManager shutdown initiated...");try{console.log("⏹️ Stopping active operations..."),this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&(console.log("🔧 Stopping all running tools..."),this.toolCalling.stopAllRunningTools?.()),console.log("🌐 Disconnecting services..."),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),console.log("🚪 Signing out user..."),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown"),console.log("✅ ServiceManager shutdown completed")}catch(e){console.error("❌ ServiceManager shutdown error:",e)}}async waitForDeviceRegistration(e=1e4){let t=this.deviceRegistration.getCurrentDeviceId();if(t){console.log(`✅ Device ID already available: ${t}`);return}return console.log("⏳ Waiting for device registration to complete..."),new Promise((s,i)=>{let n=setTimeout(()=>{i(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{console.log(`✅ Device registration completed: ${l.deviceId}`),clearTimeout(n),this.deviceRegistration.off("DeviceRegistrationComplete",r),s()};this.deviceRegistration.on("DeviceRegistrationComplete",r);let a=this.deviceRegistration.getCurrentDeviceId();a&&(console.log(`✅ Device ID became available: ${a}`),clearTimeout(n),this.deviceRegistration.off("DeviceRegistrationComplete",r),s())})}}});import*as Wt from"@sentry/node";Wt.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as zn}from"commander";import Gn from"react";import{render as qn}from"ink";se();import d,{useState as ys,useEffect as xe,useCallback as At,useRef as kn}from"react";import{Box as N,Text as b,useInput as In,useApp as xn}from"ink";import Dn from"ink-spinner";import Ts from"ink-select-input";ae();U();import{exec as dn}from"child_process";import{promisify as pn}from"util";import*as nt from"fs/promises";import*as vs from"path";import*as bs from"os";var gn=pn(dn),st=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=vs.join(bs.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;
248
- [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
249
- Start-Sleep -Milliseconds 100;
250
- $img = [System.Windows.Forms.Clipboard]::GetImage();
251
- $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return o.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await gn(t);let s=await nt.readFile(e),i=s.toString("base64");return await nt.unlink(e).catch(()=>{}),o.debug(`[SCREENSHOT] Captured screenshot: ${s.length} bytes`),`data:image/jpeg;base64,${i}`}catch(e){return o.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
252
- ⚠️ 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
253
- `)):process.platform==="darwin"&&(console.log(`
254
- ⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
255
- `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}};import Z from"chalk";import mn from"ora";var Q=class{static spinner=null;static formatUserMessage(e){return Z.cyan("You: ")+e}static formatAssistantMessage(e){return Z.green("Assistant: ")+e}static formatError(e){return Z.red("Error: ")+e}static formatWarning(e){return Z.yellow("Warning: ")+e}static formatInfo(e){return Z.blue("Info: ")+e}static formatSuccess(e){return Z.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=mn(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(Z.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(Z.bold.cyan(e)),console.log(Z.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return Z.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return Z.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(Z.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};U();Le();import{EventEmitter as hn}from"events";import Ct from"chalk";var ot=class extends hn{delegate=null;personalAgentService=K.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=(...i)=>{let n=String(i[0]||"");(n.includes("▸")||n.includes("→")||n.includes("✎"))&&t&&(e&&(e=!1),t=""),s.apply(console,i)}),this.personalAgentService.on("data",i=>{if(t+=i,this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(!n.content||n.content===""?n.content=i:n.content+=i),r&&r.isStreaming&&(!r.content||r.content===""?r.content=i:r.content+=i)}}),this.personalAgentService.on("thinking",i=>{}),this.personalAgentService.on("toolExecuting",i=>{this.delegate?.usesCustomUI||console.log(`
256
- ▸ ${i}`)}),this.personalAgentService.on("tool_completed",i=>{if(!this.delegate?.usesCustomUI){let{toolName:n,success:r,error:a}=i;console.log(r!==!1?`✓ ${n}`:`✗ ${n} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",i=>{}),this.personalAgentService.on("todo_update",i=>{}),this.personalAgentService.on("operator_progress",i=>{}),this.personalAgentService.on("webview_update",i=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let i=this.delegate.messages[this.delegate.messages.length-1],n=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];i&&i.isStreaming&&(i.isStreaming=!1),n&&n.isStreaming&&(n.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",i=>{console.error(`
257
- ❌ Error:`,i.message||i),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",i=>{if(o.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(i.content&&i.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${i.content.substring(0,50)}..."`),n.content=i.content,n.originalContent=i.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),i.completeWithTools&&(n.metadata={toolResults:i.completeWithTools}),n.isStreaming=!1,o.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(i.content&&i.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${i.content.substring(0,50)}..."`),r.content=i.content,r.originalContent=i.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),i.completeWithTools&&(r.metadata={toolResults:i.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,i=e.trim();if(i.length>s){console.log(Q.formatError(`Prompt too large (${i.length} characters). Please reduce it to ${s} characters or less.`));return}if(this.delegate.isLoading){let r=me.getInstance();r.addToQueue({content:i,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Ct.blue(`⚡ Message queued (${r.getQueueCount()} in queue)`)),console.log(Ct.dim(" Your feedback will be sent when AI completes current task"))):console.log(Ct.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let n=null;this.delegate.isVisionEnabled&&(n=await st.getInstance().captureScreen(),n?o.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${n.length} chars`):o.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision")),this.delegate.currentInput="";try{t?await this.processStreamingMessage(n):await this.processNonStreamingMessage(n)}catch(r){console.error(Q.formatError(`Message failed: ${r.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",r.message)}}async processStreamingMessage(e){if(this.delegate)try{o.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(n=>!(n.isStreaming||n.role==="system"||!n.content||typeof n.content=="string"&&n.content.trim().length===0)).map(n=>({role:n.role,content:n.content})),s=this.delegate.fullConversationHistory.filter(n=>n.role==="user"),i=s[s.length-1];if(i)try{let n=e?[e]:void 0,r={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(i.content,t,this.delegate.selectedModel,.7,!0,void 0,n,r),o.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(n){throw o.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${n.message}`),n}}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(i=>i.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let n=t.content;n.trim().length>0&&(n+=`
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(`
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(Y.formatError(`Prompt too large (${n.length} characters). Please reduce it to ${s} characters or less.`));return}if(this.delegate.isLoading){let r=re.getInstance();r.addToQueue({content:n,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Xt.blue(`⚡ Message queued (${r.getQueueCount()} in queue)`)),console.log(Xt.dim(" Your feedback will be sent when AI completes current task"))):console.log(Xt.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let o=null;this.delegate.isVisionEnabled&&(o=await Ae.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(Y.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+=`
258
405
 
259
- `),n+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=n}t.isStreaming=!1;let i=this.delegate.fullConversationHistory.find(n=>n.isStreaming);i&&(i.content=t.content,i.isStreaming=!1)}this.delegate.isLoading=!1,K.getInstance().stopStreaming().catch(i=>{o.error("[MESSAGE HANDLER] Error in comprehensive stop:",i)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};ae();gt();Le();Fe();Dt();we();Y();he();import Nt from"terminal-link";import{homedir as Cn}from"os";function ws(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",Cn())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function En(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function it(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,i)=>{let n=i;return!En(i)&&!i.startsWith("file://")&&(i.startsWith("/")||i.startsWith("~")||/\.[a-z]{2,4}$/i.test(i))&&(n=ws(i)),Nt(s,n,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let s=/\x1b\]8;;/,i=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return s.test(i)?t:Nt(t,t,{fallback:(n,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let s=/\x1b\]8;;/,i=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(s.test(i)||i.includes("http"))return t;let n=ws(t);return Nt(t,n,{fallback:(r,a)=>r})}),e}function Cs(){let{exit:c}=xn(),e=q.getInstance(),t=K.getInstance(),s=me.getInstance(),i=V.getInstance(),n=Ie.getInstance();xe(()=>(B.enableCustomUI(),()=>B.disableCustomUI()),[]);let[r,a]=ys({messages:[{role:"system",content:`Welcome to Orion
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,J.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||[]}};de();Nt();ke();He();Jt();Se();ne();ae();import Yt from"terminal-link";import{homedir as wo}from"os";function Js(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",wo())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function To(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function Tt(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,n)=>{let o=n;return!To(n)&&!n.startsWith("file://")&&(n.startsWith("/")||n.startsWith("~")||/\.[a-z]{2,4}$/i.test(n))&&(o=Js(n)),Yt(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:Yt(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=Js(t);return Yt(t,o,{fallback:(r,a)=>r})}),e}function Eo(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 Io(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 en(){let{exit:c}=xo(),e=H.getInstance(),t=J.getInstance(),s=re.getInstance(),n=j.getInstance(),o=Re.getInstance();Xe(()=>(_.enableCustomUI(),()=>_.disableCustomUI()),[]);let[r,a]=Ys({messages:[{role:"system",content:`Welcome to Orion
260
408
 
261
409
  Your autonomous on-device AI agent.
262
- 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:H.find(p=>p.name===de.string("selectedAIModel"))||H.find(p=>p.name==="snowx-h4")||H[0],isVisionEnabled:!1,queuedMessages:[],crossDeviceQueue:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=kn(null),[u]=ys(()=>{let p={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:H.find(v=>v.name===de.string("selectedAIModel"))||H.find(v=>v.name==="snowx-h4")||H[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new ot(p)}),g=At(async()=>{},[]);xe(()=>{let p=r.messages.map(f=>({role:f.role,content:f.content,timestamp:new Date(f.timestamp||Date.now()),...f.tool&&{tool:f.tool},...f.toolOutput&&{toolOutput:f.toolOutput}})),v={messages:p,fullConversationHistory:p,isLoading:r.isLoading,currentInput:r.input,selectedModel:r.selectedModel,isVisionEnabled:r.isVisionEnabled,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:g};u.setDelegate(v)},[r.messages,r.selectedModel,r.isVisionEnabled,r.isLoading,r.input,r.conversationId,u,g]);let h=At(async p=>{if(p.startsWith("/")){let C=p.toLowerCase().trim();if(C==="/help"||C==="/?"){a(E=>({...E,showCommandMenu:!0,input:""}));return}if(C==="/model"){a(E=>({...E,showModelMenu:!0,input:""}));return}if(C==="/clear"||C==="/new"){a(E=>({...E,messages:[{role:"system",content:`Welcome to Orion
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===he.string("selectedPersonalModel"))||X.find(d=>d.name==="snowx-c5")||X[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=So(null),[u]=Ys(()=>{let d={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:X.find(g=>g.name===he.string("selectedPersonalModel"))||X.find(g=>g.name==="snowx-c5")||X[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new wt(d)}),p=Zt(async()=>{},[]);Xe(()=>{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=Zt(async d=>{if(d.startsWith("/")){let y=d.toLowerCase().trim();if(y==="/help"||y==="/?"){a(x=>({...x,showCommandMenu:!0,input:""}));return}if(y==="/model"){a(x=>({...x,showModelMenu:!0,input:""}));return}if(y==="/clear"||y==="/new"){a(x=>({...x,messages:[{role:"system",content:`Welcome to Orion
263
411
 
264
412
  Your intelligent AI assistant.
265
- Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(C==="/vision"){a(E=>({...E,isVisionEnabled:!E.isVisionEnabled,messages:[...E.messages,{role:"system",content:`Vision mode ${E.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(C==="/exit"||C==="/quit"){c();return}if(C==="/stop"){r.isLoading?(t.stopStreaming(),a(E=>({...E,isLoading:!1,messages:[...E.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(E=>({...E,messages:[...E.messages,{role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(C==="/signout"){a(E=>({...E,messages:[...E.messages,{role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(_=>({..._,messages:[..._.messages,{role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(_=>({..._,messages:[..._.messages,{role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(E){a(_=>({..._,messages:[..._.messages,{role:"system",content:`❌ Error: ${E.message}`,timestamp:Date.now()}]}))}return}a(E=>({...E,messages:[...E.messages,{role:"system",content:`Unknown command: ${p}
266
-
267
- Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(r.isLoading){let C=s.addToQueue({content:p,imageUrls:[],attachments:[],model:r.selectedModel.name});a(C?E=>({...E,input:""}):E=>({...E,messages:[...E.messages,{role:"system",content:"⚠️ Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let v=Date.now(),f={role:"user",content:p,timestamp:v},x={role:"assistant",content:"",timestamp:v+1},P=[...r.messages,f,x];a(C=>({...C,messages:P,input:"",isLoading:!0,loadingMessage:"Processing"}));let D=P.map(C=>({role:C.role,content:C.content,timestamp:new Date(C.timestamp||Date.now()),...C.tool&&{tool:C.tool},...C.toolOutput&&{toolOutput:C.toolOutput}}));u.setDelegate({messages:D,fullConversationHistory:D,isLoading:!1,currentInput:"",selectedModel:r.selectedModel,isVisionEnabled:r.isVisionEnabled,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:g});try{await u.sendMessage(p)}catch(C){a(E=>({...E,messages:[...E.messages,{role:"system",content:`Error: ${C.message}`,timestamp:Date.now()}],isLoading:!1}))}},[r.isLoading,r.isVisionEnabled,r.selectedModel,s,u,e,c]),m=At(()=>{if(!s.hasQueuedMessages())return;let p=s.processNextMessage();p&&(s.startProcessing(),h(p.content))},[s,h]);xe(()=>{let p="",v=A=>{a(R=>({...R,conversationId:A.conversationId,conversationTitleGenerated:!!A.title}))},f=A=>{},x=()=>{a(A=>({...A,loadingMessage:"Processing"}))},P=A=>{p+=A,a(R=>{let k=[...R.messages];for(let T=k.length-1;T>=0;T--)if(k[T].role==="assistant"){k[T].content=p;break}return{...R,messages:k}})},D=A=>{a(R=>{let k=[...R.messages];for(let T=k.length-1;T>=0;T--)if(k[T].role==="assistant"){let y=`
268
-
269
- ${A}`;k[T].content+=y,p+=y;break}return{...R,messages:k,loadingMessage:`Running ${A}`}})},C=A=>{if(A&&A.toolName&&A.result){let R="";typeof A.result=="string"?R=A.result:Array.isArray(A.result)?R=A.result.map(I=>typeof I=="string"?I:I&&typeof I=="object"?I.text||I.content||JSON.stringify(I):"").join(""):A.result.output?R=typeof A.result.output=="string"?A.result.output:JSON.stringify(A.result.output,null,2):A.result.content?R=A.result.content:R=JSON.stringify(A.result,null,2);let k=`<context>
270
- ${R}
271
- </context>`;a(I=>{let O=[...I.messages];for(let W=O.length-1;W>=0;W--)if(O[W].role==="assistant"){let J=O[W];J.metadata||(J.metadata={});let j=J.metadata;j.toolResults?j.toolResults+=`
272
- `+k:j.toolResults=k;break}return{...I,messages:O}});let T=`${A.toolName} completed`,y="";if(R){let I=R.split(`
273
- `),O=I.length,W=R.length,J=R.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||R.match(/(?:Writing|Reading|Editing):\s*(.+?)(?:\n|$)/i),j=J?J[1].trim():null,ee=A.toolName.toLowerCase();if(ee.includes("todo")){let G=A.todos;if(G&&Array.isArray(G)&&G.length>0){let X=G.filter(ce=>ce.status==="completed").length,Se=G.length;T=`Tasks (${X}/${Se})`,y=G.map(ce=>{let _t=ce.status==="completed"?"":ce.status==="inProgress"||ce.status==="in_progress"?"":"",Mt=ce.text||ce.content||"Unknown task";return` ${_t} ${Mt}`}).join(`
274
- `)}else T="Todo list updated",y=""}else if(ee.includes("read")){T="Read completed";let G=R.match(/Read (\d+) lines \(from line (\d+) to (\d+)\) out of (\d+) total lines\.\nFile: (.+?)\n\n/);if(G){let[,X,Se,$s,ce,_t]=G;T=`Read completed (${X}/${ce} lines)`,j&&(T=`Read ${j}`),y=R.substring(G[0].length)}else R.includes("more lines)")?(T="Read completed",y=R):(T=`Read completed (${O} lines)`,y=I.slice(0,5).join(`
275
- `)+(O>5?`
276
- ...
277
- (${O-5} more lines)`:""))}else if(ee.includes("write"))if(T="Write completed",R.includes("more lines)")||R.includes("+ ..."))y=R;else{let G=I.filter(X=>X.startsWith("+ ")).slice(0,8);G.length>0?(y=G.join(`
278
- `),I.filter(X=>X.startsWith("+ ")).length>8&&(y+=`
279
- + ...
280
-
281
- (${I.filter(X=>X.startsWith("+ ")).length-8} more lines)`)):(y=I.slice(0,8).map(X=>`+ ${X}`).join(`
282
- `),O>8&&(y+=`
283
- + ...
284
-
285
- (${O-8} more lines)`))}else if(ee.includes("edit"))if(T="Edit completed",j&&(T=`Edited ${j}`),R.match(/(replaced|search|->|→)/gi)){let X=I.filter(Se=>Se.toLowerCase().includes("replaced")||Se.toLowerCase().includes("search")||Se.includes("->")||Se.includes("→"));y=X.slice(0,5).join(`
286
- `),X.length>5&&(y+=`
287
- ... (${X.length-5} more changes)`)}else y=I.slice(0,8).join(`
288
- `),O>8&&(y+=`
289
- ... (${O-8} more lines)`);else ee.includes("bash")||ee.includes("command")?(T="Command completed",R.includes("showing first")||R.includes("more lines)")?y=R:(y=I.slice(0,15).join(`
290
- `),O>15&&(y+=`
291
-
292
- ... (showing first 15 of ${O} lines)`))):(T=`${A.toolName} completed`,y=I.slice(0,8).join(`
293
- `),O>8&&(y+=`
294
- ... (${O-8} more lines)`))}let $="";y?$=`
295
- ${y.split(`
296
- `).map((W,J)=>J===0?` └─ ${T}
297
- ${W}`:` ${W}`).join(`
298
- `)}`:$=`
299
- └─ ${T}`,a(I=>{let O=[...I.messages];for(let W=O.length-1;W>=0;W--)if(O[W].role==="assistant"){if(A.toolName.toLowerCase().includes("todo")){let j=/\n\n• [Tt]odo[Ww]rite\n[\s\S]*?(?=\n\n• |\n\n▶ |$)/g;O[W].content=O[W].content.replace(j,"")}O[W].content+=$,p+=$;break}return{...I,messages:O}})}},E=()=>{p="",a(A=>({...A,isLoading:!1}))},_=A=>{a(R=>({...R,messages:[...R.messages,{role:"system",content:`Error: ${A.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),p=""};return t.on("conversation_id_received",v),t.on("conversation_title_updated",f),t.on("thinking",x),t.on("data",P),t.on("toolExecuting",D),t.on("tool_completed",C),t.on("done",E),t.on("error",_),()=>{t.off("conversation_id_received",v),t.off("conversation_title_updated",f),t.off("thinking",x),t.off("data",P),t.off("toolExecuting",D),t.off("tool_completed",C),t.off("done",E),t.off("error",_)}},[t,m]),xe(()=>{let p=P=>{a(D=>({...D,queuedMessages:P}))},v=P=>{},f=P=>{l.current=P,a(D=>({...D,todoList:P}))},x=P=>{if(r.isLoading){a(D=>D.crossDeviceQueue.length>=10?{...D,messages:[...D.messages,{role:"system",content:"⚠️ Cross-device queue is full - task rejected",timestamp:Date.now()}]}:{...D,crossDeviceQueue:[...D.crossDeviceQueue,P.prompt]});return}h(P.prompt)};return s.on("queue:updated",p),i.on("feedback:sent",v),t.on("todo_update",f),n.on("CrossDeviceTaskSendMessage",x),()=>{s.off("queue:updated",p),i.off("feedback:sent",v),t.off("todo_update",f),n.off("CrossDeviceTaskSendMessage",x)}},[s,i,t,n,h,r.isLoading,r.selectedModel.name]),xe(()=>{!r.isLoading&&s.hasQueuedMessages()&&m()},[r.isLoading,s,m]),xe(()=>{if(!r.isLoading&&!s.hasQueuedMessages()&&r.crossDeviceQueue.length>0){let p=r.crossDeviceQueue[0];a(v=>({...v,crossDeviceQueue:v.crossDeviceQueue.slice(1)})),h(p)}},[r.isLoading,r.crossDeviceQueue,s,h]),In((p,v)=>{if(v.escape){if(r.isLoading){t.stopStreaming(),a(f=>({...f,isLoading:!1,messages:[...f.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(r.showModelMenu||r.showCommandMenu){a(f=>({...f,showModelMenu:!1,showCommandMenu:!1,input:f.showCommandMenu&&f.input==="/"?"":f.input}));return}if(r.showHelp){a(f=>({...f,showHelp:!1}));return}}if(!r.showModelMenu){if(v.ctrl&&p==="c"){r.isLoading?(t.stopStreaming(),a(f=>({...f,isLoading:!1,messages:[...f.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(p==="?"&&r.input===""){a(f=>({...f,showHelp:!f.showHelp}));return}if(v.return&&!r.showCommandMenu){r.input.trim()&&h(r.input);return}if(v.delete||v.backspace){a(f=>{let x=f.input.slice(0,-1);return f.showCommandMenu&&!x.startsWith("/")?{...f,input:x,showCommandMenu:!1}:{...f,input:x}});return}!v.ctrl&&!v.meta&&p&&a(f=>{let x=f.input+p;return x==="/"&&!f.showCommandMenu?{...f,input:x,showCommandMenu:!0}:{...f,input:x}})}});let S=e.getUserEmail()||"User",w=le.getDisplayName(le.getCurrentUserTier());return d.createElement(N,{flexDirection:"column",width:"100%"},d.createElement(N,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},d.createElement(b,{color:"white"},r.selectedModel.displayName),d.createElement(b,{color:"gray",dimColor:!0}," • "),d.createElement(b,{color:"gray"},S),d.createElement(b,{color:"gray",dimColor:!0}," • "),d.createElement(b,{color:"white"},w),r.queuedMessages.length>0&&d.createElement(d.Fragment,null,d.createElement(b,{color:"gray",dimColor:!0}," • "),d.createElement(b,{color:"white",inverse:!0,bold:!0}," ",r.queuedMessages.length," "),d.createElement(b,{color:"gray"}," queued")),r.crossDeviceQueue.length>0&&d.createElement(d.Fragment,null,d.createElement(b,{color:"gray",dimColor:!0}," • "),d.createElement(b,{color:"blue",inverse:!0,bold:!0}," 📱 ",r.crossDeviceQueue.length," "),d.createElement(b,{color:"gray"}," cross-device"))),d.createElement(N,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},r.messages.map((p,v)=>d.createElement(Nn,{key:`${p.role}-${p.timestamp}-${v}`,message:p}))),r.todoList&&r.todoList.todos.length>0&&r.todoList.todos.some(p=>p.status!=="completed")&&d.createElement(N,{paddingX:2,marginBottom:1},d.createElement(N,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(N,{marginBottom:1},d.createElement(b,{color:"white",bold:!0},"Tasks"),d.createElement(b,{color:"gray"}," • "),d.createElement(b,{color:"gray"},r.todoList.todos.filter(p=>p.status==="completed").length,"/",r.todoList.todos.length)),r.todoList.todos.map((p,v)=>{let f=p.status==="completed"?"✓":p.status==="in_progress"?"⋯":"○",x=p.status==="completed"?"green":p.status==="in_progress"?"blue":"gray";return d.createElement(N,{key:p.id||v},d.createElement(b,{color:x},f),d.createElement(b,{color:"gray"}," "),d.createElement(b,{color:p.status==="completed"?"gray":"white",dimColor:p.status==="completed"},p.status==="in_progress"&&p.activeForm?p.activeForm:p.text))}))),r.isLoading&&d.createElement(N,{paddingX:0,marginBottom:1,flexDirection:"column"},d.createElement(N,null,d.createElement(b,{color:"magenta"},d.createElement(Dn,{type:"dots"})),d.createElement(b,{color:"white"}," ",r.loadingMessage,"… "),d.createElement(b,{color:"white"},"(esc to interrupt)")),d.createElement(N,{marginLeft:2},d.createElement(b,{color:"yellow"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),r.showHelp&&d.createElement(N,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Keyboard Shortcuts"),d.createElement(N,{marginTop:1,flexDirection:"column"},d.createElement(b,{color:"white"},"• ",d.createElement(b,{color:"white",bold:!0},"Enter")," ",d.createElement(b,{color:"white"},"Submit message")),d.createElement(b,{color:"white"},"• ",d.createElement(b,{color:"white",bold:!0},"?")," ",d.createElement(b,{color:"white"},"Toggle this help")),d.createElement(b,{color:"white"},"• ",d.createElement(b,{color:"white",bold:!0},"Esc")," ",d.createElement(b,{color:"white"},"Stop generation / Close menus")),d.createElement(b,{color:"white"},"• ",d.createElement(b,{color:"white",bold:!0},"Ctrl+C")," ",d.createElement(b,{color:"white"},"Stop generation / Exit"))),d.createElement(N,{marginTop:1},d.createElement(b,{color:"white"},"Press Esc to close"))),r.showModelMenu&&d.createElement(N,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Select Model"),d.createElement(N,{marginTop:1},d.createElement(Ts,{items:H.map(p=>({label:`${p.displayName}`,value:p.name})),onSelect:p=>{let v=H.find(f=>f.name===p.value);v&&(de.set("selectedAIModel",v.name),a(f=>({...f,selectedModel:v,showModelMenu:!1,messages:[...f.messages,{role:"system",content:`Switched to ${v.displayName}`,timestamp:Date.now()}]})))}})),d.createElement(N,{marginTop:1},d.createElement(b,{color:"white"},"Esc to cancel"))),r.showCommandMenu&&(()=>{let p=[{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"}],v=r.input.startsWith("/")?r.input.substring(1).toLowerCase():"",f=v?p.filter(x=>x.value.toLowerCase().includes(v)):p;return d.createElement(N,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Available Commands ",v&&`(filtered: "${v}")`),d.createElement(N,{marginTop:1},d.createElement(Ts,{items:f.length>0?f:[{label:"No matching commands",value:""}],onSelect:x=>{x.value&&(a(P=>({...P,showCommandMenu:!1,input:""})),h(`/${x.value}`))}})),d.createElement(N,{marginTop:1},d.createElement(b,{color:"white"},"Esc to cancel")))})(),r.queuedMessages.length>0&&d.createElement(N,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.map((p,v)=>d.createElement(N,{key:p.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},d.createElement(N,null,d.createElement(b,{color:"white",bold:!0},v+1),d.createElement(b,{color:"white"}," • "),d.createElement(b,{color:"white"},p.content.length>60?p.content.substring(0,60)+"...":p.content)))),d.createElement(N,null,d.createElement(b,{color:"white"},r.queuedMessages.length," message",r.queuedMessages.length>1?"s":""," queued"))),r.crossDeviceQueue.length>0&&d.createElement(N,{flexDirection:"column",paddingX:2,marginBottom:1},r.crossDeviceQueue.map((p,v)=>d.createElement(N,{key:`cross-${v}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},d.createElement(N,null,d.createElement(b,{color:"blue",bold:!0},"📱 ",v+1),d.createElement(b,{color:"white"}," • "),d.createElement(b,{color:"white"},p.length>60?p.substring(0,60)+"...":p)))),d.createElement(N,null,d.createElement(b,{color:"blue"},r.crossDeviceQueue.length," cross-device task",r.crossDeviceQueue.length>1?"s":""," waiting"))),d.createElement(N,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},d.createElement(N,null,d.createElement(b,{color:"white"},"▶ "),d.createElement(b,{color:"white"},r.input,!r.isLoading&&d.createElement(b,{color:"white",inverse:!0}," "))),d.createElement(N,{marginTop:0},d.createElement(b,{color:"white"},r.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),d.createElement(N,{paddingX:2,paddingY:0},d.createElement(b,{color:"white"},"? help · Ctrl+C exit")))}function Rt(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=it(e),e}function Nn({message:c}){let{role:e,content:t,tool:s}=c;if(e==="system"){let i=t.split(`
300
- `);return d.createElement(N,{marginBottom:1,justifyContent:"flex-start"},d.createElement(N,{paddingX:2,paddingY:1,flexDirection:"column",borderStyle:"round",borderColor:"white"},i.map((n,r)=>r===0?d.createElement(b,{key:`system-${r}-${n.substring(0,10)}`,color:"white",bold:!0},n):d.createElement(b,{key:`system-${r}-${n.substring(0,10)}`,color:"white"},n))))}if(e==="user")return d.createElement(N,{marginBottom:1},d.createElement(b,{color:"blue"}," ▶ "),d.createElement(b,{color:"white",bold:!0},t));if(e==="assistant"){let i=t.split(`
301
- `);return d.createElement(N,{marginBottom:1,flexDirection:"column"},d.createElement(N,null,d.createElement(b,{color:"white"}," Orion ")),i.map((n,r)=>{if(n.match(/^• /)){let u=!1;for(let g=r-1;g>=0;g--){if(i[g].match(/^ └─ /)){u=!0;break}if(i[g].match(/^• /))break}return u?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(b,null," "),d.createElement(N,null,d.createElement(b,{color:"gray"},"●"),d.createElement(b,{color:"white",bold:!0},n.substring(1)))):d.createElement(N,{key:r},d.createElement(b,{color:"gray"},"●"),d.createElement(b,{color:"white",bold:!0},n.substring(1)))}if(n.match(/^ └─ /)){let u=n.substring(4);return d.createElement(N,{key:r},d.createElement(b,{color:"green"}," └─ "),d.createElement(b,{color:"white"},u))}if(n.match(/^ [✓⋯○] /)){let u=n.substring(5,6),g=n.substring(7),h=u==="✓"?"green":u==="⋯"?"blue":"gray",m=i[r+1];return m&&(m.match(/^• /)||m.trim()!==""&&!m.match(/^ /))?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(N,null,d.createElement(b,{color:h}," ",u," "),d.createElement(b,{color:u==="✓"?"gray":"white"},g)),d.createElement(b,null," ")):d.createElement(N,{key:r},d.createElement(b,{color:h}," ",u," "),d.createElement(b,{color:u==="✓"?"gray":"white"},g))}if(n.match(/^ \+ /)){let u=i[r+1];return u&&(u.match(/^• /)||u.trim()!==""&&!u.match(/^ /))?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(N,null,d.createElement(b,{color:"green"}," + "),d.createElement(b,{color:"white"},n.substring(7))),d.createElement(b,null," ")):d.createElement(N,{key:r},d.createElement(b,{color:"green"}," + "),d.createElement(b,{color:"white"},n.substring(7)))}if(n.match(/^ \d+→/)){let u=n.match(/^( \d+→)(.*)$/);if(u){let g=i[r+1];return g&&(g.match(/^• /)||g.trim()!==""&&!g.match(/^ /))?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(N,null,d.createElement(b,{color:"gray"},u[1]),d.createElement(b,{color:"white"},u[2])),d.createElement(b,null," ")):d.createElement(N,{key:r},d.createElement(b,{color:"gray"},u[1]),d.createElement(b,{color:"white"},u[2]))}}if(n.match(/^ /)){let u=Rt(n),g=i[r+1];return g&&(g.match(/^• /)||g.trim()!==""&&!g.match(/^ /))?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(b,{color:"white"},u),d.createElement(b,null," ")):d.createElement(b,{key:r,color:"white"},u)}if(n.trim()==="")return d.createElement(b,{key:r}," ");let a=r>0?i[r-1]:null;return a&&a.match(/^ /)?d.createElement(N,{key:r,flexDirection:"column"},d.createElement(b,null," "),d.createElement(b,{color:"white"},Rt(n))):d.createElement(b,{key:r,color:"white"},Rt(n))}))}return null}Ot();se();se();import M from"chalk";import Ln from"inquirer";import Bn from"open";var be=class{authService;constructor(){this.authService=q.getInstance()}async login(){console.log(M.blue(`
302
- 🔐 Orion Authentication`)),console.log(M.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(M.yellow(`
303
- Please visit the following URL to authenticate:`)),console.log(M.cyan.underline(e));try{await Bn(e),console.log(M.gray(`
304
- (Browser opened automatically)`))}catch{console.log(M.gray(`
305
- (Please open the URL manually in your browser)`))}console.log(M.yellow(`
306
- After logging in, copy the access token and paste it here:`));let{accessToken:t}=await Ln.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(M.gray(`
307
- Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let i=await this.authService.getUserInfo();console.log(M.green(`
308
- ✅ Authentication successful!`)),i&&(console.log(M.gray(`Logged in as: ${i.email||i.username||"User"}`)),console.log(M.gray(`Subscription: ${this.getSubscriptionDisplay(i.subscription?.tier)}`)))}else console.log(M.red(`
309
- ❌ Authentication failed. Please try again.`))}catch(s){console.log(M.red(`
310
- ❌ Authentication error: ${s.message}`))}}async logout(){console.log(M.yellow(`
311
- 🔄 Signing out...`)),console.log(M.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(M.green(`
312
- ✅ Successfully signed out`)),console.log(M.gray("All authentication data and settings have been cleared.")),console.log(M.gray('Run "orion auth login" to sign in again.'))):(console.log(M.red(`
313
- ❌ Logout failed`)),console.log(M.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(M.green(`
314
- ✅ Authenticated`)),t){console.log(M.gray("─".repeat(50))),console.log(M.white("User:",t.name||t.username||"N/A")),console.log(M.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(M.white("Subscription:",s)),t.usage&&(console.log(M.gray(`
315
- Usage:`)),console.log(M.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(M.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(M.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(M.yellow(`
316
- ⚠️ Not authenticated`)),console.log(M.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"}}};he();var Ps=!1;async function Ft(){if(Ps){console.log("Already running...");return}Ps=!0,B.enableCustomUI();let c=We.getInstance(),e=q.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(`
413
+ Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(y==="/vision"){a(x=>({...x,isVisionEnabled:!x.isVisionEnabled,messages:[...x.messages,{role:"system",content:`Vision mode ${x.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(y==="/exit"||y==="/quit"){c();return}if(y==="/stop"){r.isLoading?(t.stopStreaming(),a(x=>({...x,isLoading:!1,messages:[...x.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(x=>({...x,messages:[...x.messages,{role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(y==="/signout"){a(x=>({...x,messages:[...x.messages,{role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(O=>({...O,messages:[...O.messages,{role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(O=>({...O,messages:[...O.messages,{role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(x){a(O=>({...O,messages:[...O.messages,{role:"system",content:`❌ Error: ${x.message}`,timestamp:Date.now()}]}))}return}a(x=>({...x,messages:[...x.messages,{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?x=>({...x,input:""}):x=>({...x,messages:[...x.messages,{role:"system",content:"⚠️ Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let g=Date.now(),m={role:"user",content:d,timestamp:g},T={role:"assistant",content:"",timestamp:g+1},k=[...r.messages,m,T];a(y=>({...y,messages:k,input:"",isLoading:!0,loadingMessage:"Processing"}));let E=k.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(x=>({...x,messages:[...x.messages,{role:"system",content:`Error: ${y.message}`,timestamp:Date.now()}],isLoading:!1}))}},[r.isLoading,r.isVisionEnabled,r.selectedModel,s,u,e,c]),v=Zt(()=>{if(!s.hasQueuedMessages())return;let d=s.processNextMessage();d&&(s.startProcessing(),f(d.content))},[s,f]);Xe(()=>{let d="",g=P=>{a($=>({...$,conversationId:P.conversationId,conversationTitleGenerated:!!P.title}))},m=P=>{},T=()=>{a(P=>({...P,loadingMessage:"Processing"}))},k=P=>{d+=P,a($=>{let D=[...$.messages];for(let I=D.length-1;I>=0;I--)if(D[I].role==="assistant"){D[I].content=d;break}return{...$,messages:D}})},E=P=>{a($=>{let D=[...$.messages];for(let I=D.length-1;I>=0;I--)if(D[I].role==="assistant"){let S=`
416
+ [TOOL:${P}]`;D[I].content+=S,d+=S;break}return{...$,messages:D,loadingMessage:`${P}`}})},y=P=>{if(P&&P.toolName&&P.result){let $="";typeof P.result=="string"?$=P.result:Array.isArray(P.result)?$=P.result.map(N=>typeof N=="string"?N:N&&typeof N=="object"?N.text||N.content||JSON.stringify(N):"").join(""):P.result.output?$=typeof P.result.output=="string"?P.result.output:JSON.stringify(P.result.output,null,2):P.result.content?$=P.result.content:$=JSON.stringify(P.result,null,2);let D=`<context>
417
+ ${$}
418
+ </context>`;a(N=>{let A=[...N.messages];for(let M=A.length-1;M>=0;M--)if(A[M].role==="assistant"){let z=A[M];z.metadata||(z.metadata={});let q=z.metadata;q.toolResults=q.toolResults?q.toolResults+`
419
+ `+D:D;break}return{...N,messages:A}});let I=P.toolName.toLowerCase(),S="";if($){let N=$.split(`
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(R,{marginBottom:1,marginTop:1,flexDirection:"column"},h.createElement(R,null,h.createElement(C,{color:"gray",dimColor:!0},"System")),h.createElement(R,{paddingLeft:1,flexDirection:"column"},o.map((r,a)=>h.createElement(C,{key:`system-${a}`,color:"gray"},r))))}if(t==="user")return h.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},h.createElement(R,null,h.createElement(C,{color:"blue",bold:!0},"You")),h.createElement(R,{paddingLeft:1},h.createElement(C,{color:"white"},s)));if(t==="assistant"){let{suggestions:o,cleanedContent:r}=Eo(s),{workingFiles:a,cleanedContent:l}=Io(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"),w=u.filter(d=>d.type==="tool");return h.createElement(R,{marginBottom:1,flexDirection:"column"},h.createElement(R,{marginBottom:0},h.createElement(C,{color:"green",bold:!0},"Orion")),b.map((d,g)=>{let m=d.content.split(`
422
+ `);return h.createElement(R,{key:`text-${g}`,flexDirection:"column",paddingLeft:1},m.map((T,k)=>T.trim()===""?h.createElement(C,{key:k}," "):h.createElement(C,{key:k,color:"white"},Po(T))))}),v&&w.length>0&&h.createElement(R,{flexDirection:"column",marginTop:1,paddingLeft:1},w.map((d,g)=>{let m=f(d.toolName||""),T=d.toolResult&&d.toolResult.length>0,k=d.toolResult?.includes("✓"),E=d.toolResult?.includes("✗")||d.toolResult?.includes("error");return h.createElement(R,{key:`tool-${g}`},h.createElement(C,{color:m.color},m.icon),h.createElement(C,{color:"gray"}," ",d.toolName),T&&h.createElement(C,{color:E?"red":k?"green":"gray"}," ",d.toolResult),!T&&h.createElement(C,{color:"gray",dimColor:!0}," …"))})),a.length>0&&h.createElement(Ao,{workingFiles:a}),o.length>0&&h.createElement(Do,{suggestions:o,onSelect:e}))}return null}ts();Z();Z();import L from"chalk";import Ho from"inquirer";var Te=class{authService;constructor(){this.authService=H.getInstance()}async login(){console.log(L.blue(`
423
+ 🔐 Orion Authentication`)),console.log(L.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(L.yellow(`
424
+ 📋 To authenticate, please follow these steps:`)),console.log(L.white("1. Open this URL in a browser (on any device):")),console.log(L.cyan.underline(` ${e}`)),console.log(L.white("2. Log in with your Orion account")),console.log(L.white("3. Copy the access token shown after login")),console.log(L.white("4. Paste the token below")),console.log(L.yellow(`
425
+ Paste your access token here:`));let{accessToken:t}=await Ho.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(L.gray(`
426
+ Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let n=await this.authService.getUserInfo();console.log(L.green(`
427
+ Authentication successful!`)),n&&(console.log(L.gray(`Logged in as: ${n.email||n.username||"User"}`)),console.log(L.gray(`Subscription: ${this.getSubscriptionDisplay(n.subscription?.tier)}`)))}else console.log(L.red(`
428
+ ❌ Authentication failed. Please try again.`))}catch(s){console.log(L.red(`
429
+ ❌ Authentication error: ${s.message}`))}}async logout(){console.log(L.yellow(`
430
+ 🔄 Signing out...`)),console.log(L.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(L.green(`
431
+ Successfully signed out`)),console.log(L.gray("All authentication data and settings have been cleared.")),console.log(L.gray('Run "orion auth login" to sign in again.'))):(console.log(L.red(`
432
+ ❌ Logout failed`)),console.log(L.gray("Some cleanup operations may have failed, but local data has been cleared.")))}async status(){if(await this.authService.autoAuthenticate(),this.authService.isAuthenticated()){let t=await this.authService.getUserInfo();if(console.log(L.green(`
433
+ Authenticated`)),t){console.log(L.gray("".repeat(50))),console.log(L.white("User:",t.name||t.username||"N/A")),console.log(L.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(L.white("Subscription:",s)),t.usage&&(console.log(L.gray(`
434
+ Usage:`)),console.log(L.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(L.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(L.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(L.yellow(`
435
+ ⚠️ Not authenticated`)),console.log(L.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};ae();var un=!1;async function ss(){if(un){console.log("Already running...");return}un=!0,_.enableCustomUI();let c=je.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(`
317
436
  ❌ Failed to initialize services:`,s.message),console.error(`
318
437
  💡 Tip: Check your internet connection and Firebase configuration.
319
438
  `),process.exit(1)}}(!await e.autoAuthenticate()||!e.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
320
- `),await new be().login(),e.isAuthenticated()||(console.error(`
439
+ `),await new Te().login(),e.isAuthenticated()||(console.error(`
321
440
  ❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
322
441
  ✨ Starting Orion CLI...
323
442
  `)),e.isFirebaseAuthenticated()||(console.error(`
324
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(`
325
444
  Please check your connection and try again.
326
- `),process.exit(1)),console.log("✅ Authentication verified"),console.clear(),process.stdout.write("\x1Bc"),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),qn(Gn.createElement(Cs))}we();U();import{EventEmitter as Hn}from"events";import Xn from"axios";import{execSync as Vn}from"child_process";import Os from"chalk";var ct=class c extends Hn{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):o.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){o.debug("Update check failed:",e)}finally{this.isChecking=!1}}}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`;return(await Xn.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let s=e.split(".").map(Number),i=t.split(".").map(Number);for(let n=0;n<3;n++){let r=s[n]||0,a=i[n]||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`;o.debug(`Auto-updating from ${this.currentVersion} to ${e}`),Vn(t,{stdio:"pipe",encoding:"utf8"}),console.log(Os.green(`✓ Updated to v${e}`)+Os.gray(` - restarting...
327
- `)),process.exit(0)}catch(t){o.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 o.debug("Update check failed:",e),{hasUpdate:!1}}}};import jn from"dotenv";import{fileURLToPath as Qn}from"url";import{dirname as Jn,join as Kn}from"path";import{readFileSync as Yn}from"fs";jn.config();var Zn=Qn(import.meta.url),eo=Jn(Zn),Fs=JSON.parse(Yn(Kn(eo,"..","package.json"),"utf8")),to=ct.getInstance(Fs.version);to.checkAndUpdate().catch(()=>{});var De=new zn;De.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Fs.version);De.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Ft()}catch(c){console.error(Q.formatError(c.message)),process.exit(1)}});De.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(()=>(Ot(),Rs)),s=t.getInstance();console.log("🔧 Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let i=H.find(r=>r.name===e.model)||H[0];console.log("💭 Sending message...");let n=await s.sendMessage(c,i,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(it(n))}catch(t){Q.stopSpinner(!1),console.error(Q.formatError(t.message)),process.exit(1)}});var $t=De.command("auth").description("Authentication commands");$t.command("login").description("Login to Orion").action(async()=>{try{await new be().login()}catch(c){console.error(Q.formatError(c.message)),process.exit(1)}});$t.command("logout").description("Logout from Orion").action(async()=>{try{await new be().logout()}catch(c){console.error(Q.formatError(c.message)),process.exit(1)}});$t.command("status").description("Check authentication status").action(async()=>{try{await new be().status()}catch(c){console.error(Q.formatError(c.message)),process.exit(1)}});De.command("models").description("List available AI models").action(()=>{Q.printHeader("Available Models");for(let c of H)console.log(`${Q.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?Ft().catch(c=>{console.error(Q.formatError(c.message)),process.exit(1)}):De.parse(process.argv);
445
+ `),process.exit(1)),console.log("✅ Authentication verified"),console.clear(),process.stdout.write("\x1Bc"),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),qo(Go.createElement(en))}Se();B();import{EventEmitter as zo}from"events";import Xo from"axios";import{execSync as jo}from"child_process";import dn from"chalk";var xt=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 Xo.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}`),jo(t,{stdio:"pipe",encoding:"utf8"}),console.log(dn.green(`✓ Updated to v${e}`)+dn.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 Ko from"dotenv";import{fileURLToPath as Qo}from"url";import{dirname as Jo,join as Yo}from"path";import{readFileSync as Zo}from"fs";Ko.config();var ei=Qo(import.meta.url),ti=Jo(ei),pn=JSON.parse(Zo(Yo(ti,"..","package.json"),"utf8")),si=xt.getInstance(pn.version);si.checkAndUpdate().catch(()=>{});var Fe=new Vo;Fe.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(pn.version);Fe.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await ss()}catch(c){console.error(Y.formatError(c.message)),process.exit(1)}});Fe.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(()=>(ts(),ln)),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(Tt(o))}catch(t){Y.stopSpinner(!1),console.error(Y.formatError(t.message)),process.exit(1)}});var ns=Fe.command("auth").description("Authentication commands");ns.command("login").description("Login to Orion").action(async()=>{try{await new Te().login()}catch(c){console.error(Y.formatError(c.message)),process.exit(1)}});ns.command("logout").description("Logout from Orion").action(async()=>{try{await new Te().logout()}catch(c){console.error(Y.formatError(c.message)),process.exit(1)}});ns.command("status").description("Check authentication status").action(async()=>{try{await new Te().status()}catch(c){console.error(Y.formatError(c.message)),process.exit(1)}});Fe.command("models").description("List available AI models").action(()=>{Y.printHeader("Available Models");for(let c of X)console.log(`${Y.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?ss().catch(c=>{console.error(Y.formatError(c.message)),process.exit(1)}):Fe.parse(process.argv);