@zinley/orion 1.2.12 → 1.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +166 -178
- package/package.json +15 -12
package/dist/index.js
CHANGED
|
@@ -1,33 +1,57 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Rt=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var ks=Object.prototype.hasOwnProperty;var Es=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var R=(c,e)=>()=>(c&&(e=c(c=0)),e);var ae=(c,e)=>{for(var t in e)Rt(c,t,{get:e[t],enumerable:!0})},Is=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xs(e))!ks.call(c,s)&&s!==t&&Rt(c,s,{get:()=>e[s],enumerable:!(n=Cs(e,s))||n.enumerable});return c};var Ps=c=>Is(Rt({},"__esModule",{value:!0}),c);var fn={};ae(fn,{AccountStatus:()=>hn,SNOWX_MODELS:()=>X,SignUpMethod:()=>gn,SnowXProvider:()=>Ft,TaskStatus:()=>mn,TodoStatus:()=>pn});var Ft,X,pn,mn,gn,hn,De=R(()=>{"use strict";Ft=(r=>(r.GPT="GPT",r.BEDROCK="BEDROCK",r.ANTHROPIC="ANTHROPIC",r.OPENAI="OPENAI",r.FOUNDRY="FOUNDRY",r.GOOGLE="google",r))(Ft||{}),X=[{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-5.1",displayName:"GPT-5.1 High",provider:"GPT",apiModelName:"gpt-5.1-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-codex",displayName:"GPT-5.1 Codex",provider:"GPT",apiModelName:"gpt-5.1-codex",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5.1-chat",displayName:"GPT-5.1",provider:"GPT",apiModelName:"gpt-5.1",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-o3-pro",displayName:"GPT o3-pro",provider:"GPT",apiModelName:"o3-pro",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"high"},{name:"snowx-o3",displayName:"GPT o3",provider:"GPT",apiModelName:"o3",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"medium"},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.5-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0}],pn=(n=>(n.PENDING="pending",n.IN_PROGRESS="in_progress",n.COMPLETED="completed",n))(pn||{}),mn=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(mn||{}),gn=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(gn||{}),hn=(n=>(n.ACTIVE="active",n.SUSPENDED="suspended",n.PENDING="pending",n))(hn||{})});var $t,i,B=R(()=>{"use strict";$t=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},i=$t.getInstance()});var ve={};ae(ve,{UserDefaults:()=>Se});import Be from"fs";import Ot from"path";import Ds from"os";var _t,Se,ce=R(()=>{"use strict";B();_t=class c{static instance;preferencesPath;preferences={};constructor(){let e=Ot.join(Ds.homedir(),".orion");this.preferencesPath=Ot.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Be.existsSync(this.preferencesPath)){let e=Be.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),i.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{i.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=Ot.dirname(this.preferencesPath);Be.existsSync(e)||Be.mkdirSync(e,{recursive:!0}),Be.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),i.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){i.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),i.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),i.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Se=_t.getInstance()});var ie,Mt=R(()=>{"use strict";De();ce();B();ie=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){return["snowx-o4.5","snowx-o3-pro","snowx-5-pro"].includes(e)?1:0}static getCurrentUserTier(){let e=Se.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Se.set("userSubscriptionTier",e),i.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let n=this.getRequiredTier(e),s=t>=n;return i.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${n} (${this.getDisplayName(n)}), Access=${s}`),s}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return X.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import As from"axios";import{EventEmitter as Ns}from"events";var xe,Ce,tt=R(()=>{"use strict";xe="firebase_timestamp",Ce=class c extends Ns{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=As.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return c.instance||(c.instance=new c),c.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(se(),vn));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let r=(await this.client.get("/documents",{params:s,headers:n})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async queryDocuments(e,t,n,s,o,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:n,value:String(s)};o&&(u.limit=o.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let f=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(f.success)return Array.isArray(f.doc)?f.doc:f.doc&&typeof f.doc=="object"?[f.doc]:[];{let y=f.error||"Unknown error";throw new Error(y)}}catch(p){throw p}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return r.success?r.doc:null}catch(o){throw o}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,n,s,o){let r=`${e}/${t}/${n}`;return this.createDocument(r,s,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let o of s)o.id&&await this.deleteDocument(n,o.id);for(let[o,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${o}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(n,a,l)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,o)=>{if(s.order!==void 0&&o.order!==void 0)return s.order-o.order;let r=new Date(s.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let r=(await this.client.put("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.get("/realtime",{params:n,headers:t})).data;if(o.success)return o.doc;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!o.success){let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),o=s.data;if(o.success)return s.data.data;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime/push",s,{headers:n})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var Ge={};ae(Ge,{DeviceRegistrationService:()=>de});import{EventEmitter as Rs}from"events";import{v4 as yn}from"uuid";import He from"os";import bn from"fs/promises";import Fs from"path";import{execSync as qe}from"child_process";import $s from"crypto";var de,we=R(()=>{"use strict";tt();se();B();de=class c extends Rs{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Ce.getInstance(),this.authService=H.getInstance(),this.configDir=Fs.join(He.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){i.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{i.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{i.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();i.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(i.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){i.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),i.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(i.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,i.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),i.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw i.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}i.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),i.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){i.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return i.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=He.platform();if(e==="darwin")try{let s=qe("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return i.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{i.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=qe('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let o=s[1].trim();if(o)return i.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{i.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=He.hostname();return i.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return i.debug(`[DEVICE REG] Error getting computer name: ${e}`),He.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=He.platform();try{let t=null;switch(e){case"darwin":try{let a=qe("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],i.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=qe("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],i.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await bn.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await bn.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),i.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{i.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=qe("wmic csproduct get UUID",{encoding:"utf8"}).split(`
|
|
3
|
-
`).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),i.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:i.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=$s.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return i.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=yn(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID: ${o}`)),o}catch(t){i.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=yn(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let o=s.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(l=>l.deviceId===t?{...l,lastSeenAt:xe,computerName:n,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:xe,lastSeenAt:xe};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let r={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:xe,lastSeenAt:xe}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}i.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw i.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=s.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var vn={};ae(vn,{AuthService:()=>H});import{EventEmitter as Os}from"events";import{signInAnonymously as _s,signInWithEmailAndPassword as Ms,createUserWithEmailAndPassword as Us,signOut as Ls,onAuthStateChanged as wn,updateProfile as Ws,signInWithCustomToken as Bs}from"firebase/auth";import ke from"axios";import Ut from"fs/promises";import Tn from"path";import Hs from"os";var H,se=R(()=>{"use strict";Mt();B();H=class c extends Os{static instance;auth=null;currentUser=null;authToken=null;userProfile=null;tokenFilePath;snowxAuthEndpoint="https://snowx.ai/api/auth";snowxApiEndpoint="https://snowx.ai/api-beta/api";constructor(){super(),this.tokenFilePath=Tn.join(Hs.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=Tn.dirname(this.tokenFilePath);await Ut.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve)),t=e.string("snowx_auth_token"),n=e.string("snowx_access_token");if(!t||!n)try{let s=await Ut.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(s);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,n=o.token,await Ut.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&n){let s={token:n,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=s,i.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(s)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(s)}this.emit("authenticated",s)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),ve));t.set("snowx_auth_token",e.userId),t.set("snowx_access_token",e.token),this.authToken=e,this.emit("authenticated",e)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));e.remove("snowx_auth_token"),e.remove("snowx_access_token"),this.authToken=null}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,wn(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}ie.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),ve));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),i.debug(`User tier updated: ${ie.getDisplayName(t)} (${e.tier})`),i.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await _s(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Ms(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await Us(this.auth,e,t);return this.currentUser=s.user,n&&await Ws(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(we(),Ge));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ls(this.auth)}catch(t){console.warn("⚠️ [AUTH] Firebase sign out error:",t)}return this.currentUser=null,this.authToken=null,await this.clearStoredToken(),await this.clearAllSnowXUserDefaults(e),this.emit("signed_out"),!0}catch(e){return console.error("❌ [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(we(),Ge));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),ve)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of n)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let o=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of o)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await ke.post(`${this.snowxAuthEndpoint}/login`,e):t=await ke.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await ke.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),ve));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let o=!1,r,a=wn(this.auth,async l=>{if(!o)if(o=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);s(u)}catch{s(null)}else s(null)});r=setTimeout(()=>{o||(o=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(i.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){i.debug("Using existing authentication token"),i.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(i.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(i.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return i.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(i.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):i.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),i.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),i.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),i.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),i.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),i.debug("Signing into Firebase with custom token...");let t=await Bs(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),i.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),i.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),i.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let l=await ke.post(s,o,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let p=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${p}`),new Error(`Custom token API failed: ${p}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),i.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),i.error("Failed to get custom token:",{attempt:n,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let p=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${p}ms... (${t-1} attempts remaining)`),i.debug(`Retrying in ${p}ms...`),await new Promise(f=>setTimeout(f,p)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await ke.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,o=s.subscription?.tier??0;return{id:t,email:s.email,tier:o}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await ke.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let o={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=n,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(i.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):i.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",o),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await ke.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return ie.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await ke.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var Sn={};ae(Sn,{MessageQueueManager:()=>pe});import{EventEmitter as qs}from"events";var pe,Ne=R(()=>{"use strict";B();pe=class c extends qs{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),i.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),i.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});var nt,Cn=R(()=>{"use strict";B();nt=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),i.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,o]of this.tools.entries())if(s.toLowerCase()===n)return o}async executeTool(e,t,n,s){let o=this.getTool(e);if(!o)return i.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{i.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await o.execute(t,e,n,s),l=Date.now()-r;i.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(p=>p.text||"").join(`
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
var _t=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var Fs=Object.prototype.hasOwnProperty;var $s=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var R=(c,e)=>()=>(c&&(e=c(c=0)),e);var ae=(c,e)=>{for(var t in e)_t(c,t,{get:e[t],enumerable:!0})},Os=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rs(e))!Fs.call(c,s)&&s!==t&&_t(c,s,{get:()=>e[s],enumerable:!(n=Ns(e,s))||n.enumerable});return c};var _s=c=>Os(_t({},"__esModule",{value:!0}),c);var wn={};ae(wn,{AccountStatus:()=>yn,SNOWX_MODELS:()=>z,SignUpMethod:()=>bn,SnowXProvider:()=>Mt,TaskStatus:()=>vn,TodoStatus:()=>fn});var Mt,z,fn,vn,bn,yn,Ae=R(()=>{"use strict";Mt=(i=>(i.GPT="GPT",i.BEDROCK="BEDROCK",i.ANTHROPIC="ANTHROPIC",i.OPENAI="OPENAI",i.FOUNDRY="FOUNDRY",i.GOOGLE="google",i))(Mt||{}),z=[{name:"snowx-o4.5",displayName:"Claude Opus 4.5",provider:"ANTHROPIC",apiModelName:"claude-opus-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:2},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:1},{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,creditMultiplier:1},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0,creditMultiplier:.5},{name:"snowx-5.1",displayName:"GPT-5.1 High",provider:"GPT",apiModelName:"gpt-5.1-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:1},{name:"snowx-5.1-codex",displayName:"GPT-5.1 Codex",provider:"GPT",apiModelName:"gpt-5.1-codex",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:1},{name:"snowx-5.1-chat",displayName:"GPT-5.1",provider:"GPT",apiModelName:"gpt-5.1",maxTokens:32768,contextWindow:1047576,supportsVision:!0,creditMultiplier:.5},{name:"snowx-o3-pro",displayName:"GPT o3-pro",provider:"GPT",apiModelName:"o3-pro",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"high",creditMultiplier:2},{name:"snowx-o3",displayName:"GPT o3",provider:"GPT",apiModelName:"o3",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"medium",creditMultiplier:1},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.5-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.5-flash",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:.5},{name:"snowx-g4",displayName:"Gemini 3 Pro",provider:"google",apiModelName:"gemini-3-pro",maxTokens:8192,contextWindow:1e6,supportsVision:!0,creditMultiplier:1}],fn=(n=>(n.PENDING="pending",n.IN_PROGRESS="in_progress",n.COMPLETED="completed",n))(fn||{}),vn=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(vn||{}),bn=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(bn||{}),yn=(n=>(n.ACTIVE="active",n.SUSPENDED="suspended",n.PENDING="pending",n))(yn||{})});var Lt,r,H=R(()=>{"use strict";Lt=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)}},r=Lt.getInstance()});var be={};ae(be,{UserDefaults:()=>ke});import Ge from"fs";import Ut from"path";import Ms from"os";var Wt,ke,ce=R(()=>{"use strict";H();Wt=class c{static instance;preferencesPath;preferences={};constructor(){let e=Ut.join(Ms.homedir(),".orion");this.preferencesPath=Ut.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Ge.existsSync(this.preferencesPath)){let e=Ge.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),r.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{r.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=Ut.dirname(this.preferencesPath);Ge.existsSync(e)||Ge.mkdirSync(e,{recursive:!0}),Ge.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),r.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){r.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),r.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(),r.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},ke=Wt.getInstance()});var ie,Bt=R(()=>{"use strict";Ae();ce();H();ie=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){return["snowx-o4.5","snowx-o3-pro","snowx-5-pro"].includes(e)?1:0}static getCurrentUserTier(){let e=ke.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){ke.set("userSubscriptionTier",e),r.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let n=this.getRequiredTier(e),s=t>=n;return r.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${n} (${this.getDisplayName(n)}), Access=${s}`),s}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return z.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 Ls from"axios";import{EventEmitter as Us}from"events";var Ce,xe,it=R(()=>{"use strict";Ce="firebase_timestamp",xe=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=Ls.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return c.instance||(c.instance=new c),c.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),be));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(se(),Tn));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(i){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",i.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",i.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",i),i}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let i=(await this.client.get("/documents",{params:s,headers:n})).data;if(i.success)return Array.isArray(i.doc)?i.doc:[];{let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async queryDocuments(e,t,n,s,o,i,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:n,value:String(s)};o&&(u.limit=o.toString()),i&&(u.orderBy=i),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 n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let i=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return i.success?i.doc:null}catch(o){throw o}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(i){throw i}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let i=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,n,s,o){let i=`${e}/${t}/${n}`;return this.createDocument(i,s,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let o of s)o.id&&await this.deleteDocument(n,o.id);for(let[o,i]of t.entries()){if(i.role==="system"||i.isStreaming)continue;let a=`message_${o}_${Date.now()}`,l={id:a,role:i.role,content:i.content,timestamp:i.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(n,a,l)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,o)=>{if(s.order!==void 0&&o.order!==void 0)return s.order-o.order;let i=new Date(s.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return i-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let i=(await this.client.put("/realtime",s,{headers:n})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.get("/realtime",{params:n,headers:t})).data;if(o.success)return o.doc;{let i=o.error||"Unknown error";throw new Error(i)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!o.success){let i=o.error||"Unknown error";throw new Error(i)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),o=s.data;if(o.success)return s.data.data;{let i=o.error||"Unknown error";throw new Error(i)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let i=(await this.client.post("/realtime",s,{headers:n})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let i=(await this.client.post("/realtime/push",s,{headers:n})).data;if(i.success){if(i.key)return i.key;throw new Error("No key returned")}else{let a=i.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 je={};ae(je,{DeviceRegistrationService:()=>pe});import{EventEmitter as Ws}from"events";import{v4 as Sn}from"uuid";import Xe from"os";import kn from"fs/promises";import Bs from"path";import{execSync as ze}from"child_process";import Hs from"crypto";var pe,Te=R(()=>{"use strict";it();se();H();pe=class c extends Ws{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=xe.getInstance(),this.authService=q.getInstance(),this.configDir=Bs.join(Xe.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){r.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{r.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{r.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();r.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(r.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){r.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),r.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(r.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,r.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),r.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw r.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}r.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),r.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){r.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return r.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=Xe.platform();if(e==="darwin")try{let s=ze("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return r.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{r.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=ze('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let o=s[1].trim();if(o)return r.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{r.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=Xe.hostname();return r.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return r.debug(`[DEVICE REG] Error getting computer name: ${e}`),Xe.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Xe.platform();try{let t=null;switch(e){case"darwin":try{let a=ze("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],r.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{r.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=ze("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],r.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{r.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await kn.readFile("/etc/machine-id","utf-8").then(i=>i.trim()),r.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await kn.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),r.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{r.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=ze("wmic csproduct get UUID",{encoding:"utf8"}).split(`
|
|
3
|
+
`).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),r.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{r.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:r.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let i=Hs.createHash("sha256").update(t).digest("hex"),a=[i.substring(0,8),i.substring(8,12),i.substring(12,16),i.substring(16,20),i.substring(20,32)].join("-");return r.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),be)),s="snowx_fallback_device_id",o=n.string(s);return o?r.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=Sn(),n.set(s,o),r.debug(`[DEVICE REG] Generated NEW fallback UUID: ${o}`)),o}catch(t){r.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),be)),s="snowx_fallback_device_id",o=n.string(s);return o?r.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=Sn(),n.set(s,o),r.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let o=s.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(l=>l.deviceId===t?{...l,lastSeenAt:Ce,computerName:n,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Ce,lastSeenAt:Ce};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let i={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:Ce,lastSeenAt:Ce}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,i)}r.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw r.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let i=s.filter(a=>a.deviceId!==t);i.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:i})}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 Tn={};ae(Tn,{AuthService:()=>q});import{EventEmitter as qs}from"events";import{signInAnonymously as Gs,signInWithEmailAndPassword as Xs,createUserWithEmailAndPassword as zs,signOut as js,onAuthStateChanged as xn,updateProfile as Vs,signInWithCustomToken as Ks}from"firebase/auth";import Ee from"axios";import Ht from"fs/promises";import Cn from"path";import Qs from"os";var q,se=R(()=>{"use strict";Bt();H();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=Cn.join(Qs.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=Cn.dirname(this.tokenFilePath);await Ht.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),be)),t=e.string("snowx_auth_token"),n=e.string("snowx_access_token");if(!t||!n)try{let s=await Ht.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(s);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,n=o.token,await Ht.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&n){let s={token:n,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=s,r.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(s)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(s)}this.emit("authenticated",s)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),be));t.set("snowx_auth_token",e.userId),t.set("snowx_access_token",e.token),this.authToken=e,this.emit("authenticated",e)}catch(t){console.error("❌ Failed to save auth token:",t)}}async clearStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),be));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,xn(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}ie.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(ce(),be));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),r.debug(`User tier updated: ${ie.getDisplayName(t)} (${e.tier})`),r.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 Gs(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Xs(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await zs(this.auth,e,t);return this.currentUser=s.user,n&&await Vs(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(Te(),je));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await js(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(()=>(Te(),je));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ce(),be)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let i of n)t.remove(i);if(e){let i=`snowx_device_id_${e}`;t.remove(i)}let o=t.getAllKeys().filter(i=>i.startsWith("snowx_device_id_"));for(let i of o)t.remove(i)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Ee.post(`${this.snowxAuthEndpoint}/login`,e):t=await Ee.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await Ee.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ce(),be));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let o=!1,i,a=xn(this.auth,async l=>{if(!o)if(o=!0,clearTimeout(i),a(),l)try{let u=await l.getIdToken(!0);s(u)}catch{s(null)}else s(null)});i=setTimeout(()=>{o||(o=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(r.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){r.debug("Using existing authentication token"),r.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(r.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(r.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return r.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(r.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):r.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!"),r.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!"),r.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}`),r.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),r.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..."),r.debug("Signing into Firebase with custom token...");let t=await Ks(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),r.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"}`),r.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),r.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},i=this.authToken?.token,a={"Content-Type":"application/json"};i?(a.Authorization=`Bearer ${i}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let l=await Ee.post(s,o,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let p=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${p}`),new Error(`Custom token API failed: ${p}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),r.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),r.error("Failed to get custom token:",{attempt:n,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let p=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${p}ms... (${t-1} attempts remaining)`),r.debug(`Retrying in ${p}ms...`),await new Promise(f=>setTimeout(f,p)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await Ee.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,o=s.subscription?.tier??0;return{id:t,email:s.email,tier:o}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await Ee.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let o={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=n,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(i){throw i.response?.status===401||i.response?.status===403||i.response?.status===404?(r.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):r.warn("Firebase auth failed with transient error - keeping token for retry"),i}return this.emit("authStateChanged",o),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await Ee.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return ie.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Ee.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var En={};ae(En,{MessageQueueManager:()=>me});import{EventEmitter as Js}from"events";var me,Re=R(()=>{"use strict";H();me=class c extends Js{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),r.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),r.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)}`}}});import{encode as In,decode as Pn,isWithinTokenLimit as Dn,countTokens as Ys}from"gpt-tokenizer";var Fe,Zs,eo,le,$e=R(()=>{"use strict";Fe=25e3,Zs=1400,eo=17e3,le=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??Fe,this.previewTokens=e?.previewTokens??Zs,this.maxContentTokens=e?.maxContentTokens??eo}count(e){return e?Ys(e):0}encode(e){return e?In(e):[]}decode(e){return!e||e.length===0?"":Pn(e)}isWithinLimit(e,t){return e?Dn(e,t??this.maxResponseTokens):0}exceedsResponseLimit(e){return this.isWithinLimit(e,this.maxResponseTokens)===!1}exceedsContentLimit(e){return this.isWithinLimit(e,this.maxContentTokens)===!1}truncate(e,t){if(!e)return{text:"",tokens:0,truncated:!1};let n=t??this.maxResponseTokens,s=Dn(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let i=In(e).slice(0,n);return{text:Pn(i),tokens:n,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let n=t??this.previewTokens,s=this.count(e);if(s<=n)return{preview:e,totalTokens:s,previewTokens:s,remainingTokens:0};let{text:o,tokens:i}=this.truncate(e,n);return{preview:o,totalTokens:s,previewTokens:i,remainingTokens:s-i}}truncateContent(e,t){let n=t??this.maxContentTokens,s=this.truncate(e,n);return s.truncated?s.text+`
|
|
4
|
+
... [Content truncated at ${s.tokens.toLocaleString()} tokens]`:e}truncateOutput(e,t){let n=t??this.maxResponseTokens,s=this.truncate(e,n);return s.truncated?s.text+`
|
|
5
|
+
|
|
6
|
+
[Output truncated at ${s.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,n){let{preview:s,totalTokens:o,previewTokens:i,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`Response too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
|
|
7
|
+
|
|
8
|
+
`;return l+=`TEMP FILE PATH: ${t}
|
|
9
|
+
`,l+=`Use read_file, grep, cat, or other tools to access the full content.
|
|
10
|
+
|
|
11
|
+
`,l+=`PREVIEW (first ${i.toLocaleString()} tokens):
|
|
12
|
+
`,l+=`${"─".repeat(50)}
|
|
13
|
+
`,l+=s,a>0&&(l+=`
|
|
14
|
+
${"─".repeat(50)}`,l+=`
|
|
15
|
+
... (${a.toLocaleString()} more tokens available in temp file)`),l+=`
|
|
16
|
+
|
|
17
|
+
To read full content: use tools like 'read_file' with path above`,l}formatLargeFileMessage(e,t,n){let{preview:s,totalTokens:o,previewTokens:i,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`File too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit).
|
|
18
|
+
|
|
19
|
+
`;return l+=`FILE PATH: ${t}
|
|
20
|
+
|
|
21
|
+
`,l+=`This file is already on disk. Use Read tool with offset and limit parameters.
|
|
22
|
+
|
|
23
|
+
`,l+=`PREVIEW (first ${i.toLocaleString()} tokens):
|
|
24
|
+
`,l+=`${"─".repeat(50)}
|
|
25
|
+
`,l+=s,a>0&&(l+=`
|
|
26
|
+
${"─".repeat(50)}`,l+=`
|
|
27
|
+
... (${a.toLocaleString()} more tokens)`),l}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});var rt,An=R(()=>{"use strict";H();rt=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),r.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,o]of this.tools.entries())if(s.toLowerCase()===n)return o}async executeTool(e,t,n,s){let o=this.getTool(e);if(!o)return r.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{r.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let i=Date.now(),a=await o.execute(t,e,n,s),l=Date.now()-i;r.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(p=>p.text||"").join(`
|
|
28
|
+
`);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(i){return r.error(`[ToolRegistry] Tool execution error (${e}):`,i),{id:t,toolName:e,success:!1,output:"",error:i instanceof Error?i.message:String(i)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);r.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),r.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var Nn={};ae(Nn,{ToolDisplay:()=>O});import X from"chalk";var O,ge=R(()=>{"use strict";O=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,n){if(c.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(X.cyan(`
|
|
29
|
+
${s} ${X.bold(e)}`)),t&&console.log(X.gray(` ${t}`)),n){let o=n.length>120?n.substring(0,120)+X.gray("..."):n;console.log(X.white(` ${o}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(c.customUIMode)return;let{toolName:t,output:n,success:s,executionTime:o,truncateLines:i=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,i):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,i):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,i):a=this.formatGenericOutput(n,i)),a&&a.trim()&&console.log(a);let l=s?X.green("✓"):X.red("✗"),u=s?X.green("SUCCESS"):X.red("FAILED"),p=o?X.gray(` (${o}ms)`):"";console.log(`${l} ${u}${p}
|
|
6
30
|
`)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
|
|
7
|
-
`),u=a.slice(0,20).map(p=>
|
|
31
|
+
`),u=a.slice(0,20).map(p=>X.gray(" ")+p).join(`
|
|
8
32
|
`);return a.length>20&&(u+=`
|
|
9
|
-
`+
|
|
10
|
-
`),s=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";s&&(o+=
|
|
11
|
-
`);let
|
|
12
|
-
`),
|
|
13
|
-
`+
|
|
14
|
-
`).filter(
|
|
15
|
-
`);let o=n.slice(0,t).map(
|
|
33
|
+
`+X.gray(` ... (${a.length-20} more lines)`)),u}let n=e.split(`
|
|
34
|
+
`),s=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";s&&(o+=X.gray(" ")+X.dim(s[1])+`
|
|
35
|
+
`);let i=n.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return i.length>0?(o+=i.slice(0,10).map(a=>X.gray(" ")+X.dim(a)).join(`
|
|
36
|
+
`),i.length>10&&(o+=`
|
|
37
|
+
`+X.gray(` ... (${i.length-10} more changes)`)),o):this.truncateOutput(e,Math.min(15,t))}static formatWriteOutput(e,t){return this.truncateOutput(e,Math.min(15,t))}static formatBashOutput(e,t){return this.truncateOutput(e,Math.min(30,t))}static formatGenericOutput(e,t){return this.truncateOutput(e,Math.min(20,t))}static truncateOutput(e,t){let n=e.split(`
|
|
38
|
+
`).filter(i=>i.trim());if(n.length===0)return"";if(n.length<=t)return n.map(i=>X.gray(" ")+X.dim(i)).join(`
|
|
39
|
+
`);let o=n.slice(0,t).map(i=>X.gray(" ")+X.dim(i)).join(`
|
|
16
40
|
`);return o+=`
|
|
17
|
-
`+
|
|
18
|
-
${
|
|
41
|
+
`+X.gray(` ... (${n.length-t} more lines)`),o}static error(e,t){c.customUIMode||(console.log(`
|
|
42
|
+
${X.red("✗")} ${X.red.bold(e)} ${X.red("ERROR")}`),console.log(X.gray(" ")+X.white(t)),console.log(""))}}});import Rn from"os";import qt from"path";function at(){return process.platform==="win32"}function Ne(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,Rn.homedir())),at()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,Rn.homedir())),!at()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),at()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Oe(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=Ne(c);if(at()){let n=qt.basename(e).split(".")[0].toUpperCase();if(to.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return qt.isAbsolute(e)?qt.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
|
|
19
43
|
|
|
20
44
|
Path must be absolute (start with / on Unix or C:\\ on Windows)
|
|
21
45
|
|
|
22
46
|
Wrong: Downloads/file.pdf
|
|
23
|
-
Correct: /Users/username/Downloads/file.pdf`}}var
|
|
24
|
-
`),
|
|
47
|
+
Correct: /Users/username/Downloads/file.pdf`}}var to,ct=R(()=>{"use strict";to=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import Fn from"path";var no,so,lt,$n=R(()=>{"use strict";H();ge();ct();$e();no=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],so={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon",tiff:"image/tiff",tif:"image/tiff"},lt=class{toolNames=["read","Read"];async execute(e,t,n,s){let o=n.file_path||n.path,i=n.offset,a=n.limit;if(!o)throw new Error("Missing file_path or path argument");let l=Ne(o),u=Oe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];r.debug(`[ReadFileTool] Reading file: ${l}${i!==void 0?`, offset: ${i}`:""}${a!==void 0?`, limit: ${a}`:""}`);let p=Date.now();O.start("Read",n.description,l);try{let f=await import("fs/promises");try{await f.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let v=await f.stat(l);if(v.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let S=Fn.extname(l).substring(1).toLowerCase();if(no.includes(S)){r.debug(`[ReadFileTool] Image file detected: ${l}`);let D=(await f.readFile(l)).toString("base64"),b=so[S]||"application/octet-stream",I=Fn.basename(l);r.debug(`[ReadFileTool] Image converted to base64: ${I} (${D.length} chars)`);let F=Date.now()-p;return O.result({toolName:"Read",filePath:l,output:`Image loaded: ${I}`,success:!0,executionTime:F}),[{type:"image_url",image_url:{url:`data:${b};base64,${D}`}}]}let d=await f.readFile(l,"utf-8"),h=d.length,m=d.split(`
|
|
48
|
+
`),k=m.length,x=Math.max(i??0,0),E=new le;if(i===void 0&&a===void 0&&E.exceedsResponseLimit(d)){let P=E.count(d),D=v.size/1024,b=D/1024,I=b>=1?`${b.toFixed(2)} MB`:`${D.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
|
|
25
49
|
|
|
26
50
|
File Information:
|
|
27
51
|
- Path: ${l}
|
|
28
|
-
- Size: ${
|
|
29
|
-
- Total Lines: ${
|
|
30
|
-
-
|
|
52
|
+
- Size: ${I} (${P.toLocaleString()} tokens)
|
|
53
|
+
- Total Lines: ${k}
|
|
54
|
+
- Token Limit: ${Fe.toLocaleString()}
|
|
31
55
|
|
|
32
56
|
Suggested Solutions:
|
|
33
57
|
1. Read specific lines using offset and limit:
|
|
@@ -41,19 +65,19 @@ Suggested Solutions:
|
|
|
41
65
|
- Lines 2000-4000: Read(path: "${l}", offset: 2000, limit: 2000)
|
|
42
66
|
- And so on...
|
|
43
67
|
|
|
44
|
-
The file has ${
|
|
45
|
-
`),
|
|
68
|
+
The file has ${k.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(k===0||d.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(x>=k)return[{type:"text",text:`Error: Offset ${x} is beyond file length. File has ${k} total lines. Try a smaller offset (0 to ${k-1}).`}];let w=a!==void 0?Math.min(x+a,k):k,T=m.slice(x,w),N=T.map((P,D)=>`${(x+D+1).toString().padStart(6," ")} ${P}`).join(`
|
|
69
|
+
`),B=N;if(i!==void 0||a!==void 0){let P=`
|
|
46
70
|
|
|
47
|
-
[Read ${
|
|
71
|
+
[Read ${T.length} lines (${x+1}-${w}) of ${k} total lines]`;B=N+P}let M=Date.now()-p;return O.result({toolName:"Read",filePath:l,output:B,success:!0,executionTime:M}),[{type:"text",text:B}]}catch(f){r.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 S=Date.now()-p;return O.result({toolName:"Read",filePath:l,output:v,success:!1,executionTime:S}),[{type:"text",text:v}]}}}});import ut from"fs/promises";import oo from"form-data";import Gt from"axios";import Xt from"path";var dt,On=R(()=>{"use strict";H();ge();se();dt=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let o=n.path;if(!o)throw new Error("Missing path argument");r.debug(`[ReadSpecialFileTool] Converting file: ${o}`);let i=Date.now();O.start("ReadSpecialFile",n.description,o);try{try{await ut.access(o)}catch{return[{type:"text",text:`Error: File does not exist at path: ${o}`}]}let a=Xt.extname(o).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let x=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
|
|
48
72
|
|
|
49
|
-
Supported file types: ${
|
|
73
|
+
Supported file types: ${x}`}]}let l=await ut.stat(o),u=Xt.basename(o);if(r.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){r.debug(`[ReadSpecialFileTool] Image file detected: ${o}`);let E=(await ut.readFile(o)).toString("base64"),w=this.imageMimeTypes[a]||"application/octet-stream";r.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${E.length} chars)`);let T=Date.now()-i;return O.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:T}),[{type:"image_url",image_url:{url:`data:${w};base64,${E}`}}]}let p=await this.uploadToBatchAPI(o,u);r.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${p}`);let f=await this.pollBatchStatus(p);r.debug("[ReadSpecialFileTool] Conversion completed");let v=f.files[0];if(!v||v.status==="failed"){let x=v?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${x}`}]}let S=await this.fetchFileContent(v.file_id);if(!S.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let y=l.size/1024,d=y/1024,h=d>=1?`${d.toFixed(2)} MB`:`${y.toFixed(2)} KB`,m=`# File: ${u}
|
|
50
74
|
**Type:** ${a.toUpperCase()}
|
|
51
|
-
**Size:** ${
|
|
75
|
+
**Size:** ${h}
|
|
52
76
|
**Conversion:** ✅ Successful
|
|
53
77
|
|
|
54
78
|
---
|
|
55
79
|
|
|
56
|
-
${
|
|
80
|
+
${S.markdown_content}`,k=Date.now()-i;return O.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${h})`,success:!0,executionTime:k}),[{type:"text",text:m}]}catch(a){r.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
|
|
57
81
|
|
|
58
82
|
This could be due to:
|
|
59
83
|
• File corruption or invalid format
|
|
@@ -61,37 +85,37 @@ This could be due to:
|
|
|
61
85
|
• Unsupported document structure
|
|
62
86
|
• File is password-protected or encrypted
|
|
63
87
|
|
|
64
|
-
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-
|
|
88
|
+
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-i;return O.result({toolName:"ReadSpecialFile",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let n=await ut.readFile(e),s=Xt.extname(t).substring(1).toLowerCase(),i=await q.getInstance().getFirebaseIdToken(),a=new oo;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let l={...a.getHeaders()};i&&(l.Authorization=`Bearer ${i}`);let u=await Gt.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let n=await q.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let o=1;o<=this.maxPollAttempts;o++)try{let a=(await Gt.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(r.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(i){throw i.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${i.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await q.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let o=await Gt.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(o.data.status==="failed")throw new Error(o.data.error||"Unknown conversion error");return o.data}catch(o){throw o.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${o.message}`)}}getMimeType(e){switch(e.toLowerCase()){case"pdf":return"application/pdf";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"doc":return"application/msword";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xls":return"application/vnd.ms-excel";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"ppt":return"application/vnd.ms-powerpoint";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var pt,_n=R(()=>{"use strict";H();ge();ct();pt=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let o=n.file_path,i=n.content,a=n.edits;if(!o)throw new Error("Missing file_path argument");let l=Ne(o),u=Oe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let p=Date.now();return O.start("Write",n.description,l),i!=null?await this.executeSimpleWrite(l,i,p):await this.executeEditsMode(l,a,p)}async executeSimpleWrite(e,t,n){r.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),i=(await import("path")).dirname(e);await s.mkdir(i,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
|
|
65
89
|
`),l="";for(let f=0;f<Math.min(a.length,8);f++)l+=`+ ${a[f]}
|
|
66
90
|
`;a.length>8&&(l+=`+ ...
|
|
67
91
|
|
|
68
|
-
(${a.length-8} more lines)`);let u=l.trim();
|
|
69
|
-
`),d="";for(let
|
|
70
|
-
`;return
|
|
92
|
+
(${a.length-8} more lines)`);let u=l.trim();r.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let p=Date.now()-n;return O.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:p}),[{type:"text",text:u}]}catch(s){r.debug(`[WriteFileTool] Failed to write file: ${s.message}`);let o=`Error writing file: ${s.message}`,i=Date.now()-n;return O.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:i}),[{type:"text",text:o}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");r.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let s=await import("fs/promises"),o=await import("path");for(let S=0;S<t.length;S++){let y=t[S];if(!y||typeof y!="object")throw new Error(`Edit operation ${S+1} must be an object with 'search' and 'replace' fields`);if(!y.hasOwnProperty("search")||typeof y.search!="string")throw new Error(`Edit operation ${S+1} missing required 'search' field (must be string)`);if(!y.hasOwnProperty("replace")||typeof y.replace!="string")throw new Error(`Edit operation ${S+1} missing required 'replace' field (must be string)`)}let i=t[0].search==="",a;if(i)if(r.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let S=o.dirname(e);await s.mkdir(S,{recursive:!0}),await s.writeFile(e,a,"utf-8");let y=a.split(`
|
|
93
|
+
`),d="";for(let h=0;h<Math.min(y.length,8);h++)d+=`+ ${y[h]}
|
|
94
|
+
`;return y.length>8&&(d+=`+ ...
|
|
71
95
|
|
|
72
|
-
(${
|
|
73
|
-
`),
|
|
74
|
-
`;return f.length>8&&(
|
|
96
|
+
(${y.length-8} more lines)`),r.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{r.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),r.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,p=[];for(let S=0;S<t.length;S++){let y=t[S];if(r.debug(`[WriteFileTool] Applying edit ${S+1}/${t.length}`),y.search==="")if(i){p.push({index:S+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{r.debug("[WriteFileTool] Rewriting entire existing file"),u=y.replace,p.push({index:S+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let d=u.indexOf(y.search);if(d!==-1)u=u.substring(0,d)+y.replace+u.substring(d+y.search.length),r.debug("[WriteFileTool] Replaced first occurrence"),p.push({index:S+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let h=`Search string not found: '${y.search}'`;return p.push({index:S+1,success:!1,message:h,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${S+1}: '${y.search}'\\n\\nEdit Summary:\\n- Total edits: ${p.length}\\n- Successful: ${p.filter(k=>k.success).length}\\n- Failed: ${p.filter(k=>!k.success).length}\\n\\nIndividual Edit Results:\\n`+p.map(k=>`${k.success?"✅":"❌"} Edit ${k.index}: ${k.message}`).join("\\n")}]}}await s.writeFile(e,u,"utf-8"),r.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let f=u.split(`
|
|
97
|
+
`),v="";for(let S=0;S<Math.min(f.length,8);S++)v+=`+ ${f[S]}
|
|
98
|
+
`;return f.length>8&&(v+=`+ ...
|
|
75
99
|
|
|
76
|
-
(${f.length-8} more lines)`),[{type:"text",text:
|
|
100
|
+
(${f.length-8} more lines)`),[{type:"text",text:v.trim()}]}catch(s){return r.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var mt,Mn=R(()=>{"use strict";H();ge();ct();mt=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let o=n.file_path,i=n.old_string,a=n.new_string,l=n.replace_all===!0;if(!o)throw new Error("Missing file_path argument");if(i==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let u=Ne(o),p=Oe(u);if(!p.valid)return[{type:"text",text:`Error: ${p.error}`}];r.debug(`[EditFileTool] Editing file: ${u}`);let f=Date.now();O.start("Edit",n.description,u);try{let v=await import("fs/promises"),S=await v.readFile(u,"utf-8"),y,d=0;if(l)for(y=S;y.includes(i);)y=y.replace(i,a),d++;else S.includes(i)?(y=S.replace(i,a),d=1):y=S;if(d===0){let E=`No matches found for the specified old_string in file: ${u}`,w=Date.now()-f;return O.result({toolName:"Edit",filePath:u,output:E,success:!1,executionTime:w}),[{type:"text",text:E}]}await v.writeFile(u,y,"utf-8");let h=`Successfully edited file: Replaced ${d} occurrence(s)`;r.debug(`[EditFileTool] ${h}`);let m=Date.now()-f,k=(await import("chalk")).default,x=`${k.red("- "+i.split(`
|
|
77
101
|
`).slice(0,5).join(`
|
|
78
102
|
- `))}
|
|
79
|
-
${
|
|
103
|
+
${k.green("+ "+a.split(`
|
|
80
104
|
`).slice(0,5).join(`
|
|
81
105
|
+ `))}
|
|
82
106
|
|
|
83
|
-
Replaced ${d} occurrence(s)`;return
|
|
107
|
+
Replaced ${d} occurrence(s)`;return O.result({toolName:"Edit",filePath:u,output:x,success:!0,executionTime:m}),[{type:"text",text:h}]}catch(v){r.debug(`[EditFileTool] Failed to edit file: ${v.message}`);let S=`Error editing file: ${v.message}`,y=Date.now()-f;return O.result({toolName:"Edit",filePath:u,output:S,success:!1,executionTime:y}),[{type:"text",text:S}]}}}});var gt,Ln=R(()=>{"use strict";H();gt=class{toolNames=["upload_file"];async execute(e,t,n,s){let o=n.file_path;if(!o)throw new Error("Missing file_path argument");return r.debug(`[UploadFileTool] Upload file not implemented for CLI: ${o}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${o}`}]}}});import zt from"fs/promises";import io from"path";import ro from"form-data";import ao from"axios";var ht,Un=R(()=>{"use strict";H();ge();se();ht=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let i=Date.now();O.start("DeployZipHTML",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let N=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 ${N} seconds.`)}r.debug(`[DeployZipHTML] Deploying HTML project: ${o}`);try{await zt.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 zt.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 zt.readFile(o),f=io.basename(o).replace(/[\r\n\t"']/g,"_");r.debug(`[DeployZipHTML] File: ${f}, Size: ${l.size} bytes`);let S=await q.getInstance().getFirebaseIdToken();if(!S)throw new Error("User must be authenticated to deploy projects");let y=new ro;y.append("zipFile",p,{filename:f,contentType:"application/zip"});let d="https://snowx.ai/api/v2/deploy-zip";r.debug(`[DeployZipHTML] Uploading to ${d}`);let h=await ao.post(d,y,{headers:{...y.getHeaders(),Authorization:`Bearer ${S}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(h.status!==200&&h.status!==201)throw new Error(`Deployment failed with status ${h.status}: ${JSON.stringify(h.data)}`);let m=h.data;r.debug("[DeployZipHTML] Deployed successfully"),r.debug(`[DeployZipHTML] Response: ${JSON.stringify(m,null,2)}`);let k=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,x=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let w=`# HTML Project Deployed Successfully!
|
|
84
108
|
|
|
85
|
-
**Deployment URL**: ${
|
|
109
|
+
**Deployment URL**: ${k}
|
|
86
110
|
|
|
87
111
|
**Project**: ${f}
|
|
88
112
|
**Type**: Static HTML
|
|
89
|
-
${
|
|
90
|
-
`:""}${
|
|
113
|
+
${x?`**Deploy ID**: ${x}
|
|
114
|
+
`:""}${E?`**Site ID**: ${E}
|
|
91
115
|
`:""}
|
|
92
116
|
Your site is now live and accessible!
|
|
93
117
|
|
|
94
|
-
${m.message||""}`,
|
|
118
|
+
${m.message||""}`,T=Date.now()-i;return O.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${k}`,success:!0,executionTime:T}),[{type:"text",text:w}]}catch(a){r.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let l=`HTML deployment failed
|
|
95
119
|
|
|
96
120
|
${a.message}
|
|
97
121
|
|
|
@@ -102,18 +126,18 @@ Troubleshooting:
|
|
|
102
126
|
4. Check network connectivity
|
|
103
127
|
5. Ensure ZIP file is under 100MB
|
|
104
128
|
|
|
105
|
-
If the issue persists, contact support.`,u=Date.now()-
|
|
129
|
+
If the issue persists, contact support.`,u=Date.now()-i;return O.result({toolName:"DeployZipHTML",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import jt from"fs/promises";import co from"path";import lo from"form-data";import uo from"axios";var ft,Wn=R(()=>{"use strict";H();ge();se();ft=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let i=Date.now();O.start("DeployZipReact",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let N=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 ${N} seconds.`)}r.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await jt.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 jt.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 jt.readFile(o),f=co.basename(o).replace(/[\r\n\t"']/g,"_");r.debug(`[DeployZipReact] File: ${f}, Size: ${l.size} bytes`);let S=await q.getInstance().getFirebaseIdToken();if(!S)throw new Error("User must be authenticated to deploy projects");let y=new lo;y.append("zipFile",p,{filename:f,contentType:"application/zip"});let d="https://snowx.ai/api/v2/deploy-zip-react";r.debug(`[DeployZipReact] Uploading to ${d}`);let h=await uo.post(d,y,{headers:{...y.getHeaders(),Authorization:`Bearer ${S}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(h.status!==200&&h.status!==201)throw new Error(`Deployment failed with status ${h.status}: ${JSON.stringify(h.data)}`);let m=h.data;r.debug("[DeployZipReact] Deployed successfully"),r.debug(`[DeployZipReact] Response: ${JSON.stringify(m,null,2)}`);let k=m.data?.deployUrl||m.deployUrl||m.url||m.deploymentUrl||m.site_url||m.siteUrl||m.website_url,x=m.data?.deployId||m.deployId||m.projectId||m.deploymentId,E=m.data?.siteId||m.siteId;this.deployCount++;let w=`# React Project Deployed Successfully!
|
|
106
130
|
|
|
107
|
-
**Deployment URL**: ${
|
|
131
|
+
**Deployment URL**: ${k}
|
|
108
132
|
|
|
109
133
|
**Project**: ${f}
|
|
110
134
|
**Type**: React / SPA
|
|
111
|
-
${
|
|
112
|
-
`:""}${
|
|
135
|
+
${x?`**Deploy ID**: ${x}
|
|
136
|
+
`:""}${E?`**Site ID**: ${E}
|
|
113
137
|
`:""}
|
|
114
138
|
Your React app is now live and accessible!
|
|
115
139
|
|
|
116
|
-
${m.message||""}`,
|
|
140
|
+
${m.message||""}`,T=Date.now()-i;return O.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${k}`,success:!0,executionTime:T}),[{type:"text",text:w}]}catch(a){r.error(`[DeployZipReact] Deployment failed: ${a.message}`);let l=`React deployment failed
|
|
117
141
|
|
|
118
142
|
${a.message}
|
|
119
143
|
|
|
@@ -124,9 +148,9 @@ Troubleshooting:
|
|
|
124
148
|
4. Check network connectivity
|
|
125
149
|
5. Ensure ZIP file is under 100MB
|
|
126
150
|
|
|
127
|
-
If the issue persists, contact support.`,u=Date.now()-
|
|
151
|
+
If the issue persists, contact support.`,u=Date.now()-i;return O.result({toolName:"DeployZipReact",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Bn=R(()=>{"use strict"});function Ve(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("'END'")||c.includes('"END"')))return he.extended;let n=["python","python3","python2","node ","nodejs","ruby","perl","php","java ","kotlin","scala","Rscript","julia"];for(let l of n)if(e.includes(l))return he.extended;let s=["pandas","numpy","scipy","matplotlib","import ","from ","require(","import(","DataFrame","Series"];for(let l of s)if(c.includes(l))return he.extended;if(c.includes(`
|
|
128
152
|
`)&&c.split(`
|
|
129
|
-
`).length>2)return
|
|
153
|
+
`).length>2)return he.extended;let o=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"]),a=new Set(["make","cmake","npm","yarn","pip","cargo","mvn","gradle","docker","git","rsync","scp","ssh","curl","wget","find","locate","tar","zip","unzip","brew","apt","yum"]);return o.has(t)||i.has(t)&&c.length<100?he.fast:a.has(t)?he.extended:c.length<20?he.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?he.default:he.extended:he.default}var he,Vt=R(()=>{"use strict";Bn();he={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as po,exec as mo}from"child_process";import{promisify as go}from"util";function Kt(){return process.platform}function Qe(){return process.platform==="win32"}function vo(){return process.platform==="darwin"}function Hn(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(Qe()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let s=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(s)return{isPrivileged:!0,reason:`Privileged command: ${s.trim()}`};let i=[{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 i?{isPrivileged:!0,reason:i.desc}:{isPrivileged:!1}}function qn(){return Qe()?"PowerShell or Command Prompt":(vo(),"Terminal")}function Gn(c,e){let t=qn();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
|
|
130
154
|
|
|
131
155
|
Reason: ${e}
|
|
132
156
|
|
|
@@ -140,7 +164,7 @@ To run this command:
|
|
|
140
164
|
2. Run the command manually: ${c}
|
|
141
165
|
3. Enter your password when prompted
|
|
142
166
|
|
|
143
|
-
Alternative: Break down the task into non-privileged commands if possible.`}function
|
|
167
|
+
Alternative: Break down the task into non-privileged commands if possible.`}function Xn(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:u,reason:p}of n)if(e.startsWith(u)||e.includes(`&& ${u}`)||e.includes(`; ${u}`))return{isInteractive:!0,reason:p};let s=[{cmd:"npm init",except:["npm init -y","npm init --yes"],reason:"npm init requires interactive prompts (use npm init -y for non-interactive)"},{cmd:"yarn init",except:["yarn init -y","yarn init --yes"],reason:"yarn init requires interactive prompts (use yarn init -y for non-interactive)"},{cmd:"pnpm init",except:["pnpm init -y","pnpm init --yes"],reason:"pnpm init requires interactive prompts"}];for(let{cmd:u,except:p,reason:f}of s)if(e.startsWith(u)&&!p?.some(S=>e.startsWith(S)))return{isInteractive:!0,reason:f};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let u of a)if(e.startsWith(u))return{isInteractive:!0,reason:`${u} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let l=["git push","git pull","git fetch","git clone"];for(let u of l)e.startsWith(u);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function zn(c,e){let t=qn();return`This command requires interactive input and cannot run in the Bash tool.
|
|
144
168
|
|
|
145
169
|
Reason: ${e}
|
|
146
170
|
|
|
@@ -154,22 +178,22 @@ To run this command:
|
|
|
154
178
|
2. Run the command manually: ${c}
|
|
155
179
|
3. Follow the interactive prompts
|
|
156
180
|
|
|
157
|
-
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}var
|
|
181
|
+
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}var ho,fo,Ke,Je,Qt=R(()=>{"use strict";Vt();$e();ho=go(mo),fo=8500,Ke=new le({maxResponseTokens:fo});Je=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,n,s,o="new",i){let a=i||Ve(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Qe())await ho(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let s=Date.now(),o=Kt(),i,a;Qe()?(i="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(i="/bin/bash",a=["-c",e]);let l=po(i,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Qe()}),u="",p="",f=!1,v=!1,S=!1,y=null,d=null,h=null,m=x=>{v||(v=!0,clearTimeout(k),d&&clearTimeout(d),h&&clearTimeout(h),n(x))},k=setTimeout(async()=>{v||(f=!0,l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),d=setTimeout(async()=>{v||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),this.cleanupStreams(l),setTimeout(()=>{if(!v){let x=Date.now()-s;m({output:u+p+`
|
|
158
182
|
|
|
159
|
-
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:
|
|
160
|
-
`);
|
|
183
|
+
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:x,platform:o})}},1e3))},1500))},t.maxTimeout);l.stdout?.on("data",x=>{u+=x.toString()}),l.stderr?.on("data",x=>{p+=x.toString()}),l.on("exit",(x,E)=>{S=!0,y=x,h=setTimeout(()=>{if(v)return;clearTimeout(k),d&&clearTimeout(d),this.cleanupStreams(l);let w=Date.now()-s,T=(u+p).trim();if(Ke.exceedsResponseLimit(T)){let N=Ke.truncate(T),B=N.text.split(`
|
|
184
|
+
`);T=N.text+`
|
|
161
185
|
|
|
162
|
-
[Output truncated at `+
|
|
163
|
-
[Showing first `+
|
|
186
|
+
[Output truncated at `+N.tokens.toLocaleString()+` tokens]
|
|
187
|
+
[Showing first `+B.length+" lines of output]"}m(f?{output:T+`
|
|
164
188
|
|
|
165
|
-
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:
|
|
166
|
-
`).length
|
|
189
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:w,platform:o}:{output:T,exitCode:x||0,isSuccess:(x||0)===0,duration:w,platform:o})},1500)}),l.on("close",x=>{if(v)return;h&&clearTimeout(h),clearTimeout(k),d&&clearTimeout(d);let E=Date.now()-s,w=(u+p).trim();if(Ke.exceedsResponseLimit(w)){let T=Ke.count(w),N=Ke.truncate(w),M=N.text.split(`
|
|
190
|
+
`).length;w=N.text+`
|
|
167
191
|
|
|
168
|
-
[Output truncated at `+
|
|
169
|
-
[Showing first `+
|
|
170
|
-
[Total output was `+
|
|
192
|
+
[Output truncated at `+N.tokens.toLocaleString()+` tokens]
|
|
193
|
+
[Showing first `+M+` lines of output]
|
|
194
|
+
[Total output was `+T.toLocaleString()+" tokens]"}m(f?{output:w+`
|
|
171
195
|
|
|
172
|
-
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:
|
|
196
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:E,platform:o}:{output:w,exitCode:x||0,isSuccess:(x||0)===0,duration:E,platform:o})}),l.on("error",x=>{if(v)return;let E=Date.now()-s;m({output:"Process execution failed: "+x.message,exitCode:-1,isSuccess:!1,duration:E,platform:o})})})}formatExitCodeInfo(e){let t;switch(e){case 0:t="Success";break;case 1:t="General error";break;case 2:t="Misuse of shell command";break;case 126:t="Command cannot execute (permission denied)";break;case 127:t="Command not found";break;case 128:t="Invalid exit argument";break;case 130:t="Terminated by Ctrl+C (SIGINT)";break;case 137:t="Killed by SIGKILL";break;case 143:t="Terminated by SIGTERM";break;default:e>128?t=`Terminated by signal ${e-128}`:e<0?t="Terminated by timeout or force kill":t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}}});var Jt={};ae(Jt,{ToolCallingService:()=>Ye});import{EventEmitter as bo}from"events";import jn from"axios";import{exec as yo,spawn as Vn}from"child_process";import{promisify as wo}from"util";import Y from"fs/promises";import ye from"fs";import _e from"path";import To from"os";var Fa,Ye,vt=R(()=>{"use strict";Qt();Vt();$e();Fa=wo(yo),Ye=class _ToolCallingService extends bo{static instance;tools=new Map;executionHistory=[];tokenCounter=new le;shellSessionManager=Je.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;backgroundProcesses=new Map;backgroundProcessCounter=0;constructor(){super(),this.initializeDefaultTools()}static getInstance(){return _ToolCallingService.instance||(_ToolCallingService.instance=new _ToolCallingService),_ToolCallingService.instance}initializeDefaultTools(){this.registerTool({name:"web_search",description:"Search the web for information on a given topic",parameters:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 5)",default:5}},required:["query"]},handler:this.webSearch.bind(this),category:"web",enabled:!0}),this.registerTool({name:"read_file",description:"Read the contents of a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to read"}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: write or append",enum:["write","append"],default:"write"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"list_directory",description:"List the contents of a directory",parameters:{type:"object",properties:{directory_path:{type:"string",description:"Path to the directory to list"},include_hidden:{type:"boolean",description:"Include hidden files and directories",default:!1}},required:["directory_path"]},handler:this.listDirectory.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Bash",description:"Execute shell commands with support for background execution, timeouts, and output truncation",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},description:{type:"string",description:"Human-readable description of what the command does"},timeout:{type:"number",description:"Timeout in milliseconds (default: auto-detected based on command)"},run_in_background:{type:"boolean",description:"Run command in background and return immediately",default:!1}},required:["command"]},handler:this.bashCommand.bind(this),category:"system",enabled:!0}),this.registerTool({name:"execute_command",description:`Execute shell commands with persistent session support and interactive prompt handling. Supports both single-shot and persistent execution modes for multi-step workflows.
|
|
173
197
|
|
|
174
198
|
🔧 SESSION MODE SELECTION (REQUIRED):
|
|
175
199
|
• Use session: "existing" for workflows that need persistent state:
|
|
@@ -203,38 +227,25 @@ Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive)
|
|
|
203
227
|
4. LLM receives prompt details and makes decision
|
|
204
228
|
5. LLM uses provide_input to send appropriate response
|
|
205
229
|
6. Command execution continues with provided input
|
|
206
|
-
7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content shows matching lines, files_with_matches shows file paths (default), count shows match counts",default:"files_with_matches"},case_insensitive:{type:"boolean",description:"Case insensitive search",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let n={};try{n=JSON.parse(c.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${t}': ${o}`)}let{ToolDisplay:s}=await Promise.resolve().then(()=>(me(),xn));s.start(t,n.description,n.command||n.file_path);try{let o=this.tools.get(t);if(!o)throw new Error(`Tool '${t}' not found`);if(!o.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await o.handler(n),a=Date.now()-e,l=this.handleLargeResponse(r,t);return this.executionHistory.push({toolName:t,args:n,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),s.result({toolName:t,command:n.command,filePath:n.file_path,description:n.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(o){let r=Date.now()-e,a={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:t,error:o,executionTime:r}),s.error(t,o.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(c){return c.success?c.result?typeof c.result=="string"?c.result:typeof c.result=="object"&&"stdout"in c.result?c.result.stdout||c.result.stderr||"":typeof c.result=="object"&&"content"in c.result?c.result.content||"":JSON.stringify(c.result,null,2):"":c.error||"Unknown error"}async captureFrontendToolResult(c,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(be(),$e)),n=t.getInstance(),s=this.extractOutputForDisplay(e);n.captureFrontendToolResult(c,s,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,n=(await Ln.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,s=[];if(n.AbstractText&&s.push({title:n.Heading||"Instant Answer",content:n.AbstractText,url:n.AbstractURL||"",type:"instant_answer"}),n.RelatedTopics&&n.RelatedTopics.length>0)for(let o of n.RelatedTopics.slice(0,c.num_results||5))o.Text&&s.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:s,total_results:s.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await Y.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:n="write"}=c;if(e.endsWith(".ipynb")&&ye.existsSync(e)){let o=await Y.readFile(e,"utf-8"),r=JSON.parse(o);if(r.cells.length>0&&r.cells[0].id){let a=r.cells.findIndex(l=>l.id===r.cells[0].id);if(a!==-1)return r.cells[a].source=t,await Y.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}ye.existsSync(e)&&n!=="append"&&await this.validateFileNotModified(e);let s=Fe.dirname(e);return await Y.mkdir(s,{recursive:!0}),n==="append"?await Y.appendFile(e,t):await Y.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:n}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await Y.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let n of e){if(!c.include_hidden&&n.name.startsWith("."))continue;let s=await Y.stat(Fe.join(c.directory_path,n.name));t.push({name:n.name,type:n.isDirectory()?"directory":"file",size:s.size,modified:s.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=je.parseSessionMode(c.session),t=ze(c.command),n={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},s=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,n);return{success:s.isSuccess,result:{command:c.command,stdout:s.output,stderr:"",exit_code:s.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await Ln({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:n=!1}=c;if(n){this.backgroundProcessCounter++;let r=`bg-${this.backgroundProcessCounter}`,a=Wn("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),l={process:a,command:e,startTime:new Date,stdout:"",stderr:""};a.stdout.on("data",p=>{let f=p.toString();if(f){let y=this.backgroundProcesses.get(r);y&&(y.stdout+=f,this.backgroundProcesses.set(r,y))}}),a.stderr.on("data",p=>{let f=p.toString();if(f){let y=this.backgroundProcesses.get(r);y&&(y.stderr+=f,this.backgroundProcesses.set(r,y))}}),a.on("close",p=>{let f=this.backgroundProcesses.get(r);f&&(f.exitCode=p||0,this.backgroundProcesses.set(r,f))}),this.backgroundProcesses.set(r,l);let u=`Command started in background with ID: ${r}
|
|
230
|
+
7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content shows matching lines, files_with_matches shows file paths (default), count shows match counts",default:"files_with_matches"},case_insensitive:{type:"boolean",description:"Case insensitive search",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let n={};try{n=JSON.parse(c.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${t}': ${o}`)}let{ToolDisplay:s}=await Promise.resolve().then(()=>(ge(),Nn));s.start(t,n.description,n.command||n.file_path);try{let o=this.tools.get(t);if(!o)throw new Error(`Tool '${t}' not found`);if(!o.enabled)throw new Error(`Tool '${t}' is disabled`);let i=await o.handler(n),a=Date.now()-e,l=this.handleLargeResponse(i,t);return this.executionHistory.push({toolName:t,args:n,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),s.result({toolName:t,command:n.command,filePath:n.file_path,description:n.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(o){let i=Date.now()-e,a={success:!1,error:o.message};return this.emit("tool_execution_error",{toolName:t,error:o,executionTime:i}),s.error(t,o.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(c){return c.success?c.result?typeof c.result=="string"?c.result:typeof c.result=="object"&&"stdout"in c.result?c.result.stdout||c.result.stderr||"":typeof c.result=="object"&&"content"in c.result?c.result.content||"":JSON.stringify(c.result,null,2):"":c.error||"Unknown error"}async captureFrontendToolResult(c,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(we(),Me)),n=t.getInstance(),s=this.extractOutputForDisplay(e);n.captureFrontendToolResult(c,s,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,n=(await jn.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,s=[];if(n.AbstractText&&s.push({title:n.Heading||"Instant Answer",content:n.AbstractText,url:n.AbstractURL||"",type:"instant_answer"}),n.RelatedTopics&&n.RelatedTopics.length>0)for(let o of n.RelatedTopics.slice(0,c.num_results||5))o.Text&&s.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:s,total_results:s.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await Y.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:n="write"}=c;if(e.endsWith(".ipynb")&&ye.existsSync(e)){let o=await Y.readFile(e,"utf-8"),i=JSON.parse(o);if(i.cells.length>0&&i.cells[0].id){let a=i.cells.findIndex(l=>l.id===i.cells[0].id);if(a!==-1)return i.cells[a].source=t,await Y.writeFile(e,JSON.stringify(i,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}ye.existsSync(e)&&n!=="append"&&await this.validateFileNotModified(e);let s=_e.dirname(e);return await Y.mkdir(s,{recursive:!0}),n==="append"?await Y.appendFile(e,t):await Y.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:n}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await Y.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let n of e){if(!c.include_hidden&&n.name.startsWith("."))continue;let s=await Y.stat(_e.join(c.directory_path,n.name));t.push({name:n.name,type:n.isDirectory()?"directory":"file",size:s.size,modified:s.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=Je.parseSessionMode(c.session),t=Ve(c.command),n={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},s=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,n);return{success:s.isSuccess,result:{command:c.command,stdout:s.output,stderr:"",exit_code:s.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await jn({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:n=!1}=c;if(n){this.backgroundProcessCounter++;let i=`bg-${this.backgroundProcessCounter}`,a=Vn("/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(i);v&&(v.stdout+=f,this.backgroundProcesses.set(i,v))}}),a.stderr.on("data",p=>{let f=p.toString();if(f){let v=this.backgroundProcesses.get(i);v&&(v.stderr+=f,this.backgroundProcesses.set(i,v))}}),a.on("close",p=>{let f=this.backgroundProcesses.get(i);f&&(f.exitCode=p||0,this.backgroundProcesses.set(i,f))}),this.backgroundProcesses.set(i,l);let u=`Command started in background with ID: ${i}
|
|
207
231
|
PID: ${a.pid}
|
|
208
232
|
Command: ${e}
|
|
209
233
|
|
|
210
234
|
Note: The process will continue running in the background.
|
|
211
|
-
Output will be collected automatically.`;return{success:!0,result:{process_id:
|
|
212
|
-
`).filter(
|
|
213
|
-
|
|
214
|
-
`;return n+=`📁 TEMP FILE PATH: ${e}
|
|
215
|
-
`,n+=`🔍 Use read_file, grep, cat, or other tools to access the full content.
|
|
216
|
-
|
|
217
|
-
`,n+=`📝 PREVIEW (first 10,000 characters):
|
|
218
|
-
`,n+=`${"─".repeat(50)}
|
|
219
|
-
`,n+=t,c.length>1e4&&(n+=`
|
|
220
|
-
${"─".repeat(50)}`,n+=`
|
|
221
|
-
... (${c.length-1e4} more characters available in temp file)`),n+=`
|
|
235
|
+
Output will be collected automatically.`;return{success:!0,result:{process_id:i,pid:a.pid,message:u}}}let s=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:Ve(e),o=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",s);return{success:o.isSuccess,result:{command:e,stdout:o.output,stderr:"",exit_code:o.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(c){try{let{file_path:e,old_string:t,new_string:n,replace_all:s=!1}=c;if(t===n)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&ye.existsSync(e)){let a=await Y.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let p=l.cells[u],f=Array.isArray(p.source)?p.source.join(""):p.source;if(f.includes(t)){let v=s?f.replaceAll(t,n):f.replace(t,n);return l.cells[u].source=v,await Y.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:s?f.split(t).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(e);let o=await Y.readFile(e,"utf-8");if(!o.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let i=s?o.replaceAll(t,n):o.replace(t,n);if(i===o)throw new Error("Edit failed: File content unchanged after replacement");return await Y.writeFile(e,i,"utf-8"),this.cacheFileState(e,i),{success:!0,result:{file_path:e,replacements:s?o.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(c){try{let{pattern:e,path:t=process.cwd(),glob:n,output_mode:s="files_with_matches",case_insensitive:o=!1}=c,i=[];return o&&i.push("-i"),s==="files_with_matches"?i.push("-l"):s==="count"&&i.push("-c"),n&&i.push("--glob",n),i.push(e,t),new Promise(a=>{let l=Vn("rg",i,{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(`
|
|
236
|
+
`).filter(y=>y),S=v.length;a({success:!0,result:{pattern:e,num_files:S,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,s=(a=>{let l=a;return l=l.replace(/[.+^${}()|[\]\\]/g,"\\$&"),l=l.replace(/\*\*/g,"<DOUBLESTAR>"),l=l.replace(/\*/g,"[^/]*"),l=l.replace(/<DOUBLESTAR>/g,".*"),l=l.replace(/\?/g,"."),new RegExp(`^${l}$`)})(e),o=[],i=async a=>{try{let l=await Y.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let p=_e.join(a,u.name),f=_e.relative(t,p);u.isDirectory()?await i(p):(s.test(f)||s.test(u.name))&&o.push(p)}}catch{}};return await i(t),{success:!0,result:{pattern:e,num_files:o.length,files:o}}}catch(e){return{success:!1,error:`Glob failed: ${e.message}`}}}async editNotebook(c){try{let{notebook_path:e,cell_id:t,new_source:n,cell_type:s="code",edit_mode:o="replace"}=c;if(!ye.existsSync(e))throw new Error(`Notebook file does not exist: ${e}`);if(!e.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let i=await Y.readFile(e,"utf-8"),a=JSON.parse(i);switch(o){case"replace":{if(!t)throw new Error("cell_id is required for replace mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells[l].source=n;break}case"insert":{if(!s)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:s,source:n,metadata:{},execution_count:s==="code"?null:void 0,outputs:s==="code"?[]:void 0};if(t){let u=a.cells.findIndex(p=>p.id===t);a.cells.splice(u+1,0,l)}else a.cells.unshift(l);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${o}`)}return await Y.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:o,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=ye.statSync(c);this.fileStateCache.set(c,{content:e,modificationDate:t.mtime,filePath:c})}catch{}}async validateFileNotModified(c){let e=this.fileStateCache.get(c);if(!e){if(ye.existsSync(c)){let n=await Y.readFile(c,"utf-8");this.cacheFileState(c,n)}return}if(ye.statSync(c).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let c=[];for(let[e,t]of this.tools.entries())t.enabled&&c.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return c}getToolsByCategory(c){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===c)}enableTool(c){let e=this.tools.get(c);return e?(e.enabled=!0,!0):!1}disableTool(c){let e=this.tools.get(c);return e?(e.enabled=!1,!0):!1}getExecutionHistory(c=10){return this.executionHistory.slice(-c)}getExecutionStats(){let c=this.executionHistory.length,e=this.executionHistory.filter(i=>i.result.success).length,t=c-e,n=c>0?this.executionHistory.reduce((i,a)=>i+a.executionTime,0)/c:0,s=new Map;this.executionHistory.forEach(i=>{s.set(i.toolName,(s.get(i.toolName)||0)+1)});let o=s.size>0?Array.from(s.entries()).reduce((i,a)=>a[1]>i[1]?a:i)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(n),mostUsed:o}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){}handleLargeResponse(c,e){if(!c.success||!c.result)return c;let t=typeof c.result=="string"?c.result:JSON.stringify(c.result);if(this.tokenCounter.exceedsResponseLimit(t)){let n=this.createTempFile(t,e);return n?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(t,n)}:{success:!0,result:this.tokenCounter.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=To.tmpdir(),n=_e.join(t,"orion_tool_responses");ye.existsSync(n)||ye.mkdirSync(n,{recursive:!0});let s=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),i=`${e}_${s}_${o}.txt`,a=_e.join(n,i);return ye.writeFileSync(a,c,"utf8"),a}catch{return null}}stopAllRunningTools(){}}});var bt,Kn=R(()=>{"use strict";H();Qt();bt=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let o=n.command;if(o==null)throw new Error("Missing command argument");if(typeof o!="string")throw new Error(`Command must be a string. Received: ${typeof o}`);if(o.trim().length===0)throw new Error("Command cannot be empty");let i=n.session;if(i==null)i="new";else{if(typeof i!="string")throw new Error(`Session must be a string. Received: ${typeof i}`);i=i.toLowerCase()}if(i!=="new"&&i!=="existing")throw new Error(`Invalid session mode '${i}' - must be 'new' or 'existing'`);let a;if(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let y=Number(n.timeout);if(Number.isNaN(y))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=y}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let l=n.description;l!=null&&typeof l!="string"&&r.debug(`[RunCommandTool] Invalid description type: ${typeof l}, ignoring`);let u=n.run_in_background;if(u!=null){if(typeof u!="boolean")throw new Error(`run_in_background must be a boolean. Received: ${typeof u}`);u===!0&&r.debug("[RunCommandTool] run_in_background=true requested but not yet implemented, running in foreground")}let p=Hn(o);if(p.isPrivileged)return r.debug(`[RunCommandTool] Blocked privileged command: ${p.reason}`),[{type:"text",text:`Error: ${Gn(o,p.reason||"Privileged command detected")}`}];let f=Xn(o);if(f.isInteractive)return r.debug(`[RunCommandTool] Blocked interactive command: ${f.reason}`),[{type:"text",text:`Error: ${zn(o,f.reason||"Interactive command detected")}`}];let v=a||12e4,S=Kt();r.debug(`[RunCommandTool] Executing command on platform: ${S}`),r.debug(`[RunCommandTool] Command: ${o.substring(0,50)}${o.length>50?"...":""}`),l&&r.debug(`[RunCommandTool] Description: ${l}`),r.debug(`[RunCommandTool] Session: ${i}, Timeout: ${v}ms, Background: ${u||!1}`);try{let y=(await Promise.resolve().then(()=>(vt(),Jt))).ToolCallingService.getInstance(),d={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:i,timeout:v})}},h=await y.executeTool(d),m="";if(h.success){let k=(h.result?.stdout||"").trim(),x=h.result?.exitCode??0;if(m=`Command: ${o}
|
|
237
|
+
`,m+=`Exit Code: ${x}
|
|
222
238
|
|
|
223
|
-
|
|
239
|
+
`,k.length>0){let E=k.split(`
|
|
240
|
+
`),w=E.slice(0,15);m+=w.join(`
|
|
241
|
+
`),E.length>15&&(m+=`
|
|
224
242
|
|
|
225
|
-
... (
|
|
226
|
-
`,m+=`Exit Code: ${
|
|
227
|
-
|
|
228
|
-
`,C.length>0){let k=C.split(`
|
|
229
|
-
`),v=k.slice(0,15);m+=v.join(`
|
|
230
|
-
`),k.length>15&&(m+=`
|
|
231
|
-
|
|
232
|
-
... (showing first 15 of ${k.length} lines)`)}else m+="(no output)";return[{type:"text",text:m}]}else{let C=g.error||"Unknown error",S=g.result?.exitCode??1;return m=`Command: ${o}
|
|
233
|
-
`,m+=`Exit Code: ${S}
|
|
243
|
+
... (showing first 15 of ${E.length} lines)`)}else m+="(no output)";return[{type:"text",text:m}]}else{let k=h.error||"Unknown error",x=h.result?.exitCode??1;return m=`Command: ${o}
|
|
244
|
+
`,m+=`Exit Code: ${x}
|
|
234
245
|
|
|
235
246
|
`,m+=`Error:
|
|
236
|
-
${
|
|
237
|
-
Error: ${
|
|
247
|
+
${k}`,[{type:"text",text:m}]}}catch(y){return r.debug(`[RunCommandTool] Failed to execute bash command: ${y.message}`),[{type:"text",text:`Command: ${o}
|
|
248
|
+
Error: ${y.message}`}]}}ensureMeaningfulOutput(e,t,n){let s=(e||"").trim();return s.length===0?n?`✅ Command '${t}' executed successfully.
|
|
238
249
|
|
|
239
250
|
ℹ️ No output was produced, which may be expected for this operation. This typically means:
|
|
240
251
|
• The command completed without errors
|
|
@@ -251,15 +262,15 @@ If you expected output, the command may need different parameters or the operati
|
|
|
251
262
|
Consider:
|
|
252
263
|
• Checking the command syntax and parameters
|
|
253
264
|
• Verifying file permissions and paths
|
|
254
|
-
• Running the command with verbose flags for more details`:s}}});var
|
|
265
|
+
• Running the command with verbose flags for more details`:s}}});var yt,Qn=R(()=>{"use strict";H();yt=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let o=n.pattern,i=n.output_mode||"files_with_matches",a=n.path||process.cwd(),l=n.glob,u=n.type,p=n["-i"]===!0,f=n["-n"]===!0,v=n["-A"],S=n["-B"],y=n["-C"],d=n.multiline===!0,h=n.head_limit;if(!o)throw new Error("Missing pattern argument");if(o.trim().length===0)throw new Error("Pattern cannot be empty");r.debug(`[GrepTool] Grep search: pattern="${o}", path="${a}", output_mode="${i}"`);try{let{exec:m}=await import("child_process"),{promisify:k}=await import("util"),x=k(m),E="rg",w=!0;try{await x("which rg")}catch{r.debug("[GrepTool] ripgrep not found, falling back to grep"),E="grep -r",w=!1}if(w){switch(p&&(E+=" -i"),f&&(E+=" -n"),i){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break;case"content":default:break}y!==void 0?E+=` -C ${y}`:(v!==void 0&&(E+=` -A ${v}`),S!==void 0&&(E+=` -B ${S}`)),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"),i){case"files_with_matches":E+=" -l";break;case"count":E+=" -c";break}y!==void 0?E+=` -C ${y}`:(v!==void 0&&(E+=` -A ${v}`),S!==void 0&&(E+=` -B ${S}`)),E+=` "${o.replace(/"/g,'\\"')}"`,l&&(E+=` --include="${l}"`),E+=` "${a}"`}h!==void 0&&h>0&&(E+=` | head -n ${h}`),r.debug(`[GrepTool] Executing: ${E}`);let{stdout:T,stderr:N}=await x(E,{maxBuffer:10*1024*1024});if(!T&&!N)return[{type:"text",text:"No matches found"}];let B=T||N;if(i==="content"&&B){let P=`
|
|
255
266
|
|
|
256
|
-
[Found ${
|
|
257
|
-
`).length} matching line(s)]`;return[{type:"text",text:
|
|
258
|
-
`);return[{type:"text",text:`Found ${
|
|
259
|
-
${
|
|
260
|
-
`)}`}]}catch(a){return
|
|
267
|
+
[Found ${B.trim().split(`
|
|
268
|
+
`).length} matching line(s)]`;return[{type:"text",text:B+P}]}return[{type:"text",text:B}]}catch(m){return m.code===1?[{type:"text",text:"No matches found"}]:(r.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 wt,Jn=R(()=>{"use strict";H();wt=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let o=n.pattern,i=n.path||process.cwd();if(!o)throw new Error("Missing pattern argument");r.debug(`[GlobTool] Glob search: pattern="${o}", path="${i}"`);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 "${i}\\${p}"`:`find "${i}" -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 S=v.trim().split(`
|
|
269
|
+
`);return[{type:"text",text:`Found ${S.length} file(s):
|
|
270
|
+
${S.join(`
|
|
271
|
+
`)}`}]}catch(a){return r.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Tt,Yn=R(()=>{"use strict";H();Tt=class{toolNames=["open_url"];async execute(e,t,n,s){let o=n.url;if(!o)throw new Error("Missing url argument");r.debug(`[OpenUrlTool] Opening URL: ${o}`),s.activeWebViewURLs.includes(o)||(s.activeWebViewURLs.push(o),r.debug(`[OpenUrlTool] Added to active URLs: ${o}`));try{let{exec:i}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return i(`${a} "${o}"`,l=>{l?r.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):r.debug(`[OpenUrlTool] URL opened in default browser: ${o}`)}),[{type:"text",text:`✅ URL opened in default browser: ${o}`}]}catch(i){return r.debug(`[OpenUrlTool] Failed to open URL: ${i.message}`),[{type:"text",text:`❌ Failed to open URL: ${i.message}`}]}}}});import{exec as So,execSync as Ga}from"child_process";import{promisify as ko}from"util";function Le(){return process.platform==="win32"}function St(){return process.platform==="darwin"}function kt(){return process.platform==="linux"}function Yt(){return Le()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var za,Zn=R(()=>{"use strict";za=ko(So)});import*as L from"fs";import*as Q from"path";import*as W from"os";import{exec as es}from"child_process";import{promisify as xo}from"util";var xt,Zt,oe,ts=R(()=>{"use strict";Zn();xt=xo(es),Zt=class c{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return c.instance||(c.instance=new c),c.instance}get orionDirectory(){return Q.join(W.homedir(),".orion")}getKnowledgeFilePath(){return Q.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!L.existsSync(this.orionDirectory))try{L.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Le()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{es(`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 L.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return L.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),L.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
|
|
261
272
|
|
|
262
|
-
`+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return
|
|
273
|
+
`+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return L.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
|
|
263
274
|
|
|
264
275
|
`;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
|
|
265
276
|
|
|
@@ -273,7 +284,7 @@ ${T.join(`
|
|
|
273
284
|
`,e+=`- **Username**: ${W.userInfo().username}
|
|
274
285
|
`,e+=`- **Home Directory**: ${W.homedir()}
|
|
275
286
|
|
|
276
|
-
`;let t=
|
|
287
|
+
`;let t=Yt();e+=`## Shell Environment
|
|
277
288
|
`,e+=`- **Default Shell**: ${t}
|
|
278
289
|
`,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
|
|
279
290
|
`),e+=`
|
|
@@ -281,7 +292,7 @@ ${T.join(`
|
|
|
281
292
|
`,e+=s.join(`
|
|
282
293
|
`),e+=`
|
|
283
294
|
|
|
284
|
-
`);let o=[];if(
|
|
295
|
+
`);let o=[];if(St()){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(L.existsSync(p)){let f=Q.basename(p,".app");o.push(`- ${f}`)}}else if(Le()){let u=["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe","C:\\Program Files\\Microsoft VS Code\\Code.exe","C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe",Q.join(process.env.LOCALAPPDATA||"","Programs\\Microsoft VS Code\\Code.exe"),"C:\\Program Files\\Sublime Text\\sublime_text.exe","C:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition","C:\\Program Files\\JetBrains\\PyCharm Community Edition","C:\\Program Files\\Android\\Android Studio","C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe","C:\\Program Files\\Postman\\Postman.exe",Q.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let p of u)if(L.existsSync(p)){let f=Q.basename(p).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");o.push(`- ${f}`)}}else if(kt()){let u=[{path:"/snap/bin/code",name:"VS Code (snap)"},{path:"/snap/bin/sublime-text",name:"Sublime Text (snap)"},{path:"/snap/bin/postman",name:"Postman (snap)"},{path:"/snap/bin/intellij-idea-community",name:"IntelliJ IDEA (snap)"},{path:"/snap/bin/pycharm-community",name:"PyCharm (snap)"},{path:"/usr/bin/code",name:"VS Code"},{path:"/usr/share/code/code",name:"VS Code"},{path:"/opt/visual-studio-code/code",name:"VS Code"},{path:"/usr/bin/sublime_text",name:"Sublime Text"},{path:"/opt/sublime_text/sublime_text",name:"Sublime Text"},{path:"/usr/bin/docker",name:"Docker"},{path:"/usr/bin/vim",name:"Vim"},{path:"/usr/bin/nvim",name:"Neovim"},{path:"/usr/bin/emacs",name:"Emacs"},{path:"/usr/bin/nano",name:"Nano"},{path:Q.join(W.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let v of u)L.existsSync(v.path)&&o.push(`- ${v.name}`);let p=["/usr/share/applications",Q.join(W.homedir(),".local/share/applications")],f=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let v of p)if(L.existsSync(v))try{let S=L.readdirSync(v);for(let y of S){let d=y.toLowerCase();for(let h of f)d.includes(h)&&!o.some(m=>m.toLowerCase().includes(h))&&o.push(`- ${y.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
|
|
285
296
|
`,e+=o.join(`
|
|
286
297
|
`),e+=`
|
|
287
298
|
|
|
@@ -290,23 +301,23 @@ ${T.join(`
|
|
|
290
301
|
`,e+=`- **Desktop**: ${Q.join(W.homedir(),"Desktop")}
|
|
291
302
|
`,e+=`- **Documents**: ${Q.join(W.homedir(),"Documents")}
|
|
292
303
|
`,e+=`- **Downloads**: ${Q.join(W.homedir(),"Downloads")}
|
|
293
|
-
`,
|
|
304
|
+
`,St()?(e+=`- **Applications**: /Applications
|
|
294
305
|
`,e+=`- **usr/local/bin**: /usr/local/bin
|
|
295
|
-
`):
|
|
306
|
+
`):Le()?(e+=`- **Program Files**: C:\\Program Files
|
|
296
307
|
`,e+=`- **Program Files (x86)**: C:\\Program Files (x86)
|
|
297
308
|
`,e+=`- **AppData**: ${Q.join(W.homedir(),"AppData")}
|
|
298
309
|
`,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||Q.join(W.homedir(),"AppData","Local")}
|
|
299
|
-
`):
|
|
310
|
+
`):kt()&&(e+=`- **/usr/bin**: /usr/bin
|
|
300
311
|
`,e+=`- **/usr/local/bin**: /usr/local/bin
|
|
301
312
|
`,e+=`- **/opt**: /opt
|
|
302
313
|
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||Q.join(W.homedir(),".config")}
|
|
303
314
|
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||Q.join(W.homedir(),".local/share")}
|
|
304
|
-
`,
|
|
305
|
-
`),
|
|
315
|
+
`,L.existsSync("/snap")&&(e+=`- **Snap**: /snap
|
|
316
|
+
`),L.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
|
|
306
317
|
`)),e+=`
|
|
307
318
|
`,e+=`## Network
|
|
308
319
|
`,e+=`- **Hostname**: ${W.hostname()}
|
|
309
|
-
`;let
|
|
320
|
+
`;let i=W.networkInterfaces(),a=Object.values(i).flat().find(u=>u&&!u.internal&&u.family==="IPv4");a&&(e+=`- **IP Address**: ${a.address}
|
|
310
321
|
`),e+=`
|
|
311
322
|
`;let l=await this.detectEnvironment();return l&&(e+=`## Environment
|
|
312
323
|
`,e+=l,e+=`
|
|
@@ -315,64 +326,41 @@ ${T.join(`
|
|
|
315
326
|
`,e+=`- **File Downloads**: Always follow redirects to ensure proper file access and downloads.
|
|
316
327
|
|
|
317
328
|
`,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let s=(this.readDeviceKnowledge()||"").split(`
|
|
318
|
-
`),o=[],
|
|
329
|
+
`),o=[],i=!1,a=!1;for(let u of s)u.startsWith(`## ${e}`)?(i=!0,a=!0,o.push(u),o.push(t)):u.startsWith("## ")&&i?(i=!1,o.push(u)):i||o.push(u);a||(o.push(""),o.push(`## ${e}`),o.push(t));let l=o.join(`
|
|
319
330
|
`);return this.writeDeviceKnowledge(l)}addNote(e,t,n="Notes"){let s=new Date().toLocaleString(),o=`### ${e} (${s})
|
|
320
|
-
${t}`,
|
|
321
|
-
`),l=[],u=!1,p=!1;for(let
|
|
322
|
-
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(n,o)}deleteDeviceKnowledge(){try{return
|
|
323
|
-
`):null}async getCommandVersion(e){try{let t=
|
|
324
|
-
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}},oe=
|
|
331
|
+
${t}`,i=this.readDeviceKnowledge()||"";if(i.includes(`## ${n}`)){let a=i.split(`
|
|
332
|
+
`),l=[],u=!1,p=!1;for(let v of a)v.startsWith(`## ${n}`)?(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(`
|
|
333
|
+
`);return this.writeDeviceKnowledge(f)}else return this.updateKnowledgeSection(n,o)}deleteDeviceKnowledge(){try{return L.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return L.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=L.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(kt()){try{let{stdout:n}=await xt("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),s=n.trim();s&&s!=="none"&&e.push(`- **Virtualization**: ${s}`)}catch{}if(L.existsSync("/proc/cpuinfo"))try{L.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(s=>s.includes("Virtualization"))||e.push("- **Virtualization**: VM detected (hypervisor flag)"))}catch{}let t=["/sys/class/dmi/id/product_name","/sys/class/dmi/id/sys_vendor","/sys/class/dmi/id/board_vendor"];for(let n of t)if(L.existsSync(n))try{let s=L.readFileSync(n,"utf8").trim().toLowerCase();if(s.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(s.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(s.includes("kvm")||s.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(s.includes("hyper-v")||s.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(s.includes("xen")){e.push("- **VM Type**: Xen");break}else if(s.includes("amazon")||s.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(s.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(s.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(L.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),L.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),L.existsSync("/proc/version"))try{let n=L.readFileSync("/proc/version","utf8");(n.toLowerCase().includes("microsoft")||n.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(L.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),L.existsSync("/etc/os-release"))try{let s=L.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);s&&e.push(`- **Distribution**: ${s[1]}`)}catch{}}else if(St())try{let{stdout:t}=await xt('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(Le())try{let{stdout:t}=await xt('systeminfo | findstr /i "System Model"',{timeout:5e3}),n=t.toLowerCase();(n.includes("virtual")||n.includes("vmware")||n.includes("virtualbox"))&&e.push(`- **Environment**: ${t.split(":")[1]?.trim()||"Virtual Machine"}`)}catch{}(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)&&e.push("- **Access**: SSH Session"),process.env.TMUX&&e.push("- **Terminal Multiplexer**: tmux"),process.env.STY&&e.push("- **Terminal Multiplexer**: screen")}catch{}return e.length>0?e.join(`
|
|
334
|
+
`):null}async getCommandVersion(e){try{let t=Yt(),{stdout:n,stderr:s}=await xt(e,{timeout:5e3,shell:t,windowsHide:!0});return(n+s).trim().split(`
|
|
335
|
+
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}},oe=Zt.shared()});var Ct,ns=R(()=>{"use strict";H();ge();ts();Ct=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let o=n.action,i=Date.now();r.debug(`[ManageDeviceKnowledgeTool] Executing action: ${o}`),O.start("ManageDeviceKnowledge",o);try{let a,l=!0;switch(o){case"read":{let p=oe.readDeviceKnowledge();p?a=p:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await oe.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${oe.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let p=n.content;p?oe.writeDeviceKnowledge(p)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",l=!1):(a='Error: Missing "content" argument for write action.',l=!1);break}case"append":{let p=n.content;p?oe.appendDeviceKnowledge(p)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",l=!1):(a='Error: Missing "content" argument for append action.',l=!1);break}case"update_section":{let p=n.section,f=n.content;!p||!f?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):oe.updateKnowledgeSection(p,f)?a=`Section "${p}" updated successfully.`:(a=`Failed to update section "${p}".`,l=!1);break}case"add_note":{let p=n.title,f=n.content,v=n.category||"Notes";!p||!f?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):oe.addNote(p,f,v)?a=`Note "${p}" added to ${v} successfully.`:(a=`Failed to add note "${p}".`,l=!1);break}case"delete":{oe.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=oe.getKnowledgeFilePath();break}case"exists":{a=oe.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${oe.getKnowledgeFileSize()} bytes`;break}case"export":{let p=n.destination;p?oe.exportDeviceKnowledge(p)?a=`Device knowledge exported to: ${p}`:(a=`Failed to export device knowledge to: ${p}`,l=!1):(a='Error: Missing "destination" argument for export action.',l=!1);break}case"import":{let p=n.source;p?oe.importDeviceKnowledge(p)?a=`Device knowledge imported from: ${p}`:(a=`Failed to import device knowledge from: ${p}`,l=!1):(a='Error: Missing "source" argument for import action.',l=!1);break}default:a=`Unknown action: ${o}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-i;return O.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){r.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-i;return O.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Et,ss=R(()=>{"use strict";H();Et=class{toolNames=["operator_status"];async execute(e,t,n,s){let o=n.taskId,i=n.status,a=n.message;return r.debug(`[OperatorStatusTool] Operator status - Task ${o}: ${i} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var It,os=R(()=>{"use strict";H();It=class{toolNames=["provide_input"];async execute(e,t,n,s){let o=n.input;if(!o)throw new Error("Missing input argument");r.debug(`[ProvideInputTool] Delegating provide_input to backend: ${o.substring(0,20)}...`);try{let i=(await Promise.resolve().then(()=>(vt(),Jt))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:o})}},l=await i.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(i){return r.debug(`[ProvideInputTool] Failed to delegate provide_input: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});import{exec as Co}from"child_process";import{promisify as Eo}from"util";import*as Pt from"fs/promises";import*as is from"path";import*as rs from"os";var Io,Ue,en=R(()=>{"use strict";H();Io=Eo(Co),Ue=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=is.join(rs.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;
|
|
325
336
|
[System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
|
|
326
337
|
Start-Sleep -Milliseconds 100;
|
|
327
338
|
$img = [System.Windows.Forms.Clipboard]::GetImage();
|
|
328
|
-
$img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return
|
|
339
|
+
$img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return r.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await Io(t);let n=await Pt.readFile(e),s=n.toString("base64");return await Pt.unlink(e).catch(()=>{}),r.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return r.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
|
|
329
340
|
⚠️ 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
|
|
330
341
|
`)):process.platform==="darwin"&&(console.log(`
|
|
331
342
|
⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
|
|
332
|
-
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var kt,Zn=R(()=>{"use strict";B();Qt();kt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await _e.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return i.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(o){return i.error(`[TakeScreenshotTool] Failed to capture screenshot: ${o.message}`),[{type:"text",text:`Failed to capture screenshot: ${o.message}`}]}}}});function es(c){c.register(new it),c.register(new at),c.register(new ct),c.register(new lt),c.register(new ut),c.register(new dt),c.register(new pt),c.register(new gt),c.register(new ht),c.register(new ft),c.register(new vt),c.register(new Tt),c.register(new St),c.register(new Ct),c.register(new kt)}var ts=R(()=>{"use strict";En();In();Pn();Dn();An();Nn();Rn();Bn();Hn();qn();Gn();Vn();Kn();Qn();Zn()});var Et,ns=R(()=>{"use strict";Et=class{constructor(e,t,n,s,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=o}}});var os={};ae(os,{FrontendWebSocketService:()=>K});import{EventEmitter as go}from"events";import{io as ho}from"socket.io-client";import ss from"os";import fo from"path";var K,Ke=R(()=>{"use strict";B();we();se();Ne();Cn();ts();ns();K=class c extends go{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=3e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=1e4;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;maxResponseCharacters=87500;wsConnectionStartTime=null;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new nt,es(this.toolRegistry),i.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?i.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):i.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{i.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return i.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return i.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(i.debug("[FRONTEND WS] connectForConversation called"),i.debug(`[FRONTEND WS] New sessionId: ${t}`),i.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),i.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t&&(i.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1)),this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)i.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return i.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(i.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){i.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],i.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){i.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(i.debug("[FRONTEND WS] connect() called"),this.socket?.connected){i.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(i.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),i.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;i.debug(`[FRONTEND WS] Connecting to ${t}`),i.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),i.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),i.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=ho(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){i.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){i.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,i.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(i.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),i.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(s),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(s),this.connectionPromise=null,n(o)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{i.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{i.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{i.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,i.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{i.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{i.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{i.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{i.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{i.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{i.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{i.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{i.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{}),this.socket.on("checkpoint_request",e=>{this.handleCheckpointRequest(e)}),this.socket.on("messages_saved",e=>{this.handleMessagesSaved(e)}),this.socket.on("auto_prompt",e=>{this.handleAutoPrompt(e)}),this.socket.on("error",e=>{console.error("[FRONTEND WS] Socket.IO error:",e)}))}handleConnect(){i.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();i.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else i.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.flushPendingToolResults(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){i.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||i.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){i.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(i.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:i.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",n=e.reason||"backend_stop_request";i.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${n}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){i.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,o=t.iteration;if(!n||!s||o===void 0){i.warn("[FRONTEND WS] Invalid checkpoint request format");return}i.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${o}`);let r=pe.getInstance(),a=r.getQueuedMessages(),l=a.map(p=>({content:p.content,timestamp:Math.floor(p.timestamp.getTime())})),u=l.length>0;i.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:u,feedback:l}),u&&(i.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){i.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){i.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}i.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),i.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(i.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n,e.data?.arguments)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){i.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();i.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t,n){this.activeToolCount++;let s=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),i.debug("[FRONTEND WS] === EXECUTING TOOL ==="),i.debug(`[FRONTEND WS] Tool name: ${e.name}`),i.debug(`[FRONTEND WS] Tool ID: ${e.id}`),i.debug(`[FRONTEND WS] Tool call ID: ${t}`);let o=new Et(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,o);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success}),await this.handleLargeResponse(e.id,t,e.name,r,r.success,n)}catch(r){i.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-s)/1e3).toFixed(2);i.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(i.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),i.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}i.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(n){i.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;i.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),i.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){i.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,n,s,o){let r;if(s&&typeof s=="object"&&"content"in s&&Array.isArray(s.content))r=s.content;else{let a;typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),r=this.createContentBlocks(a,o,n)}if(o){let a=this.createDeviceKnowledgeReminderBlock();r.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:r,success:!0,error:null})}sendToolError(e,t,n,s){let o=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:o,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
|
|
343
|
+
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var Dt,as=R(()=>{"use strict";H();en();Dt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){r.debug("[TakeScreenshotTool] Capturing screenshot...");try{let i=await Ue.getInstance().captureScreen();if(!i)throw new Error("Failed to capture screenshot - no image data returned");return r.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:i}}]}catch(o){return r.error(`[TakeScreenshotTool] Failed to capture screenshot: ${o.message}`),[{type:"text",text:`Failed to capture screenshot: ${o.message}`}]}}}});function cs(c){c.register(new lt),c.register(new dt),c.register(new pt),c.register(new mt),c.register(new gt),c.register(new ht),c.register(new ft),c.register(new bt),c.register(new yt),c.register(new wt),c.register(new Tt),c.register(new Ct),c.register(new Et),c.register(new It),c.register(new Dt)}var ls=R(()=>{"use strict";$n();On();_n();Mn();Ln();Un();Wn();Kn();Qn();Jn();Yn();ns();ss();os();as()});var At,us=R(()=>{"use strict";At=class{constructor(e,t,n,s,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=o}}});var ps={};ae(ps,{FrontendWebSocketService:()=>K});import{EventEmitter as Po}from"events";import{io as Do}from"socket.io-client";import ds from"os";import Ao from"path";var K,Ze=R(()=>{"use strict";H();Te();se();Re();$e();An();ls();us();K=class c extends Po{static instance;socket=null;_connectionState="disconnected";connectionError=null;isConversationActive=!1;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;runningProcesses=new Map;activeWebViewURLs=[];reconnectAttempts=0;heartbeatTimer=null;baseHeartbeatInterval=3e4;lastHeartbeat=null;lastPongReceived=new Date;connectionQuality="excellent";aggressiveHeartbeatTimer=null;baseAggressiveHeartbeatInterval=1e4;toolProgressTimer=null;baseToolProgressInterval=15e3;activeToolExecutions=new Set;lastHeartbeatSent=null;toolExecutionQueue=[];activeToolCount=0;MAX_CONCURRENT_TOOLS=5;MAX_QUEUED_TOOLS=50;pendingToolResults=[];MAX_PENDING_RESULTS=100;tokenCounter=new le;wsConnectionStartTime=null;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=pe.getInstance(),this.authService=q.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new rt,cs(this.toolRegistry),r.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?r.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):r.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{r.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return r.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return r.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(r.debug("[FRONTEND WS] connectForConversation called"),r.debug(`[FRONTEND WS] New sessionId: ${t}`),r.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),r.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t&&(r.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1)),this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)r.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return r.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(r.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){r.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],r.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){r.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(r.debug("[FRONTEND WS] connect() called"),this.socket?.connected){r.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(r.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),r.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;r.debug(`[FRONTEND WS] Connecting to ${t}`),r.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),r.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),r.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Do(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){r.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){r.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,r.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&&(r.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),r.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(s),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(s),this.connectionPromise=null,n(o)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{r.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{r.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{r.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,r.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{r.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{r.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{r.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=>{r.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{r.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{r.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{r.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{r.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(){r.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.activeToolExecutions.size>0&&(r.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();r.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else r.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){r.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||r.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){r.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(r.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:r.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",n=e.reason||"backend_stop_request";r.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${n}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){r.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,o=t.iteration;if(!n||!s||o===void 0){r.warn("[FRONTEND WS] Invalid checkpoint request format");return}r.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${o}`);let i=me.getInstance(),a=i.getQueuedMessages(),l=a.map(p=>({content:p.content,timestamp:Math.floor(p.timestamp.getTime())})),u=l.length>0;r.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:u,feedback:l}),u&&(r.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),i.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){r.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){r.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}r.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),r.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(r.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n,e.data?.arguments)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){r.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();r.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t,n){this.activeToolCount++;let s=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),r.debug("[FRONTEND WS] === EXECUTING TOOL ==="),r.debug(`[FRONTEND WS] Tool name: ${e.name}`),r.debug(`[FRONTEND WS] Tool ID: ${e.id}`),r.debug(`[FRONTEND WS] Tool call ID: ${t}`);let o=new At(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let i=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,o);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:i.output,success:i.success}),await this.handleLargeResponse(e.id,t,e.name,i,i.success,n)}catch(i){r.error(`[FRONTEND WS] Tool execution failed: ${i.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:i.message,success:!1,error:i.message}),this.sendToolError(e.id,t,e.name,i)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let i=((Date.now()-s)/1e3).toFixed(2);r.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${i}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&&(r.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),r.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}r.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(n){r.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;r.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),r.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){r.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,n,s,o){let i;if(s&&typeof s=="object"&&"content"in s&&Array.isArray(s.content))i=s.content;else{let a;typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),i=this.createContentBlocks(a,o,n)}if(o){let a=this.createDeviceKnowledgeReminderBlock();i.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:i,success:!0,error:null})}sendToolError(e,t,n,s){let o=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:o,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
|
|
333
344
|
|
|
334
|
-
UPDATE DEVICE KNOWLEDGE: ${
|
|
345
|
+
UPDATE DEVICE KNOWLEDGE: ${Ao.join(ds.homedir(),".orion","device-knowledge.md")}
|
|
335
346
|
Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
|
|
336
347
|
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
|
|
337
348
|
|
|
338
|
-
No output was produced, which may be expected for this operation.`:s=`Command '${n}' failed but no error message was provided.`);try{let o=JSON.parse(s);if(Array.isArray(o)){let
|
|
339
|
-
|
|
340
|
-
FILE PATH: ${f}
|
|
341
|
-
|
|
342
|
-
This file is already on disk. Use Read tool with offset and limit parameters.
|
|
343
|
-
|
|
344
|
-
PREVIEW (first 5,000 characters):
|
|
345
|
-
${"─".repeat(50)}
|
|
346
|
-
`+y+(a.length>5e3?`
|
|
347
|
-
${"─".repeat(50)}
|
|
348
|
-
... (${a.length-5e3} more characters)`:"");await this.sendToolResult(e,t,n,T,o);return}let u=await this.createTempFile(a,n);if(!u){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.truncateOutput(a),o);return}let p=this.generatePreview(a,u);await this.sendToolResult(e,t,n,p,o)}else await this.sendToolResult(e,t,n,a,o)}async createTempFile(e,t){try{let n=await import("fs/promises"),s=await import("path"),o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=ss.homedir(),u=s.join(l,".orion","tool_outputs");await n.mkdir(u,{recursive:!0});let p=s.join(u,a);return await n.writeFile(p,e,"utf-8"),i.debug(`[FRONTEND WS] Created temp file: ${p}`),p}catch(n){return i.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}generatePreview(e,t){let n=e.substring(0,5e3),s=`Response too large (${e.length} characters > 87,500 limit), saved to temporary file.
|
|
349
|
-
|
|
350
|
-
`;return s+=`TEMP FILE PATH: ${t}
|
|
351
|
-
`,s+=`Use read_file, grep, cat, or other tools to access the full content.
|
|
352
|
-
|
|
353
|
-
`,s+=`PREVIEW (first 5,000 characters):
|
|
354
|
-
`,s+=`${"─".repeat(50)}
|
|
355
|
-
`,s+=n,e.length>5e3&&(s+=`
|
|
356
|
-
${"─".repeat(50)}`,s+=`
|
|
357
|
-
... (${e.length-5e3} more characters available in temp file)`),s+=`
|
|
358
|
-
|
|
359
|
-
To read full content: use tools like 'read_file' with path above`,s}truncateOutput(e){return e.length<=this.maxResponseCharacters?e:e.substring(0,this.maxResponseCharacters)+`
|
|
360
|
-
|
|
361
|
-
[Output truncated at ${this.maxResponseCharacters} characters]`}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),i.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},this.baseAggressiveHeartbeatInterval),i.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),i.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}sendAggressiveHeartbeat(){this.lastHeartbeatSent=new Date,this.socket?.connected&&(this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size}),i.debug(`[FRONTEND WS] Sent aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)),this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3;e<10?this.connectionQuality="excellent":e<30?this.connectionQuality="good":e<60?this.connectionQuality="fair":this.connectionQuality="poor"}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),i.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),i.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});i.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}terminateAllRunningProcesses(){i.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),i.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){i.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){i.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){i.debug("[FRONTEND WS] Not connected, cannot register session");return}i.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw i.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};i.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async captureFrontendToolResultForHistory(e,t,n,s){let o=t.map(r=>r.text||"").join(`
|
|
362
|
-
`);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(be(),$e)),a=r.getInstance(),l=s?`Error: ${s}`:o;a.captureFrontendToolResult(e,l,n),i.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){i.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}forceCleanup(){if(i.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.socket){try{this.socket.disconnect()}catch{}this.socket=null}i.debug("[FRONTEND WS] Force cleanup complete")}destroy(){i.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Ee,is=R(()=>{"use strict";Ee=class{static remove(e){if(!e||!e.includes("<context>"))return e;let t=e,n=/<context>[\s\S]*?<\/context>/gi;return t=t.replace(n,""),t=t.replace(/\n{3,}/g,`
|
|
349
|
+
No output was produced, which may be expected for this operation.`:s=`Command '${n}' failed but no error message was provided.`);try{let o=JSON.parse(s);if(Array.isArray(o)){let i=[];for(let a of o)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?i.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&i.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(i.length>0)return i}}catch{}return[{type:"text",text:s}]}async handleLargeResponse(e,t,n,s,o,i){let a;if(typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),n==="take_screenshot"||n==="take_current_screenshot"){await this.sendToolResult(e,t,n,s,o);return}if(this.tokenCounter.exceedsResponseLimit(a)){let l=this.tokenCounter.count(a);if(r.debug(`[FRONTEND WS] Response too large (${l} tokens), creating temp file`),n.toLowerCase()==="read"&&i?.file_path){let v=i.file_path,S=this.tokenCounter.formatLargeFileMessage(a,v);await this.sendToolResult(e,t,n,S,o);return}let p=await this.createTempFile(a,n);if(!p){r.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.tokenCounter.truncateOutput(a),o);return}let f=this.tokenCounter.formatLargeResponsePreview(a,p);await this.sendToolResult(e,t,n,f,o)}else await this.sendToolResult(e,t,n,a,o)}async createTempFile(e,t){try{let n=await import("fs/promises"),s=await import("path"),o=Math.floor(Date.now()/1e3),i=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${i}.txt`,l=ds.homedir(),u=s.join(l,".orion","tool_outputs");await n.mkdir(u,{recursive:!0});let p=s.join(u,a);return await n.writeFile(p,e,"utf-8"),r.debug(`[FRONTEND WS] Created temp file: ${p}`),p}catch(n){return r.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),r.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),r.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),r.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}),r.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),r.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),r.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()});r.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}terminateAllRunningProcesses(){r.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),r.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){r.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){r.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()}),r.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){r.debug("[FRONTEND WS] Not connected, cannot register session");return}r.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),r.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw r.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()}};r.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async captureFrontendToolResultForHistory(e,t,n,s){let o=t.map(i=>i.text||"").join(`
|
|
350
|
+
`);try{let{PersonalAgentService:i}=await Promise.resolve().then(()=>(we(),Me)),a=i.getInstance(),l=s?`Error: ${s}`:o;a.captureFrontendToolResult(e,l,n),r.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(i){r.debug(`[FRONTEND WS] Could not capture tool result: ${i}`)}}forceCleanup(){if(r.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}r.debug("[FRONTEND WS] Force cleanup complete")}destroy(){r.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Ie,ms=R(()=>{"use strict";Ie=class{static remove(e){if(!e||!e.includes("<context>"))return e;let t=e,n=/<context>[\s\S]*?<\/context>/gi;return t=t.replace(n,""),t=t.replace(/\n{3,}/g,`
|
|
363
351
|
|
|
364
|
-
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var
|
|
352
|
+
`),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var Me={};ae(Me,{PersonalAgentService:()=>ee});import{EventEmitter as No}from"events";import tn from"axios";import Ro from"http";import Fo from"https";import{v4 as Pe}from"uuid";import fe from"fs";import et from"path";import We from"os";var tt,ee,we=R(()=>{"use strict";Ae();se();Ze();Re();H();ms();tt=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,o=String(n||""),i=Number(s);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(o)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||i===401||i===403||o==="401"||o==="403"?"critical":"parsing"}},ee=class c extends No{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 Ro.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Fo.Agent({keepAlive:!0,timeout:36e5}),r.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),K.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(r.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=$s("fs");if(t.existsSync("/etc/os-release")){let s=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(s)return s[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return fe.existsSync(e)?t=fe.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
|
|
365
353
|
|
|
366
354
|
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.
|
|
367
355
|
|
|
368
|
-
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=
|
|
356
|
+
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=et.join(We.homedir(),".orion");return et.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(fe.existsSync(e))return;let t=et.join(We.homedir(),"Documents","orion","orion-device-knowledge.md");if(fe.existsSync(t)){r.info("📦 Migrating device knowledge to cross-platform location...");let n=et.dirname(e);fe.existsSync(n)||fe.mkdirSync(n,{recursive:!0});let s=fe.readFileSync(t,"utf8");fe.writeFileSync(e,s,"utf8"),r.info(`✅ Device knowledge migrated to: ${e}`),r.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){r.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=et.dirname(e);fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0});let n=We.platform(),s=We.arch(),o=We.hostname(),i=We.userInfo(),a=`# Device Knowledge
|
|
369
357
|
|
|
370
358
|
## System Information
|
|
371
359
|
- **Platform**: ${n}
|
|
372
360
|
- **Architecture**: ${s}
|
|
373
361
|
- **Hostname**: ${o}
|
|
374
|
-
- **Username**: ${
|
|
375
|
-
- **Home Directory**: ${
|
|
362
|
+
- **Username**: ${i.username}
|
|
363
|
+
- **Home Directory**: ${i.homedir}
|
|
376
364
|
|
|
377
365
|
## Available Tools
|
|
378
366
|
- Terminal/shell commands via system execution
|
|
@@ -385,28 +373,28 @@ Remember to update memory about device if any new information is learned during
|
|
|
385
373
|
|
|
386
374
|
---
|
|
387
375
|
*Last updated: ${new Date().toISOString()}*
|
|
388
|
-
`;return
|
|
376
|
+
`;return fe.writeFileSync(e,a,"utf8"),a}catch{return"Basic device knowledge initialization failed."}}static getInstance(){return c.instance||(c.instance=new c),c.instance}async sendMessageWithToolCalling(e,t,n,s=.7,o=!0,i,a,l){this.currentPromptId=Pe(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let u=l?.crossDeviceTaskId;u&&r.debug(`[PERSONAL AGENT] Executing cross-device task: ${u}`),l?.mode==="new"&&(t=[],r.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let p=i||this.authService.getUserId();r.debug("🔌 WebSocket will connect after receiving sessionId from API...");let v=(await Promise.resolve().then(()=>(Te(),je))).DeviceRegistrationService.getInstance().getCurrentDeviceId();if(!v)throw r.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(y=>({type:"image_url",image_url:{url:y}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:v,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(l?.conversationId)S.conversationId=l.conversationId,r.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),r.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let y=t.map(d=>{let h,m=d;m.metadata?.toolResults?h=m.metadata.toolResults:m.originalContent?h=m.originalContent:h=typeof d.content=="string"?d.content:JSON.stringify(d.content);let k=[{type:"text",text:h}];return m.imageUrls&&m.imageUrls.length>0&&k.push(...m.imageUrls.map(x=>({type:"image_url",image_url:{url:x}}))),{role:d.role,content:k}});for(let d=0;d<y.length;d++)y[d].role;S.messages=y,r.debug(`[PERSONAL AGENT] Sending request with ${y.length} messages (new conversation)`)}else r.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return o?this.performStreamingToolCall(S):this.performNonStreamingToolCall(S)}async performStreamingToolCall(e){let t=await this.getFirebaseIdToken();return t||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((n,s)=>{this.currentAbortController=new AbortController;let o="",i=Buffer.alloc(0),a="",l="",u=[],p=null,f=!1,v="";this.currentOutput="",this.completeOutputWithToolResults="";let S=new Map,y=new Set,d=this.authService.getUserId();tn.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 h=>{let m=h.data,k=h.headers["x-session-id"]||h.headers["session-id"];if(k){p=k,this.currentSessionId=k,r.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${k}`);let x=(await Promise.resolve().then(()=>(Ze(),ps))).FrontendWebSocketService.getInstance();r.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await x.connectForConversation(d||void 0,k)?r.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):r.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else r.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");m.on("data",x=>{try{i=Buffer.concat([i,x]);let N="",B=0;for(let M=0;M<i.length;M++)try{N=i.slice(0,M+1).toString("utf8"),B=M+1}catch{break}if(B>0){let M=i.slice(0,B);i=i.slice(B),o+=M.toString("utf8")}}catch{o+=x.toString()}let E=[/\r?\n/,/\r/],w=[],T=o;w=T.split(/\r?\n/),T=w.pop()||"",o=T;for(let N of w){let B=N.trim();if(B.startsWith("data: ")){let M=B.slice(6).trim();if(M==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),n(a);return}try{let P=JSON.parse(M);if(P.type==="session_start"&&P.conversationId){let D=P.conversationId,b=P.isNewConversation||!1,I=P.title;r.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),r.debug(`[PERSONAL AGENT] conversationId: ${D}`),r.debug(`[PERSONAL AGENT] isNewConversation: ${b}`),I&&r.debug(`[PERSONAL AGENT] title: "${I}"`),this.emit("conversation_id_received",{conversationId:D,isNew:b,title:I||void 0});continue}if(P.type==="title_generated"&&P.title&&P.conversationId){let D=P.title,b=P.conversationId;r.debug("[PERSONAL AGENT] Received title_generated event!"),r.debug(`[PERSONAL AGENT] conversationId: ${b}`),r.debug(`[PERSONAL AGENT] title: "${D}"`),this.emit("conversation_title_updated",{conversationId:b,title:D});continue}if(P.tool_response&&P.tool_response.content){let D=P.tool_response.content,b=P.tool_response.id||"unknown",I=P.tool_response.name||"unknown";this.emit("tool_completed",{toolName:I,toolId:b,result:D,todos:P.tool_response.todos||null}),this.emit("toolComplete",I);let F="";Array.isArray(D)?F=D.map(_=>typeof _=="string"?_:_&&typeof _=="object"&&(_.text||_.content)||"").join(""):typeof D=="string"?F=D:F=JSON.stringify(D),(!F||F.trim().length===0)&&(F="(empty tool result)");let $=`<context>
|
|
389
377
|
${F}
|
|
390
378
|
</context>`;u.push($),a+=$+`
|
|
391
379
|
`,this.completeOutputWithToolResults+=$+`
|
|
392
380
|
`,this.currentOutput+=$+`
|
|
393
|
-
`;continue}if(P.tool_calls){
|
|
394
|
-
${
|
|
381
|
+
`;continue}if(P.tool_calls){r.debug("Processing tool calls:",P.tool_calls.length,"items");for(let[D,b]of P.tool_calls.entries())if(r.debug("Tool call ["+D+"]:"),b.id){r.debug("Processing tool call ID:",b.id);let I=S.get(b.id)||{};for(let[F,$]of Object.entries(b))if(F==="function"&&typeof $=="object"&&$!==null){let _=I.function||{};I.function={..._,...$}}else I[F]=$;if(S.set(b.id,I),I.function?.name&&!y.has(b.id)){let F=I.function.name;r.debug("[TOOL-DISPLAY] Showing tool call:",F,"ID:",b.id),this.emit("toolExecuting",F)}if(I.function?.arguments&&I.function?.name){let F=I.function.arguments;F.endsWith("}")||F.endsWith('"}')?(r.debug("Complete tool call accumulated:",b.id,"-",I.function.name),r.debug("Arguments:",F.substring(0,100)+(F.length>100?"...":"")),y.has(b.id)||(y.add(b.id),this.handleCompleteToolCall(I))):r.debug("Partial tool call:",b.id,"-",I.function.name)}}}else if(P.tool_response&&P.tool_response.content){let D=P.tool_response.content,b=P.tool_response.id||"unknown",I=P.tool_response.name||"unknown",F=P.tool_response.role||"unknown";r.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),r.debug(" Tool ID:",b),r.debug(" Tool Name:",I),r.debug(" Tool Role:",F),r.debug(" Content Length:",D.length),r.debug(" Content Preview:",D.substring(0,200)+"..."),this.emit("tool_completed",{toolName:I,toolId:b,result:D,todos:P.tool_response.todos||null}),this.emit("toolComplete",I),P.tool_response.todos&&Array.isArray(P.tool_response.todos)&&(r.debug("[PERSONAL AGENT] Tool response contains",P.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:P.tool_response.todos}));let $=`<context>
|
|
382
|
+
${D}
|
|
395
383
|
</context>`;u.push($),a+=$+`
|
|
396
384
|
`,this.completeOutputWithToolResults+=$+`
|
|
397
385
|
`,this.currentOutput+=$+`
|
|
398
|
-
`,
|
|
399
|
-
${
|
|
386
|
+
`,r.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(P.content!==void 0){let D=P.content;if(D&&D.length>0&&r.debug(`[STREAMING] Received content chunk: "${D}" (length: ${D.length})`),D&&D.includes('{"tool_response"'))try{let b,I=!1;try{b=JSON.parse(D),I=!0}catch{let F=D.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(F){let $=F[0];b=JSON.parse($),I=!1}}if(b&&b.tool_response&&b.tool_response.content){let F=b.tool_response.content,$=b.tool_response.id||"unknown",_=b.tool_response.name||"unknown";this.emit("tool_completed",{toolName:_,toolId:$,result:F,todos:b.tool_response.todos||null}),this.emit("toolComplete",_),b.tool_response.todos&&Array.isArray(b.tool_response.todos)&&this.handleTodoUpdate({items:b.tool_response.todos});let de="";Array.isArray(F)?de=F.map(G=>G.text||"").join(""):typeof F=="string"?de=F:de=JSON.stringify(F);let re=`<context>
|
|
387
|
+
${de}
|
|
400
388
|
</context>`;if(u.push(re),a+=re+`
|
|
401
389
|
`,this.completeOutputWithToolResults+=re+`
|
|
402
390
|
`,this.currentOutput+=re+`
|
|
403
|
-
`,!I){let G=
|
|
391
|
+
`,!I){let G=D.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(G){let j=D.replace(G[0],"").trim();if(j.length>0){a+=j,l+=j,this.currentOutput+=j,this.completeOutputWithToolResults+=j;let Z=Ie.remove(j);this.emit("data",Z)}}}continue}}catch{}if(D.includes("<think>")){f=!0;let b=D.split("<think>")[0];if(b){a+=b,l+=b,this.currentOutput+=b,this.completeOutputWithToolResults+=b;let I=Ie.remove(b);this.emit("data",I)}}else if(D.includes("</think>")){f=!1,v+=D.split("</think>")[0],this.emit("thinking",v),v="";let b=D.split("</think>")[1]||"";if(b){a+=b,l+=b,this.currentOutput+=b,this.completeOutputWithToolResults+=b;let I=Ie.remove(b);this.emit("data",I)}}else if(f)v+=D,this.emit("thinking",v);else{a+=D,l+=D,this.currentOutput+=D,this.completeOutputWithToolResults+=D;let b=Ie.remove(D);this.emit("data",b)}}else if(P.type==="checkpoint_reached"||P.event==="checkpoint_reached")r.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(P.type==="todo_update")this.handleTodoUpdate(P.data);else if(P.type==="webview_update")this.handleWebViewUpdate(P.data);else if(P.type==="operator_progress")this.handleOperatorProgress(P.data);else if(P.type==="stop"){this.handleStop(P.data),n(a);return}}catch{r.debug("Treating as plain text"),a+=M,l+=M,this.currentOutput+=M,this.completeOutputWithToolResults+=M;let D=Ie.remove(M);this.emit("data",D)}}}}),m.on("end",()=>{this.emit("done"),n(a)}),m.on("error",x=>{switch(r.debug("Streaming error, disconnecting WebSocket and cleaning up"),tt.classify(x)){case"parsing":let w={type:"tool_result",tool_call_id:`error_${Pe()}`,error:!0,content:`Streaming parsing error occurred: ${x.message}. Please check response format and retry.`};r.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(w)),K.getInstance().handleConversationComplete(),n(a);return;case"critical":K.getInstance().handleConversationComplete(),this.emit("error",x),s(x);break}})}).catch(h=>{if(h.code==="ERR_CANCELED")r.debug("Task was cancelled, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),this.emit("canceled"),n(a);else switch(tt.classify(h)){case"parsing":let k={type:"tool_result",tool_call_id:`error_${Pe()}`,error:!0,content:`Request parsing error: ${h.message}. Please check request format and retry.`};r.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(k)),K.getInstance().handleConversationComplete(),n(a);break;case"critical":r.debug("Request failed, disconnecting WebSocket"),K.getInstance().handleConversationComplete(),s(h);break}})})}async performNonStreamingToolCall(e){try{let t=await this.getFirebaseIdToken();t||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let n=await tn.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}});if(n.data?.content){if(this.currentOutput=n.data.content,this.completeOutputWithToolResults=n.data.completeOutput||n.data.content,n.data.toolResults)for(let s of n.data.toolResults)this.handleToolResult(s.tool,s.result);return n.data.content}throw new Error("No response content received")}catch(t){switch(tt.classify(t)){case"parsing":let s={type:"tool_result",tool_call_id:`error_${Pe()}`,error:!0,content:`Non-streaming API parsing error: ${t.message}. Please check request format and retry.`};return r.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(s)),"";case"critical":throw this.emit("error",t),new Error(`Tool calling API Error: ${t.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{r.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}this.emit("toolExecuting",t),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=K.getInstance(),o={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(o)}catch(s){r.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),r.debug(`Tool Result: ${e.name}`),t&&r.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:o}=e;if(r.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
|
|
404
392
|
${n.map(l=>l.text||"").join("")}
|
|
405
393
|
</context>`;this.completeOutputWithToolResults+=a+`
|
|
406
394
|
`,this.currentOutput+=a+`
|
|
407
|
-
`,
|
|
395
|
+
`,r.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(o){r.debug("[PERSONAL AGENT] WebSocket tool error:",o);let i=`<context>
|
|
408
396
|
Error: ${o}
|
|
409
|
-
</context>`;this.completeOutputWithToolResults+=
|
|
397
|
+
</context>`;this.completeOutputWithToolResults+=i+`
|
|
410
398
|
`}}captureFrontendToolResult(e,t,n,s){let o=`<context>
|
|
411
399
|
Tool: ${e}
|
|
412
400
|
Success: ${n}
|
|
@@ -414,55 +402,55 @@ Output:
|
|
|
414
402
|
${t}
|
|
415
403
|
</context>`;this.completeOutputWithToolResults+=o+`
|
|
416
404
|
`,this.currentOutput+=o+`
|
|
417
|
-
`,
|
|
405
|
+
`,r.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),r.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:s,wrappedContent:o})}handleCheckpointReached(){let e=me.getInstance(),t=e.getQueuedMessages();if(t.length===0){r.debug("[CHECKPOINT] No queued messages to convert");return}let n=t.filter(o=>!o.isCrossDeviceTask),s=t.filter(o=>o.isCrossDeviceTask);if(r.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),r.debug(` - ${n.length} user messages -> convert to feedback`),r.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let o=n.map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",o),r.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(i=>{e.removeFromQueueById(i.id)})}s.length>0&&r.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||Pe(),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||Pe(),taskId:e.taskId||e.id||Pe(),sessionId:e.sessionId||Pe(),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(r.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),K.getInstance().handleConversationComplete(),r.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};r.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),r.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),r.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",{SNOWX_MODELS:s}=await Promise.resolve().then(()=>(Ae(),wn)),o=s.find(a=>a.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},i=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,i,o,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){r.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),K.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
|
|
418
406
|
|
|
419
|
-
[STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{i.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){i.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),i.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),i.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let o=(await Promise.resolve().then(()=>(we(),Ge))).DeviceRegistrationService.getInstance().getCurrentDeviceId();o?(n.device_id=o,i.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${o}`)):i.debug("[PERSONAL AGENT] No device_id available for stop request"),i.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Jt.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(i.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&i.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&i.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){i.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){i.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),K.getInstance().handleConversationComplete();let s={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",s),this.resetState(),i.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear()}getCurrentTodoList(){return this.currentTodoList}getActiveWebViewURLs(){return this.activeWebViewURLs}getOperatorTaskState(){return this.operatorTaskState}getCompleteOutput(){return this.completeOutputWithToolResults||this.currentOutput}get isProcessing(){return this.currentAbortController!==null||this.currentPromptId!==null}}});var rs={};ae(rs,{FirebaseNativeService:()=>Ye,TaskMode:()=>en,TaskStatus:()=>tn});import{getDatabase as So,ref as Zt,onChildAdded as Co,update as xo,set as ko,serverTimestamp as Eo}from"firebase/database";import{EventEmitter as Io}from"events";var en,tn,Ye,nn=R(()=>{"use strict";B();tt();en=(t=>(t.NEW="new",t.EXISTING="existing",t))(en||{}),tn=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(tn||{}),Ye=class c extends Io{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),i.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Ce.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=So(e),i.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(i.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(i.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){i.error("[Firebase Native] Firebase not initialized properly");return}i.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;i.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=Zt(this.database,n),o=this.auth?.currentUser;i.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=Co(s,r=>{let a=r.key,l=r.val();if(i.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){i.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){i.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){i.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:l.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let u=Array.from(this.processedTaskIds);u.slice(0,u.length-this.MAX_PROCESSED_IDS).forEach(f=>this.processedTaskIds.delete(f))}i.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{i.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),i.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){i.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,i.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),i.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),i.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){i.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){i.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),i.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),i.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(be(),$e))).PersonalAgentService.getInstance()){i.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}i.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?i.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):i.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),i.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),i.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){i.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(be(),$e)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(i.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.message||s||"Unknown error occurred";i.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.reason;i.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),i.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(be(),$e)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),i.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){i.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};n&&(o.result=n),i.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{i.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,o),i.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){i.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:r.message}),i.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Zt(this.database,s),l={status:t,updatedAt:Eo()};n&&(l.result=n),await xo(a,l),i.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else i.error("[Firebase Native] Database not available for fallback")}catch(a){i.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;i.debug("[Firebase Native] Sending task to device",{taskId:o,targetDeviceId:t,mode:s});try{let r=Zt(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await ko(r,a),i.debug("[Firebase Native] Task sent successfully",{taskId:o,targetDeviceId:t}),o}catch(r){throw r}}stopListening(){if(i.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,i.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){i.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),i.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Po}from"events";var Ue,sn=R(()=>{"use strict";we();se();tt();nn();be();B();Ue=class c extends Po{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=de.getInstance(),this.authService=H.getInstance(),this.firebaseAPI=Ce.getInstance(),this.firebaseNative=Ye.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=ee.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){i.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(i.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(i.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){i.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){i.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();i.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){i.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,i.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){i.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){i.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),i.error("Refusing to start listener for different user");return}i.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw i.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),i.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){i.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){i.error("No stored user ID found - cannot authenticate Firebase for listeners");return}i.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);i.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){i.warn("Firebase authentication failed:",n.message),i.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){i.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e.taskId),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}i.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,i.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),i.debug("Cross-device task UI flow triggered successfully")}catch(t){i.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){i.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){i.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),i.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],o=n[2];return s.length!==13||!Number.isInteger(Number(s))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,o=t.status;if(!n||!s){i.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){i.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",o);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),i.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),i.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){i.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();i.debug(`🔵 [CrossDevice] Processing task: ${e}`),i.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(i.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(i.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){i.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}i.debug("✅ [CrossDevice] Task accepted:",e),i.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let s=(Ne(),Ps(Sn)).MessageQueueManager.getInstance(),o=s.getQueueCount(),r=s.canAddToQueue();if(i.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(i.debug(`Executing task: ${e} with mode: ${n}`),i.debug(`Prompt to execute: ${t}`),ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(r),i.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}i.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{i.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){i.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=o=>{this.currentTaskId===e&&this.cleanupObservers()},s=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:xe,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(r,o),i.debug("Task submitted to device:",e)}catch(a){throw i.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return i.error("Failed to get available devices:",e.message),[]}}enable(){i.debug("[CROSS DEVICE] Service enabled")}disable(){i.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){i.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var ds={};ae(ds,{SnowXStreamHandlerService:()=>an});import{EventEmitter as Ho}from"events";var an,ps=R(()=>{"use strict";an=class extends Ho{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,n,s,o){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let p=this.byteBuffer.toString("utf8");this.buffer+=p,this.rawDataReceived+=p,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(n,s,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,o),this.printFinalStatistics(),!this.fullResponse&&!o){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,o=this.buffer.indexOf(`\r
|
|
420
|
-
`);if(o!==-1)s=o;else{let
|
|
421
|
-
`);if(
|
|
422
|
-
`?this.buffer=this.buffer.substring(s+2):this.buffer=this.buffer.substring(s+1);let a=
|
|
407
|
+
[STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{r.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){r.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),r.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),r.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,r.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):r.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let o=(await Promise.resolve().then(()=>(Te(),je))).DeviceRegistrationService.getInstance().getCurrentDeviceId();o?(n.device_id=o,r.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${o}`)):r.debug("[PERSONAL AGENT] No device_id available for stop request"),r.debug("[PERSONAL AGENT] Sending backend stop request");let i=await this.getFirebaseIdToken();i||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await tn.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i||this.getAuthToken()}`}});a.status===200&&(r.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&r.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&r.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){r.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){r.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),K.getInstance().handleConversationComplete();let s={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",s),this.resetState(),r.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 gs={};ae(gs,{FirebaseNativeService:()=>nt,TaskMode:()=>on,TaskStatus:()=>rn});import{getDatabase as _o,ref as sn,onChildAdded as Mo,update as Lo,set as Uo,serverTimestamp as Wo}from"firebase/database";import{EventEmitter as Bo}from"events";var on,rn,nt,an=R(()=>{"use strict";H();it();on=(t=>(t.NEW="new",t.EXISTING="existing",t))(on||{}),rn=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))(rn||{}),nt=class c extends Bo{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(),r.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=xe.getInstance()}setFirebaseInstances(e,t){r.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=_o(e),r.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(r.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(r.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){r.error("[Firebase Native] Firebase not initialized properly");return}r.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;r.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=sn(this.database,n),o=this.auth?.currentUser;r.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=Mo(s,i=>{let a=i.key,l=i.val();if(r.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:i.exists()}),!a||!l){r.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){r.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){r.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))}r.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},i=>{r.error("[Firebase Native] Firebase listener error",{code:i.code||"unknown",message:i.message,authState:this.auth?.currentUser?.uid||"null"})}),r.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){r.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,r.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),r.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),r.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){r.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){r.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),r.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),r.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(we(),Me))).PersonalAgentService.getInstance()){r.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}r.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?r.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):r.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),r.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),r.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){r.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(we(),Me)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(r.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.message||s||"Unknown error occurred";r.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.reason;r.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),r.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(we(),Me)),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),r.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){r.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};n&&(o.result=n),r.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{r.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,o),r.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(i){r.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:i.message}),r.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=sn(this.database,s),l={status:t,updatedAt:Wo()};n&&(l.result=n),await Lo(a,l),r.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else r.error("[Firebase Native] Database not available for fallback")}catch(a){r.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r.debug("[Firebase Native] Sending task to device",{taskId:o,targetDeviceId:t,mode:s});try{let i=sn(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await Uo(i,a),r.debug("[Firebase Native] Task sent successfully",{taskId:o,targetDeviceId:t}),o}catch(i){throw i}}stopListening(){if(r.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,r.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){r.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),r.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Ho}from"events";var Be,cn=R(()=>{"use strict";Te();se();it();an();we();H();Be=class c extends Ho{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=pe.getInstance(),this.authService=q.getInstance(),this.firebaseAPI=xe.getInstance(),this.firebaseNative=nt.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=ee.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){r.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(r.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(r.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){r.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){r.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){r.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();r.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){r.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,r.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){r.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){r.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),r.error("Refusing to start listener for different user");return}r.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw r.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),r.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){r.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){r.error("No stored user ID found - cannot authenticate Firebase for listeners");return}r.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);r.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){r.warn("Firebase authentication failed:",n.message),r.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){r.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){r.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),r.warn("🚨 [SECURITY] Task ID:",e.taskId),r.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),r.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}r.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,r.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}),r.debug("Cross-device task UI flow triggered successfully")}catch(t){r.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){r.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){r.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),r.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],o=n[2];return s.length!==13||!Number.isInteger(Number(s))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,o=t.status;if(!n||!s){r.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){r.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",o);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),r.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),r.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){r.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,r.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();r.debug(`🔵 [CrossDevice] Processing task: ${e}`),r.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(r.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){r.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),r.warn("🚨 [SECURITY] Task ID:",e),r.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),r.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(r.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){r.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}r.debug("✅ [CrossDevice] Task accepted:",e),r.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let i="existing";await this.executeTask(e,t,i),this.isProcessingIncoming=!1,r.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let s=(Re(),_s(En)).MessageQueueManager.getInstance(),o=s.getQueueCount(),i=s.canAddToQueue();if(r.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${i}`),!i)return!1}return!0}async executeTask(e,t,n){if(r.debug(`Executing task: ${e} with mode: ${n}`),r.debug(`Prompt to execute: ${t}`),ee.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){r.debug(`System is busy - queueing cross-device task: ${e}`);let i={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(i),r.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}r.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{r.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){r.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=o=>{this.currentTaskId===e&&this.cleanupObservers()},s=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:Ce,status:"pending"},i=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(i,o),r.debug("Task submitted to device:",e)}catch(a){throw r.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return r.error("Failed to get available devices:",e.message),[]}}enable(){r.debug("[CROSS DEVICE] Service enabled")}disable(){r.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){r.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var ys={};ae(ys,{SnowXStreamHandlerService:()=>dn});import{EventEmitter as ni}from"events";var dn,ws=R(()=>{"use strict";dn=class extends ni{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,n,s,o){let i=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let p=this.byteBuffer.toString("utf8");this.buffer+=p,this.rawDataReceived+=p,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(n,s,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,o),this.printFinalStatistics(),!this.fullResponse&&!o){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,o=this.buffer.indexOf(`\r
|
|
408
|
+
`);if(o!==-1)s=o;else{let i=this.buffer.indexOf(`
|
|
409
|
+
`);if(i!==-1)s=i;else{let a=this.buffer.indexOf("\r");if(a!==-1)s=a;else return}}for(;s!==-1;){if(this.isCancelled)return;let i=this.buffer.substring(0,s);this.linesProcessed++,this.buffer.substring(s,s+2)===`\r
|
|
410
|
+
`?this.buffer=this.buffer.substring(s+2):this.buffer=this.buffer.substring(s+1);let a=i.trim();if(!a){s=this.findNextLineEnd();continue}if(a.startsWith(":")){s=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,n),s=this.findNextLineEnd()}}processDataLine(e,t,n,s){if(this.isCancelled)return;this.dataLinesFound++;let o=e.substring(6).trim();if(o==="[DONE]"){this.emit("streamEnd");return}if(o)try{let i=JSON.parse(o);if(i.choices&&i.choices.length>0){let a=i.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)s?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,n))}}catch{}}processThinkingContent(e,t,n){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let s=this.thinkingBuffer.indexOf("</think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.thinkingContent+=o,n?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",n?.(this.thinkingContent));break}else{let s=this.thinkingBuffer.indexOf("<think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.regularContent+=o,this.fullResponse+=o,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,n){if(this.rawDataReceived.startsWith("data: ")){let s=this.rawDataReceived.substring(6).trim();try{let o=JSON.parse(s);o.choices&&o.choices.length>0&&o.choices[0].delta.content&&this.processThinkingContent(o.choices[0].delta.content,e,t)}catch{}}else try{let s=JSON.parse(this.rawDataReceived);s.choices?.[0]?.message?.content&&this.processThinkingContent(s.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
|
|
423
411
|
`);if(e!==-1)return e;let t=this.buffer.indexOf(`
|
|
424
|
-
`);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import qo from"axios";import{EventEmitter as Go}from"events";import zo from"http";import Xo from"https";var Dt,ms=R(()=>{"use strict";se();Dt=class extends Go{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new zo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Xo.Agent({keepAlive:!0,timeout:36e5}),this.client=qo.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=H.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){if(s.response?.status===429){if(n===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,n);await new Promise(r=>setTimeout(r,o*1e3))}else throw s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,o=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,o,r){let a=this.buildRequest(e,t,!1,n,s,o,r);try{let u=(await this.executeWithRetry(async()=>{let{data:p}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return p})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,o,r,a,l,u){let{SnowXStreamHandlerService:p}=await Promise.resolve().then(()=>(ps(),ds)),f=this.buildRequest(e,t,!0,n,s,o,r);return new Promise((y,T)=>{this.currentAbortController=new AbortController;let b=[],d=new Map,g=new p;this.client.post("/chat/completions",f,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async m=>{let C=m.data,S=m.headers["content-type"]||"",k=v=>{if(v?.index!==void 0){let x=v.index;d.has(x)||d.set(x,{});let A=d.get(x);v.id&&(A.id=v.id,A.type="function"),v.function&&(A.function||(A.function={name:"",arguments:""}),v.function.name&&(A.function.name=v.function.name),v.function.arguments&&(A.function.arguments+=v.function.arguments))}u?.(v),this.emit("tool_call_delta",v)};g.on("streamEnd",()=>{d.forEach((v,x)=>{v.id&&v.function?.name&&b.push(v)}),this.emit("done"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})}),g.on("cancelled",()=>{this.emit("canceled"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})});try{await g.processStreamingResponse(C,S,a||(()=>{}),l,k),d.forEach((v,x)=>{v.id&&v.function?.name&&b.push(v)}),this.emit("done"),y({content:g.getFinalResponse(),toolCalls:b.length>0?b:void 0})}catch(v){this.emit("error",v),T(v)}}).catch(m=>{m.code==="ERR_CANCELED"?(this.emit("canceled"),y({content:"",toolCalls:b.length>0?b:void 0})):T(m)})})}stopStreaming(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=void 0)}async testConnection(e){try{let t={role:"user",content:"Hello"};return!!(await this.performNonStreamingRequest([t],e,.7,.9)).content}catch{return!1}}}});import{io as jo}from"socket.io-client";import{EventEmitter as Vo}from"events";var At,gs=R(()=>{"use strict";we();At=class c extends Vo{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=de.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=jo(t,n),this.setupEventHandlers(),new Promise((s,o)=>{let r=setTimeout(()=>{o(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var hs,fs=R(()=>{"use strict";hs={apiKey:process.env.FIREBASE_API_KEY||"AIzaSyARpn1ypwsrIwB53shF2K0AKvHjNABcpBA",authDomain:process.env.FIREBASE_AUTH_DOMAIN||"snowx-31c33.firebaseapp.com",databaseURL:process.env.FIREBASE_DATABASE_URL||"https://snowx-31c33-default-rtdb.firebaseio.com",projectId:process.env.FIREBASE_PROJECT_ID||"snowx-31c33",storageBucket:process.env.FIREBASE_STORAGE_BUCKET||"snowx-31c33.firebasestorage.app",messagingSenderId:process.env.FIREBASE_MESSAGING_SENDER_ID||"679827069698",appId:process.env.FIREBASE_APP_ID||"1:679827069698:web:d4fd2c1c30d0b94ca04b5d",measurementId:process.env.FIREBASE_MEASUREMENT_ID||"G-1HZDCGCV7M"}});var ys={};ae(ys,{ServiceManager:()=>et});import{EventEmitter as Ko}from"events";import{initializeApp as Qo,getApps as vs}from"firebase/app";import{getAuth as Jo}from"firebase/auth";var et,cn=R(()=>{"use strict";be();ms();se();we();gs();Ke();sn();mt();De();B();fs();et=class c extends Ko{static instance;initialized=!1;personalAgent;networkClient;authService;deviceRegistration;webSocketService;frontendWebSocketService;crossDeviceService;toolCalling;firebaseApp=null;firebaseAuth=null;options={enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0};constructor(){super(),this.personalAgent=ee.getInstance(),this.networkClient=new Dt,this.authService=H.getInstance(),this.deviceRegistration=de.getInstance(),this.webSocketService=At.getInstance(),this.frontendWebSocketService=K.getInstance(),this.crossDeviceService=Ue.getInstance(),this.toolCalling=Ve.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}isInitialized(){return this.initialized}async initialize(e={}){if(!this.initialized){this.options={...this.options,...e};try{this.options.enableFirebase&&await this.initializeFirebase(),this.options.enableWebSocket&&await this.initializeWebSocket(),this.options.enableCrossDevice&&this.options.enableWebSocket&&await this.initializeCrossDevice(),this.options.enableToolCalling&&await this.initializeToolCalling(),this.setupServiceConnections(),this.initialized=!0,this.emit("initialized")}catch(t){throw t}}}async initializeFirebase(){try{let e=this.options.firebaseConfig||hs;if(vs().length===0?(this.firebaseApp=Qo(e),i.debug("Firebase app initialized")):(this.firebaseApp=vs()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=Jo(this.firebaseApp),i.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),i.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(nn(),rs));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),i.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{i.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){i.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=X[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=n;try{let l=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=o?this.toolCalling.getAvailableTools():void 0;return a?new Promise((p,f)=>{let y="";this.networkClient.on("data",T=>{y+=T}),this.networkClient.on("done",()=>{p(y)}),this.networkClient.on("error",f),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return X.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let o=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n())})}}});import*as dn from"@sentry/node";dn.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as oi}from"commander";import Zo from"react";import{render as ei}from"ink";se();import h,{useState as cs,useEffect as Ze,useCallback as rn,useRef as No}from"react";import{Box as D,Text as E,useInput as Ro,useApp as Fo}from"ink";import $o from"ink-spinner";import ls from"ink-select-input";be();Qt();import le from"chalk";import wo from"ora";var te=class{static spinner=null;static formatUserMessage(e){return le.cyan("You: ")+e}static formatAssistantMessage(e){return le.green("Assistant: ")+e}static formatError(e){return le.red("Error: ")+e}static formatWarning(e){return le.yellow("Warning: ")+e}static formatInfo(e){return le.blue("Info: ")+e}static formatSuccess(e){return le.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=wo(e).start()}static updateSpinner(e){this.spinner&&(this.spinner.text=e)}static stopSpinner(e=!0,t){this.spinner&&(t?e?this.spinner.succeed(t):this.spinner.fail(t):this.spinner.stop(),this.spinner=null)}static clearLine(){process.stdout.clearLine(0),process.stdout.cursorTo(0)}static printDivider(){console.log(le.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(le.bold.cyan(e)),console.log(le.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return le.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return le.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(le.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};B();Ne();import{EventEmitter as To}from"events";import Yt from"chalk";var It=class extends To{delegate=null;personalAgentService=ee.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let o=String(s[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s),r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
|
|
425
|
-
▸ ${s}`)}),this.personalAgentService.on("tool_completed",s=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:
|
|
426
|
-
❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(
|
|
412
|
+
`);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import si from"axios";import{EventEmitter as oi}from"events";import ii from"http";import ri from"https";var Ft,Ts=R(()=>{"use strict";se();Ft=class extends oi{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new ii.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new ri.Agent({keepAlive:!0,timeout:36e5}),this.client=si.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 n=0;n<t;n++)try{return await e()}catch(s){if(s.response?.status===429){if(n===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,n);await new Promise(i=>setTimeout(i,o*1e3))}else throw s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,o=.9,i,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:i,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,o,i){let a=this.buildRequest(e,t,!1,n,s,o,i);try{let u=(await this.executeWithRetry(async()=>{let{data:p}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return p})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,n=.7,s=.9,o,i,a,l,u){let{SnowXStreamHandlerService:p}=await Promise.resolve().then(()=>(ws(),ys)),f=this.buildRequest(e,t,!0,n,s,o,i);return new Promise((v,S)=>{this.currentAbortController=new AbortController;let y=[],d=new Map,h=new p;this.client.post("/chat/completions",f,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async m=>{let k=m.data,x=m.headers["content-type"]||"",E=w=>{if(w?.index!==void 0){let T=w.index;d.has(T)||d.set(T,{});let N=d.get(T);w.id&&(N.id=w.id,N.type="function"),w.function&&(N.function||(N.function={name:"",arguments:""}),w.function.name&&(N.function.name=w.function.name),w.function.arguments&&(N.function.arguments+=w.function.arguments))}u?.(w),this.emit("tool_call_delta",w)};h.on("streamEnd",()=>{d.forEach((w,T)=>{w.id&&w.function?.name&&y.push(w)}),this.emit("done"),v({content:h.getFinalResponse(),toolCalls:y.length>0?y:void 0})}),h.on("cancelled",()=>{this.emit("canceled"),v({content:h.getFinalResponse(),toolCalls:y.length>0?y:void 0})});try{await h.processStreamingResponse(k,x,a||(()=>{}),l,E),d.forEach((w,T)=>{w.id&&w.function?.name&&y.push(w)}),this.emit("done"),v({content:h.getFinalResponse(),toolCalls:y.length>0?y:void 0})}catch(w){this.emit("error",w),S(w)}}).catch(m=>{m.code==="ERR_CANCELED"?(this.emit("canceled"),v({content:"",toolCalls:y.length>0?y:void 0})):S(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 ai}from"socket.io-client";import{EventEmitter as ci}from"events";var $t,Ss=R(()=>{"use strict";Te();$t=class c extends ci{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=pe.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=ai(t,n),this.setupEventHandlers(),new Promise((s,o)=>{let i=setTimeout(()=>{o(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(i),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(i),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var ks,xs=R(()=>{"use strict";ks={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 Es={};ae(Es,{ServiceManager:()=>ot});import{EventEmitter as li}from"events";import{initializeApp as ui,getApps as Cs}from"firebase/app";import{getAuth as di}from"firebase/auth";var ot,pn=R(()=>{"use strict";we();Ts();se();Te();Ss();Ze();cn();vt();Ae();H();xs();ot=class c extends li{static instance;initialized=!1;personalAgent;networkClient;authService;deviceRegistration;webSocketService;frontendWebSocketService;crossDeviceService;toolCalling;firebaseApp=null;firebaseAuth=null;options={enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0};constructor(){super(),this.personalAgent=ee.getInstance(),this.networkClient=new Ft,this.authService=q.getInstance(),this.deviceRegistration=pe.getInstance(),this.webSocketService=$t.getInstance(),this.frontendWebSocketService=K.getInstance(),this.crossDeviceService=Be.getInstance(),this.toolCalling=Ye.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||ks;if(Cs().length===0?(this.firebaseApp=ui(e),r.debug("Firebase app initialized")):(this.firebaseApp=Cs()[0],r.debug("Using existing Firebase app")),this.firebaseAuth=di(this.firebaseApp),r.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),r.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(an(),gs));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),r.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{r.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){r.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=z[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:i=.7,stream:a=!0}=n;try{let l=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,i,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",S=>{v+=S}),this.networkClient.on("done",()=>{p(v)}),this.networkClient.on("error",f),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,i,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,i,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return z.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let o=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),i=l=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",i),n()};this.deviceRegistration.on("DeviceRegistrationComplete",i),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",i),n())})}}});import*as hn from"@sentry/node";hn.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as bi}from"commander";import mi from"react";import{render as gi}from"ink";se();import g,{useState as fs,useEffect as st,useCallback as un,useRef as Xo}from"react";import{Box as A,Text as C,useInput as zo,useApp as jo}from"ink";import Vo from"ink-spinner";import vs from"ink-select-input";we();en();import ue from"chalk";import $o from"ora";var te=class{static spinner=null;static formatUserMessage(e){return ue.cyan("You: ")+e}static formatAssistantMessage(e){return ue.green("Assistant: ")+e}static formatError(e){return ue.red("Error: ")+e}static formatWarning(e){return ue.yellow("Warning: ")+e}static formatInfo(e){return ue.blue("Info: ")+e}static formatSuccess(e){return ue.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=$o(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(ue.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(ue.bold.cyan(e)),console.log(ue.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return ue.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return ue.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(ue.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};H();Re();$e();import{EventEmitter as Oo}from"events";import nn from"chalk";var Nt=class extends Oo{delegate=null;personalAgentService=ee.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let o=String(s[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s),i&&i.isStreaming&&(!i.content||i.content===""?i.content=s:i.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
|
|
413
|
+
▸ ${s}`)}),this.personalAgentService.on("tool_completed",s=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:i,error:a}=s;console.log(i!==!1?`✓ ${o}`:`✗ ${o} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",s=>{}),this.personalAgentService.on("todo_update",s=>{}),this.personalAgentService.on("operator_progress",s=>{}),this.personalAgentService.on("webview_update",s=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(s.isStreaming=!1),o&&o.isStreaming&&(o.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",s=>{console.error(`
|
|
414
|
+
❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(r.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(s.content&&s.content.trim()?(r.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${s.content.substring(0,50)}..."`),o.content=s.content,o.originalContent=s.content):r.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),s.completeWithTools&&(o.metadata={toolResults:s.completeWithTools}),o.isStreaming=!1,r.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),i&&i.isStreaming&&(s.content&&s.content.trim()?(r.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${s.content.substring(0,50)}..."`),i.content=s.content,i.originalContent=s.content):r.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),s.completeWithTools&&(i.metadata={toolResults:s.completeWithTools}),i.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t=!0){if(!this.delegate||!e.trim())return;let n=new le,s=e.trim(),o=n.count(s);if(o>Fe){console.log(te.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${Fe.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let a=me.getInstance();a.addToQueue({content:s,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(nn.blue(`⚡ Message queued (${a.getQueueCount()} in queue)`)),console.log(nn.dim(" Your feedback will be sent when AI completes current task"))):console.log(nn.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let i=null;this.delegate.isVisionEnabled&&(i=await Ue.getInstance().captureScreen(),i?r.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${i.length} chars`):r.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision")),this.delegate.currentInput="";try{t?await this.processStreamingMessage(i):await this.processNonStreamingMessage(i)}catch(a){console.error(te.formatError(`Message failed: ${a.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",a.message)}}async processStreamingMessage(e){if(this.delegate)try{r.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(o=>!(o.isStreaming||o.role==="system"||!o.content||typeof o.content=="string"&&o.content.trim().length===0)).map(o=>({role:o.role,content:o.content})),n=this.delegate.fullConversationHistory.filter(o=>o.role==="user"),s=n[n.length-1];if(s)try{let o=e?[e]:void 0,i={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,o,i),r.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(o){throw r.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${o.message}`),o}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let o=t.content;o.trim().length>0&&(o+=`
|
|
427
415
|
|
|
428
|
-
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(o=>o.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,ee.getInstance().stopStreaming().catch(s=>{
|
|
429
|
-
`).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());
|
|
416
|
+
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(o=>o.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,ee.getInstance().stopStreaming().catch(s=>{r.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};we();Bt();Re();Ze();cn();Ae();ce();ge();import ln from"terminal-link";import{homedir as qo}from"os";function hs(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",qo())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Go(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function Rt(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let o=s;return!Go(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(o=hs(s)),ln(n,o,{fallback:(i,a)=>`${i} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(s)?t:ln(t,t,{fallback:(o,i)=>i})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(s)||s.includes("http"))return t;let o=hs(t);return ln(t,o,{fallback:(i,a)=>i})}),e}var Ko=0;function V(){return`msg-${Date.now()}-${++Ko}`}function Qo(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(c))!==null;){let i=n[1].split(`
|
|
417
|
+
`).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());i.length>0&&t.push({options:i})}let s=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return s=s.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:s}}function Jo(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,s;for(;(s=e.exec(c))!==null;){let i=s[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(i))!==null;){let u=l[1],p=l[2];n.has(p)||(n.add(p),t.push({name:u,path:p}))}}let o=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return o=o.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:o}}function bs(){let{exit:c}=jo(),e=q.getInstance(),t=ee.getInstance(),n=me.getInstance(),s=K.getInstance(),o=Be.getInstance();st(()=>(O.enableCustomUI(),()=>O.disableCustomUI()),[]);let[i,a]=fs({messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
430
418
|
|
|
431
419
|
Your autonomous on-device AI agent.
|
|
432
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",isLoading:!1,loadingMessage:"Processing",mode:"prompt",showHelp:!1,showModelMenu:!1,showCommandMenu:!1,tokens:0,cost:0,selectedModel:
|
|
420
|
+
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:z.find(d=>d.name===ke.string("selectedPersonalModel"))||z.find(d=>d.name==="snowx-c5")||z[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=Xo(null),[u]=fs(()=>{let d={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:z.find(h=>h.name===ke.string("selectedPersonalModel"))||z.find(h=>h.name==="snowx-c5")||z[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Nt(d)}),p=un(async()=>{},[]);st(()=>{let d=i.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}})),h={messages:d,fullConversationHistory:d,isLoading:i.isLoading,currentInput:i.input,selectedModel:i.selectedModel,isVisionEnabled:i.isVisionEnabled,conversationId:i.conversationId,usesCustomUI:!0,updateCurrentConversation:p};u.setDelegate(h)},[i.messages,i.selectedModel,i.isVisionEnabled,i.isLoading,i.input,i.conversationId,u,p]);let f=un(async d=>{if(d.startsWith("/")){let w=d.toLowerCase().trim();if(w==="/help"||w==="/?"){a(T=>({...T,showCommandMenu:!0,input:""}));return}if(w==="/model"){a(T=>({...T,showModelMenu:!0,input:""}));return}if(w==="/clear"||w==="/new"){a(T=>({...T,messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
433
421
|
|
|
434
422
|
Your intelligent AI assistant.
|
|
435
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(
|
|
423
|
+
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(w==="/vision"){a(T=>({...T,isVisionEnabled:!T.isVisionEnabled,messages:[...T.messages,{id:V(),role:"system",content:`Vision mode ${T.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(w==="/exit"||w==="/quit"){c();return}if(w==="/stop"){i.isLoading?(t.stopStreaming(),a(T=>({...T,isLoading:!1,messages:[...T.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(T=>({...T,messages:[...T.messages,{id:V(),role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(w==="/signout"){a(T=>({...T,messages:[...T.messages,{id:V(),role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(N=>({...N,messages:[...N.messages,{id:V(),role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(N=>({...N,messages:[...N.messages,{id:V(),role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(T){a(N=>({...N,messages:[...N.messages,{id:V(),role:"system",content:`❌ Error: ${T.message}`,timestamp:Date.now()}]}))}return}a(T=>({...T,messages:[...T.messages,{id:V(),role:"system",content:`Unknown command: ${d}
|
|
436
424
|
|
|
437
|
-
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(
|
|
438
|
-
[TOOL:${
|
|
425
|
+
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(i.isLoading){let w=n.addToQueue({content:d,imageUrls:[],attachments:[],model:i.selectedModel.name});a(w?T=>({...T,input:""}):T=>({...T,messages:[...T.messages,{id:V(),role:"system",content:"⚠️ Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let h=Date.now(),m={id:V(),role:"user",content:d,timestamp:h},k={id:V(),role:"assistant",content:"",timestamp:h+1},x=[...i.messages,m,k];a(w=>({...w,messages:x,input:"",isLoading:!0,loadingMessage:"Processing"}));let E=x.map(w=>({role:w.role,content:w.content,timestamp:new Date(w.timestamp||Date.now()),...w.tool&&{tool:w.tool},...w.toolOutput&&{toolOutput:w.toolOutput}}));u.setDelegate({messages:E,fullConversationHistory:E,isLoading:!1,currentInput:"",selectedModel:i.selectedModel,isVisionEnabled:i.isVisionEnabled,conversationId:i.conversationId,usesCustomUI:!0,updateCurrentConversation:p});try{await u.sendMessage(d)}catch(w){a(T=>({...T,messages:[...T.messages,{id:V(),role:"system",content:`Error: ${w.message}`,timestamp:Date.now()}],isLoading:!1}))}},[i.isLoading,i.isVisionEnabled,i.selectedModel,n,u,e,c]),v=un(()=>{if(!n.hasQueuedMessages())return;let d=n.processNextMessage();d&&(n.startProcessing(),f(d.content))},[n,f]);st(()=>{let d="",h=!1,m=!1,k=100,x=b=>{a(I=>({...I,conversationId:b.conversationId,conversationTitleGenerated:!!b.title}))},E=b=>{},w=()=>{a(b=>({...b,loadingMessage:"Processing"}))},T=()=>{if(m=!1,!h)return;h=!1;let b=d;a(I=>{let F=I.messages.map(($,_)=>$.role==="assistant"&&!I.messages.slice(_+1).some(re=>re.role==="assistant")?{...$,content:b}:$);return{...I,messages:F}})},N=b=>{d+=b,h=!0,m||(m=!0,setTimeout(T,k))},B=b=>{let I=`
|
|
426
|
+
[TOOL:${b}]`;d+=I,a(F=>{let $=F.messages.map((_,de)=>_.role==="assistant"&&!F.messages.slice(de+1).some(G=>G.role==="assistant")?{..._,content:_.content+I}:_);return{...F,messages:$,loadingMessage:`${b}`}})},M=b=>{if(b&&b.toolName&&b.result){let I="";typeof b.result=="string"?I=b.result:Array.isArray(b.result)?I=b.result.map(G=>typeof G=="string"?G:G&&typeof G=="object"?G.text||G.content||JSON.stringify(G):"").join(""):b.result.output?I=typeof b.result.output=="string"?b.result.output:JSON.stringify(b.result.output,null,2):b.result.content?I=b.result.content:I=JSON.stringify(b.result,null,2);let F=`<context>
|
|
439
427
|
${I}
|
|
440
|
-
</context>`;a(G=>{let j=G.messages.map((Z,
|
|
441
|
-
`+F:F}}}return Z});return{...G,messages:j}});let $=
|
|
442
|
-
`).filter(J=>J.trim()),j=G.length,Z=I.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||I.match(/^\s*(\S+\.\w+)/m),fe=Z?Z[1].split("/").pop():null;if($.includes("todo")){let J=w.todos;if(J&&Array.isArray(J)&&J.length>0){let ne=J.filter(Te=>Te.status==="completed").length,We=J.filter(Te=>Te.status==="in_progress"||Te.status==="inProgress");if(O=` ${ne}/${J.length} done`,We.length>0){let Te=We[0].text||We[0].content||"",Ss=Te.length>40?Te.substring(0,40)+"…":Te;O+=` → ${Ss}`}}}else if($.includes("read"))fe?O=` ${fe} (${j} lines)`:O=` ${j} lines`;else if($.includes("write"))fe?O=` ${fe} ✓`:O=" ✓";else if($.includes("edit"))fe?O=` ${fe} ✓`:O=" ✓";else if($.includes("bash")||$.includes("command"))if(I.includes("error")||I.includes("Error"))O=" ✗ error";else if(j===0||j===1&&G[0].trim()==="")O=" ✓";else if(j<=3){let J=G.slice(0,2).join(" ").substring(0,50);O=j===1?` → ${J}`:` → ${J}…`}else O=` ✓ ${j} lines`;else if($.includes("grep")||$.includes("search")){let J=G.length;O=J>0?` ${J} matches`:" no matches"}else $.includes("glob")?O=` ${j} files`:$.includes("task")?O=" ✓":O=j>0?" ✓":""}let ue=`[TOOL:${w.toolName}]`,re=`[TOOL:${w.toolName}|${O.trim()}]`;d=d.replace(ue,re),a(G=>{let j=G.messages.map((Z,fe)=>{if(Z.role==="assistant"&&!G.messages.slice(fe+1).some(ne=>ne.role==="assistant")){let ne=Z.content;if($.includes("todo")){let We=/\n\[TOOL:TodoWrite\][^\n]*/g;ne=ne.replace(We,"")}return ne=ne.replace(ue,re),{...Z,content:ne}}return Z});return{...G,messages:j}})}},P=()=>{if(g){g=!1,m=!1;let w=d;a(I=>{let F=I.messages.map(($,O)=>$.role==="assistant"&&!I.messages.slice(O+1).some(re=>re.role==="assistant")?{...$,content:w}:$);return{...I,messages:F,isLoading:!1}})}else a(w=>({...w,isLoading:!1}));d=""},N=w=>{a(I=>({...I,messages:[...I.messages,{id:V(),role:"system",content:`Error: ${w.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),d=""};return t.on("conversation_id_received",S),t.on("conversation_title_updated",k),t.on("thinking",v),t.on("data",A),t.on("toolExecuting",M),t.on("tool_completed",q),t.on("done",P),t.on("error",N),()=>{t.off("conversation_id_received",S),t.off("conversation_title_updated",k),t.off("thinking",v),t.off("data",A),t.off("toolExecuting",M),t.off("tool_completed",q),t.off("done",P),t.off("error",N)}},[t,y]),Ze(()=>{let d=S=>{a(k=>({...k,queuedMessages:S}))},g=S=>{},m=S=>{l.current=S,a(k=>({...k,todoList:S}))},C=S=>{if(r.isLoading){n.addToQueue({content:S.prompt,imageUrls:[],attachments:[],model:r.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:S.taskId})||a(v=>({...v,messages:[...v.messages,{id:V(),role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(S.prompt)};return n.on("queue:updated",d),s.on("feedback:sent",g),t.on("todo_update",m),o.on("CrossDeviceTaskSendMessage",C),()=>{n.off("queue:updated",d),s.off("feedback:sent",g),t.off("todo_update",m),o.off("CrossDeviceTaskSendMessage",C)}},[n,s,t,o,f,r.isLoading,r.selectedModel.name]),Ze(()=>{!r.isLoading&&n.hasQueuedMessages()&&y()},[r.isLoading,n,y]),Ro((d,g)=>{if(g.escape){if(r.isLoading){t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(r.showModelMenu||r.showCommandMenu){a(m=>({...m,showModelMenu:!1,showCommandMenu:!1,input:m.showCommandMenu&&m.input==="/"?"":m.input}));return}if(r.showHelp){a(m=>({...m,showHelp:!1}));return}}if(!r.showModelMenu){if(g.ctrl&&d==="c"){r.isLoading?(t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(d==="?"&&r.input===""){a(m=>({...m,showHelp:!m.showHelp}));return}if(g.return&&!r.showCommandMenu){r.input.trim()&&f(r.input);return}if(g.delete||g.backspace){a(m=>{let C=m.input.slice(0,-1);return m.showCommandMenu&&!C.startsWith("/")?{...m,input:C,showCommandMenu:!1}:{...m,input:C}});return}!g.ctrl&&!g.meta&&d&&a(m=>{let C=m.input+d;return C==="/"&&!m.showCommandMenu?{...m,input:C,showCommandMenu:!0}:{...m,input:C}})}});let T=e.getUserEmail()||"User",b=ie.getDisplayName(ie.getCurrentUserTier());return h.createElement(D,{flexDirection:"column",width:"100%"},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},h.createElement(E,{color:"white"},r.selectedModel.displayName),h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"gray"},T),h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"white"},b),r.queuedMessages.length>0&&h.createElement(h.Fragment,null,h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"white",inverse:!0,bold:!0}," ",r.queuedMessages.length," "),h.createElement(E,{color:"gray"}," queued")),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(h.Fragment,null,h.createElement(E,{color:"gray",dimColor:!0}," • "),h.createElement(E,{color:"blue",inverse:!0,bold:!0}," 📱 ",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," "),h.createElement(E,{color:"gray"}," cross-device"))),h.createElement(D,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},r.messages.map(d=>h.createElement(Bo,{key:d.id,message:d,onSuggestionClick:g=>{a(m=>({...m,input:g}))}}))),r.todoList&&r.todoList.todos.length>0&&r.todoList.todos.some(d=>d.status!=="completed")&&h.createElement(D,{paddingX:2,marginBottom:1},h.createElement(D,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(D,{marginBottom:1},h.createElement(E,{color:"white",bold:!0},"Tasks"),h.createElement(E,{color:"gray"}," • "),h.createElement(E,{color:"gray"},r.todoList.todos.filter(d=>d.status==="completed").length,"/",r.todoList.todos.length)),r.todoList.todos.map((d,g)=>{let m=d.status==="completed"?"✓":d.status==="in_progress"?"⋯":"○",C=d.status==="completed"?"green":d.status==="in_progress"?"blue":"gray";return h.createElement(D,{key:d.id||g},h.createElement(E,{color:C},m),h.createElement(E,{color:"gray"}," "),h.createElement(E,{color:d.status==="completed"?"gray":"white",dimColor:d.status==="completed"},d.status==="in_progress"&&d.activeForm?d.activeForm:d.text))}))),r.isLoading&&h.createElement(D,{paddingX:0,marginBottom:1,flexDirection:"column"},h.createElement(D,null,h.createElement(E,{color:"magenta"},h.createElement($o,{type:"dots"})),h.createElement(E,{color:"white"}," ",r.loadingMessage,"… "),h.createElement(E,{color:"white"},"(esc to interrupt)")),h.createElement(D,{marginLeft:2},h.createElement(E,{color:"yellow"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),r.showHelp&&h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Keyboard Shortcuts"),h.createElement(D,{marginTop:1,flexDirection:"column"},h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Enter")," ",h.createElement(E,{color:"white"},"Submit message")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"?")," ",h.createElement(E,{color:"white"},"Toggle this help")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Esc")," ",h.createElement(E,{color:"white"},"Stop generation / Close menus")),h.createElement(E,{color:"white"},"• ",h.createElement(E,{color:"white",bold:!0},"Ctrl+C")," ",h.createElement(E,{color:"white"},"Stop generation / Exit"))),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Press Esc to close"))),r.showModelMenu&&(()=>{let d=ie.getCurrentUserTier(),g=X.filter(v=>v.name.startsWith("snowx-o4")||v.name.startsWith("snowx-c")||v.name.startsWith("snowx-h")),m=X.filter(v=>v.name.startsWith("snowx-5")||v.name.startsWith("snowx-o3")||v.name.startsWith("snowx-4")),C=X.filter(v=>v.name.startsWith("snowx-g")),S=v=>v.map(x=>{let A=ie.isModelAccessible(x.name,d);return{label:A?x.displayName:`🔒 ${x.displayName}`,value:x.name,isAccessible:A}}),k=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1},...S(g),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1},...S(m),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1},...S(C)];return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Select Model"),h.createElement(E,{color:"gray",dimColor:!0},"Tier: ",ie.getDisplayName(d)),h.createElement(D,{marginTop:1},h.createElement(ls,{items:k.map(v=>({label:v.label,value:v.value})),onSelect:v=>{if(v.value.startsWith("_"))return;if(!k.find(M=>M.value===v.value)?.isAccessible){a(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:ie.getAccessDeniedMessage(v.value),timestamp:Date.now()}]}));return}let A=X.find(M=>M.name===v.value);A&&(Se.set("selectedPersonalModel",A.name),a(M=>({...M,selectedModel:A,showModelMenu:!1,messages:[...M.messages,{id:V(),role:"system",content:`Switched to ${A.displayName}`,timestamp:Date.now()}]})))}})),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Esc to cancel")))})(),r.showCommandMenu&&(()=>{let d=[{label:"/model — Change AI model",value:"model"},{label:"/new — Start new conversation",value:"new"},{label:"/clear — Clear conversation",value:"clear"},{label:"/stop — Stop current generation",value:"stop"},{label:"/vision — Toggle vision mode",value:"vision"},{label:"/signout — Sign out and exit",value:"signout"},{label:"/exit — Exit Orion",value:"exit"},{label:"/help — Show this menu",value:"help"}],g=r.input.startsWith("/")?r.input.substring(1).toLowerCase():"",m=g?d.filter(C=>C.value.toLowerCase().includes(g)):d;return h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},h.createElement(E,{bold:!0,color:"white"},"Available Commands ",g&&`(filtered: "${g}")`),h.createElement(D,{marginTop:1},h.createElement(ls,{items:m.length>0?m:[{label:"No matching commands",value:""}],onSelect:C=>{C.value&&(a(S=>({...S,showCommandMenu:!1,input:""})),f(`/${C.value}`))}})),h.createElement(D,{marginTop:1},h.createElement(E,{color:"white"},"Esc to cancel")))})(),r.queuedMessages.length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.map((d,g)=>h.createElement(D,{key:d.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(E,{color:"white",bold:!0},g+1),h.createElement(E,{color:"white"}," • "),h.createElement(E,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(E,{color:"white"},r.queuedMessages.length," message",r.queuedMessages.length>1?"s":""," queued"))),r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&h.createElement(D,{flexDirection:"column",paddingX:2,marginBottom:1},r.queuedMessages.filter(d=>d.isCrossDeviceTask).map((d,g)=>h.createElement(D,{key:`cross-${d.id}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},h.createElement(D,null,h.createElement(E,{color:"blue",bold:!0},"📱 ",g+1),h.createElement(E,{color:"white"}," • "),h.createElement(E,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),h.createElement(D,null,h.createElement(E,{color:"blue"},r.queuedMessages.filter(d=>d.isCrossDeviceTask).length," cross-device task",r.queuedMessages.filter(d=>d.isCrossDeviceTask).length>1?"s":""," waiting"))),h.createElement(D,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},h.createElement(D,null,h.createElement(E,{color:"white"},"▶ "),h.createElement(E,{color:"white"},r.input,!r.isLoading&&h.createElement(E,{color:"white",inverse:!0}," "))),h.createElement(D,{marginTop:0},h.createElement(E,{color:"white"},r.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),h.createElement(D,{paddingX:2,paddingY:0},h.createElement(E,{color:"white"},"? help · Ctrl+C exit")))}function Uo(c){let e=c;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/\*(.+?)\*/g,"$1"),e=e.replace(/_(.+?)_/g,"$1"),e=e.replace(/`(.+?)`/g,"$1"),e=Pt(e),e}function Lo({suggestions:c,onSelect:e}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},c.map((t,n)=>h.createElement(D,{key:`sug-block-${n}-${t.options.join(",").slice(0,20)}`,flexWrap:"wrap",gap:1},t.options.map(s=>h.createElement(D,{key:`sug-opt-${s.slice(0,30)}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(E,{color:"cyan"},s))))),e&&h.createElement(D,{marginTop:0},h.createElement(E,{color:"gray",dimColor:!0},"Type a suggestion to use it")))}function Wo({workingFiles:c}){return c.length===0?null:h.createElement(D,{flexDirection:"column",marginTop:1},h.createElement(D,{marginBottom:0},h.createElement(E,{color:"gray",bold:!0},"Working Files"),h.createElement(E,{color:"gray",dimColor:!0}," (",c.length,")")),h.createElement(D,{flexWrap:"wrap",gap:1},c.map(e=>h.createElement(D,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},h.createElement(E,{color:"white"},e.name)))))}function Bo({message:c,onSuggestionClick:e}){let{role:t,content:n,tool:s}=c;if(t==="system"){let o=n.split(`
|
|
443
|
-
`);return
|
|
444
|
-
`);return
|
|
445
|
-
🔐 Orion Authentication`)),console.log(
|
|
446
|
-
📋 To authenticate, please follow these steps:`)),console.log(
|
|
447
|
-
Paste your access token here:`));let{accessToken:t}=await
|
|
448
|
-
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(
|
|
449
|
-
✅ Authentication successful!`)),s&&(console.log(
|
|
450
|
-
❌ Authentication failed. Please try again.`))}catch(n){console.log(
|
|
451
|
-
❌ Authentication error: ${n.message}`))}}async logout(){console.log(
|
|
452
|
-
🔄 Signing out...`)),console.log(
|
|
453
|
-
✅ Successfully signed out`)),console.log(
|
|
454
|
-
❌ Logout failed`)),console.log(
|
|
455
|
-
✅ Authenticated`)),t){console.log(
|
|
456
|
-
Usage:`)),console.log(
|
|
457
|
-
⚠️ Not authenticated`)),console.log(
|
|
428
|
+
</context>`;a(G=>{let j=G.messages.map((Z,ve)=>{if(Z.role==="assistant"&&!G.messages.slice(ve+1).some(ne=>ne.role==="assistant")){let ne=Z.metadata?.toolResults;return{...Z,metadata:{...Z.metadata,toolResults:ne?ne+`
|
|
429
|
+
`+F:F}}}return Z});return{...G,messages:j}});let $=b.toolName.toLowerCase(),_="";if(I){let G=I.split(`
|
|
430
|
+
`).filter(J=>J.trim()),j=G.length,Z=I.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||I.match(/^\s*(\S+\.\w+)/m),ve=Z?Z[1].split("/").pop():null;if($.includes("todo")){let J=b.todos;if(J&&Array.isArray(J)&&J.length>0){let ne=J.filter(Se=>Se.status==="completed").length,qe=J.filter(Se=>Se.status==="in_progress"||Se.status==="inProgress");if(_=` ${ne}/${J.length} done`,qe.length>0){let Se=qe[0].text||qe[0].content||"",As=Se.length>40?Se.substring(0,40)+"…":Se;_+=` → ${As}`}}}else if($.includes("read"))ve?_=` ${ve} (${j} lines)`:_=` ${j} lines`;else if($.includes("write"))ve?_=` ${ve} ✓`:_=" ✓";else if($.includes("edit"))ve?_=` ${ve} ✓`:_=" ✓";else if($.includes("bash")||$.includes("command"))if(I.includes("error")||I.includes("Error"))_=" ✗ error";else if(j===0||j===1&&G[0].trim()==="")_=" ✓";else if(j<=3){let J=G.slice(0,2).join(" ").substring(0,50);_=j===1?` → ${J}`:` → ${J}…`}else _=` ✓ ${j} lines`;else if($.includes("grep")||$.includes("search")){let J=G.length;_=J>0?` ${J} matches`:" no matches"}else $.includes("glob")?_=` ${j} files`:$.includes("task")?_=" ✓":_=j>0?" ✓":""}let de=`[TOOL:${b.toolName}]`,re=`[TOOL:${b.toolName}|${_.trim()}]`;d=d.replace(de,re),a(G=>{let j=G.messages.map((Z,ve)=>{if(Z.role==="assistant"&&!G.messages.slice(ve+1).some(ne=>ne.role==="assistant")){let ne=Z.content;if($.includes("todo")){let qe=/\n\[TOOL:TodoWrite\][^\n]*/g;ne=ne.replace(qe,"")}return ne=ne.replace(de,re),{...Z,content:ne}}return Z});return{...G,messages:j}})}},P=()=>{if(h){h=!1,m=!1;let b=d;a(I=>{let F=I.messages.map(($,_)=>$.role==="assistant"&&!I.messages.slice(_+1).some(re=>re.role==="assistant")?{...$,content:b}:$);return{...I,messages:F,isLoading:!1}})}else a(b=>({...b,isLoading:!1}));d=""},D=b=>{a(I=>({...I,messages:[...I.messages,{id:V(),role:"system",content:`Error: ${b.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),d=""};return t.on("conversation_id_received",x),t.on("conversation_title_updated",E),t.on("thinking",w),t.on("data",N),t.on("toolExecuting",B),t.on("tool_completed",M),t.on("done",P),t.on("error",D),()=>{t.off("conversation_id_received",x),t.off("conversation_title_updated",E),t.off("thinking",w),t.off("data",N),t.off("toolExecuting",B),t.off("tool_completed",M),t.off("done",P),t.off("error",D)}},[t,v]),st(()=>{let d=x=>{a(E=>({...E,queuedMessages:x}))},h=x=>{},m=x=>{l.current=x,a(E=>({...E,todoList:x}))},k=x=>{if(i.isLoading){n.addToQueue({content:x.prompt,imageUrls:[],attachments:[],model:i.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:x.taskId})||a(w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(x.prompt)};return n.on("queue:updated",d),s.on("feedback:sent",h),t.on("todo_update",m),o.on("CrossDeviceTaskSendMessage",k),()=>{n.off("queue:updated",d),s.off("feedback:sent",h),t.off("todo_update",m),o.off("CrossDeviceTaskSendMessage",k)}},[n,s,t,o,f,i.isLoading,i.selectedModel.name]),st(()=>{!i.isLoading&&n.hasQueuedMessages()&&v()},[i.isLoading,n,v]),zo((d,h)=>{if(h.escape){if(i.isLoading){t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(i.showModelMenu||i.showCommandMenu){a(m=>({...m,showModelMenu:!1,showCommandMenu:!1,input:m.showCommandMenu&&m.input==="/"?"":m.input}));return}if(i.showHelp){a(m=>({...m,showHelp:!1}));return}}if(!i.showModelMenu){if(h.ctrl&&d==="c"){i.isLoading?(t.stopStreaming(),a(m=>({...m,isLoading:!1,messages:[...m.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(d==="?"&&i.input===""){a(m=>({...m,showHelp:!m.showHelp}));return}if(h.return&&!i.showCommandMenu){i.input.trim()&&f(i.input);return}if(h.delete||h.backspace){a(m=>{let k=m.input.slice(0,-1);return m.showCommandMenu&&!k.startsWith("/")?{...m,input:k,showCommandMenu:!1}:{...m,input:k}});return}!h.ctrl&&!h.meta&&d&&a(m=>{let k=m.input+d;return k==="/"&&!m.showCommandMenu?{...m,input:k,showCommandMenu:!0}:{...m,input:k}})}});let S=e.getUserEmail()||"User",y=ie.getDisplayName(ie.getCurrentUserTier());return g.createElement(A,{flexDirection:"column",width:"100%"},g.createElement(A,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},g.createElement(C,{color:"white"},i.selectedModel.displayName),g.createElement(C,{color:"gray",dimColor:!0}," • "),g.createElement(C,{color:"gray"},S),g.createElement(C,{color:"gray",dimColor:!0}," • "),g.createElement(C,{color:"white"},y),i.queuedMessages.length>0&&g.createElement(g.Fragment,null,g.createElement(C,{color:"gray",dimColor:!0}," • "),g.createElement(C,{color:"white",inverse:!0,bold:!0}," ",i.queuedMessages.length," "),g.createElement(C,{color:"gray"}," queued")),i.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&g.createElement(g.Fragment,null,g.createElement(C,{color:"gray",dimColor:!0}," • "),g.createElement(C,{color:"blue",inverse:!0,bold:!0}," 📱 ",i.queuedMessages.filter(d=>d.isCrossDeviceTask).length," "),g.createElement(C,{color:"gray"}," cross-device"))),g.createElement(A,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},i.messages.map(d=>g.createElement(ti,{key:d.id,message:d,onSuggestionClick:h=>{a(m=>({...m,input:h}))}}))),i.todoList&&i.todoList.todos.length>0&&i.todoList.todos.some(d=>d.status!=="completed")&&g.createElement(A,{paddingX:2,marginBottom:1},g.createElement(A,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},g.createElement(A,{marginBottom:1},g.createElement(C,{color:"white",bold:!0},"Tasks"),g.createElement(C,{color:"gray"}," • "),g.createElement(C,{color:"gray"},i.todoList.todos.filter(d=>d.status==="completed").length,"/",i.todoList.todos.length)),i.todoList.todos.map((d,h)=>{let m=d.status==="completed"?"✓":d.status==="in_progress"?"⋯":"○",k=d.status==="completed"?"green":d.status==="in_progress"?"blue":"gray";return g.createElement(A,{key:d.id||h},g.createElement(C,{color:k},m),g.createElement(C,{color:"gray"}," "),g.createElement(C,{color:d.status==="completed"?"gray":"white",dimColor:d.status==="completed"},d.status==="in_progress"&&d.activeForm?d.activeForm:d.text))}))),i.isLoading&&g.createElement(A,{paddingX:0,marginBottom:1,flexDirection:"column"},g.createElement(A,null,g.createElement(C,{color:"magenta"},g.createElement(Vo,{type:"dots"})),g.createElement(C,{color:"white"}," ",i.loadingMessage,"… "),g.createElement(C,{color:"white"},"(esc to interrupt)")),g.createElement(A,{marginLeft:2},g.createElement(C,{color:"yellow"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),i.showHelp&&g.createElement(A,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},g.createElement(C,{bold:!0,color:"white"},"Keyboard Shortcuts"),g.createElement(A,{marginTop:1,flexDirection:"column"},g.createElement(C,{color:"white"},"• ",g.createElement(C,{color:"white",bold:!0},"Enter")," ",g.createElement(C,{color:"white"},"Submit message")),g.createElement(C,{color:"white"},"• ",g.createElement(C,{color:"white",bold:!0},"?")," ",g.createElement(C,{color:"white"},"Toggle this help")),g.createElement(C,{color:"white"},"• ",g.createElement(C,{color:"white",bold:!0},"Esc")," ",g.createElement(C,{color:"white"},"Stop generation / Close menus")),g.createElement(C,{color:"white"},"• ",g.createElement(C,{color:"white",bold:!0},"Ctrl+C")," ",g.createElement(C,{color:"white"},"Stop generation / Exit"))),g.createElement(A,{marginTop:1},g.createElement(C,{color:"white"},"Press Esc to close"))),i.showModelMenu&&(()=>{let d=ie.getCurrentUserTier(),h=T=>{switch(T){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},m=z.filter(T=>T.name.startsWith("snowx-o4")||T.name.startsWith("snowx-c")||T.name.startsWith("snowx-h")),k=z.filter(T=>T.name.startsWith("snowx-5")||T.name.startsWith("snowx-o3")||T.name.startsWith("snowx-4")),x=z.filter(T=>T.name.startsWith("snowx-g")),E=T=>T.map(N=>{let B=ie.isModelAccessible(N.name,d),M=h(N.creditMultiplier);return{label:`${B?"":"🔒 "}${N.displayName} ${M}`,value:N.name,isAccessible:B,creditMultiplier:N.creditMultiplier}}),w=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1,creditMultiplier:1},...E(m),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1,creditMultiplier:1},...E(k),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1,creditMultiplier:1},...E(x)];return g.createElement(A,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},g.createElement(C,{bold:!0,color:"white"},"Select Model"),g.createElement(A,null,g.createElement(C,{color:"gray",dimColor:!0},"Tier: ",ie.getDisplayName(d)," • "),g.createElement(C,{color:"green"},"[0.5x]"),g.createElement(C,{color:"gray"}," "),g.createElement(C,{color:"gray",dimColor:!0},"[1x]"),g.createElement(C,{color:"gray"}," "),g.createElement(C,{color:"yellow"},"[2x]"),g.createElement(C,{color:"gray",dimColor:!0}," credits")),g.createElement(A,{marginTop:1},g.createElement(vs,{items:w.map(T=>({label:T.label,value:T.value})),onSelect:T=>{if(T.value.startsWith("_"))return;if(!w.find(M=>M.value===T.value)?.isAccessible){a(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:ie.getAccessDeniedMessage(T.value),timestamp:Date.now()}]}));return}let B=z.find(M=>M.name===T.value);B&&(ke.set("selectedPersonalModel",B.name),a(M=>({...M,selectedModel:B,showModelMenu:!1,messages:[...M.messages,{id:V(),role:"system",content:`Switched to ${B.displayName}`,timestamp:Date.now()}]})))}})),g.createElement(A,{marginTop:1},g.createElement(C,{color:"white"},"Esc to cancel")))})(),i.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"}],h=i.input.startsWith("/")?i.input.substring(1).toLowerCase():"",m=h?d.filter(k=>k.value.toLowerCase().includes(h)):d;return g.createElement(A,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},g.createElement(C,{bold:!0,color:"white"},"Available Commands ",h&&`(filtered: "${h}")`),g.createElement(A,{marginTop:1},g.createElement(vs,{items:m.length>0?m:[{label:"No matching commands",value:""}],onSelect:k=>{k.value&&(a(x=>({...x,showCommandMenu:!1,input:""})),f(`/${k.value}`))}})),g.createElement(A,{marginTop:1},g.createElement(C,{color:"white"},"Esc to cancel")))})(),i.queuedMessages.length>0&&g.createElement(A,{flexDirection:"column",paddingX:2,marginBottom:1},i.queuedMessages.map((d,h)=>g.createElement(A,{key:d.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},g.createElement(A,null,g.createElement(C,{color:"white",bold:!0},h+1),g.createElement(C,{color:"white"}," • "),g.createElement(C,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),g.createElement(A,null,g.createElement(C,{color:"white"},i.queuedMessages.length," message",i.queuedMessages.length>1?"s":""," queued"))),i.queuedMessages.filter(d=>d.isCrossDeviceTask).length>0&&g.createElement(A,{flexDirection:"column",paddingX:2,marginBottom:1},i.queuedMessages.filter(d=>d.isCrossDeviceTask).map((d,h)=>g.createElement(A,{key:`cross-${d.id}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},g.createElement(A,null,g.createElement(C,{color:"blue",bold:!0},"📱 ",h+1),g.createElement(C,{color:"white"}," • "),g.createElement(C,{color:"white"},d.content.length>60?d.content.substring(0,60)+"...":d.content)))),g.createElement(A,null,g.createElement(C,{color:"blue"},i.queuedMessages.filter(d=>d.isCrossDeviceTask).length," cross-device task",i.queuedMessages.filter(d=>d.isCrossDeviceTask).length>1?"s":""," waiting"))),g.createElement(A,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},g.createElement(A,null,g.createElement(C,{color:"white"},"▶ "),g.createElement(C,{color:"white"},i.input,!i.isLoading&&g.createElement(C,{color:"white",inverse:!0}," "))),g.createElement(A,{marginTop:0},g.createElement(C,{color:"white"},i.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),g.createElement(A,{paddingX:2,paddingY:0},g.createElement(C,{color:"white"},"? help · Ctrl+C exit")))}function Yo(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=Rt(e),e}function Zo({suggestions:c,onSelect:e}){return c.length===0?null:g.createElement(A,{flexDirection:"column",marginTop:1},c.map((t,n)=>g.createElement(A,{key:`sug-block-${n}-${t.options.join(",").slice(0,20)}`,flexWrap:"wrap",gap:1},t.options.map(s=>g.createElement(A,{key:`sug-opt-${s.slice(0,30)}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},g.createElement(C,{color:"cyan"},s))))),e&&g.createElement(A,{marginTop:0},g.createElement(C,{color:"gray",dimColor:!0},"Type a suggestion to use it")))}function ei({workingFiles:c}){return c.length===0?null:g.createElement(A,{flexDirection:"column",marginTop:1},g.createElement(A,{marginBottom:0},g.createElement(C,{color:"gray",bold:!0},"Working Files"),g.createElement(C,{color:"gray",dimColor:!0}," (",c.length,")")),g.createElement(A,{flexWrap:"wrap",gap:1},c.map(e=>g.createElement(A,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"gray",paddingX:1,paddingY:0},g.createElement(C,{color:"white"},e.name)))))}function ti({message:c,onSuggestionClick:e}){let{role:t,content:n,tool:s}=c;if(t==="system"){let o=n.split(`
|
|
431
|
+
`);return g.createElement(A,{marginBottom:1,marginTop:1,flexDirection:"column"},g.createElement(A,null,g.createElement(C,{color:"gray",dimColor:!0},"System")),g.createElement(A,{paddingLeft:1,flexDirection:"column"},o.map((i,a)=>g.createElement(C,{key:`sys-${a}-${i.slice(0,20)}`,color:"gray"},i))))}if(t==="user")return g.createElement(A,{marginBottom:1,marginTop:1,flexDirection:"column"},g.createElement(A,null,g.createElement(C,{color:"blue",bold:!0},"You")),g.createElement(A,{paddingLeft:1},g.createElement(C,{color:"white"},n)));if(t==="assistant"){let{suggestions:o,cleanedContent:i}=Qo(n),{workingFiles:a,cleanedContent:l}=Jo(i),u=[],p=l.split(/(\[TOOL:[^\]]+\])/);for(let d of p){if(!d)continue;let h=d.match(/^\[TOOL:([^|\]]+)(?:\|([^\]]*))?\]$/);h?u.push({type:"tool",content:d,toolName:h[1],toolResult:h[2]||""}):d.trim()&&u.push({type:"text",content:d})}let f=d=>{let h=d.toLowerCase();return h.includes("read")?{icon:"◆",color:"cyan"}:h.includes("write")?{icon:"◇",color:"green"}:h.includes("edit")?{icon:"✎",color:"yellow"}:h.includes("bash")||h.includes("command")?{icon:"▸",color:"magenta"}:h.includes("grep")||h.includes("search")?{icon:"⌕",color:"blue"}:h.includes("glob")?{icon:"⊕",color:"blue"}:h.includes("todo")?{icon:"☰",color:"cyan"}:h.includes("task")?{icon:"◈",color:"magenta"}:h.includes("web")?{icon:"◎",color:"blue"}:{icon:"●",color:"gray"}},v=u.some(d=>d.type==="tool"),S=u.filter(d=>d.type==="text"),y=u.filter(d=>d.type==="tool");return g.createElement(A,{marginBottom:1,flexDirection:"column"},g.createElement(A,{marginBottom:0},g.createElement(C,{color:"green",bold:!0},"Orion")),S.map((d,h)=>{let m=d.content.split(`
|
|
432
|
+
`);return g.createElement(A,{key:`text-${h}-${d.content.slice(0,15)}`,flexDirection:"column",paddingLeft:1},m.map((k,x)=>k.trim()===""?g.createElement(C,{key:`ln-${x}-empty`}," "):g.createElement(C,{key:`ln-${x}-${k.slice(0,15)}`,color:"white"},Yo(k))))}),v&&y.length>0&&g.createElement(A,{flexDirection:"column",marginTop:1,paddingLeft:1},y.map((d,h)=>{let m=f(d.toolName||""),k=d.toolResult&&d.toolResult.length>0,x=d.toolResult?.includes("✓"),E=d.toolResult?.includes("✗")||d.toolResult?.includes("error");return g.createElement(A,{key:`tool-${h}-${d.toolName}`},g.createElement(C,{color:m.color},m.icon),g.createElement(C,{color:"gray"}," ",d.toolName),k&&g.createElement(C,{color:E?"red":x?"green":"gray"}," ",d.toolResult),!k&&g.createElement(C,{color:"gray",dimColor:!0}," …"))})),a.length>0&&g.createElement(ei,{workingFiles:a}),o.length>0&&g.createElement(Zo,{suggestions:o,onSelect:e}))}return null}pn();se();se();import U from"chalk";import pi from"inquirer";var De=class{authService;constructor(){this.authService=q.getInstance()}async login(){console.log(U.blue(`
|
|
433
|
+
🔐 Orion Authentication`)),console.log(U.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(U.yellow(`
|
|
434
|
+
📋 To authenticate, please follow these steps:`)),console.log(U.white("1. Open this URL in a browser (on any device):")),console.log(U.cyan.underline(` ${e}`)),console.log(U.white("2. Log in with your Orion account")),console.log(U.white("3. Copy the access token shown after login")),console.log(U.white("4. Paste the token below")),console.log(U.yellow(`
|
|
435
|
+
Paste your access token here:`));let{accessToken:t}=await pi.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(U.gray(`
|
|
436
|
+
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(U.green(`
|
|
437
|
+
✅ Authentication successful!`)),s&&(console.log(U.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(U.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(U.red(`
|
|
438
|
+
❌ Authentication failed. Please try again.`))}catch(n){console.log(U.red(`
|
|
439
|
+
❌ Authentication error: ${n.message}`))}}async logout(){console.log(U.yellow(`
|
|
440
|
+
🔄 Signing out...`)),console.log(U.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(U.green(`
|
|
441
|
+
✅ Successfully signed out`)),console.log(U.gray("All authentication data and settings have been cleared.")),console.log(U.gray('Run "orion auth login" to sign in again.'))):(console.log(U.red(`
|
|
442
|
+
❌ Logout failed`)),console.log(U.gray("Some cleanup operations may have failed, but local data has been cleared.")))}async status(){if(await this.authService.autoAuthenticate(),this.authService.isAuthenticated()){let t=await this.authService.getUserInfo();if(console.log(U.green(`
|
|
443
|
+
✅ Authenticated`)),t){console.log(U.gray("─".repeat(50))),console.log(U.white("User:",t.name||t.username||"N/A")),console.log(U.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(U.white("Subscription:",n)),t.usage&&(console.log(U.gray(`
|
|
444
|
+
Usage:`)),console.log(U.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(U.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(U.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(U.yellow(`
|
|
445
|
+
⚠️ Not authenticated`)),console.log(U.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};ge();var Is=!1;async function mn(){if(Is){console.log("Already running...");return}Is=!0,O.enableCustomUI();let c=ot.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(n){console.error(`
|
|
458
446
|
❌ Failed to initialize services:`,n.message),console.error(`
|
|
459
447
|
💡 Tip: Check your internet connection and Firebase configuration.
|
|
460
448
|
`),process.exit(1)}}(!await e.autoAuthenticate()||!e.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
|
|
461
|
-
`),await new
|
|
449
|
+
`),await new De().login(),e.isAuthenticated()||(console.error(`
|
|
462
450
|
❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
|
|
463
451
|
✨ Starting Orion CLI...
|
|
464
452
|
`)),e.isFirebaseAuthenticated()||(console.error(`
|
|
465
453
|
❌ 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(`
|
|
466
454
|
Please check your connection and try again.
|
|
467
|
-
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),
|
|
468
|
-
`)),process.exit(0)}catch(t){
|
|
455
|
+
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),gi(mi.createElement(bs),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1})}Ae();H();import{EventEmitter as hi}from"events";import fi from"axios";import{execSync as vi}from"child_process";import Ps from"chalk";var Ot=class c extends hi{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):r.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){r.debug("Update check failed:",e)}finally{this.isChecking=!1}}}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`;return(await fi.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let n=e.split(".").map(Number),s=t.split(".").map(Number);for(let o=0;o<3;o++){let i=n[o]||0,a=s[o]||0;if(i>a)return!0;if(i<a)return!1}return!1}async performUpdate(e){try{let t=`npm install -g ${this.packageName}@latest`;r.debug(`Auto-updating from ${this.currentVersion} to ${e}`),vi(t,{stdio:"pipe",encoding:"utf8"}),console.log(Ps.green(`✓ Updated to v${e}`)+Ps.gray(` - restarting...
|
|
456
|
+
`)),process.exit(0)}catch(t){r.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 r.debug("Update check failed:",e),{hasUpdate:!1}}}};import yi from"dotenv";import{fileURLToPath as wi}from"url";import{dirname as Ti,join as Si}from"path";import{readFileSync as ki}from"fs";yi.config();var xi=wi(import.meta.url),Ci=Ti(xi),Ds=JSON.parse(ki(Si(Ci,"..","package.json"),"utf8")),Ei=Ot.getInstance(Ds.version);Ei.checkAndUpdate().catch(()=>{});var He=new bi;He.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Ds.version);He.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await mn()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});He.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(()=>(pn(),Es)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=z.find(i=>i.name===e.model)||z[0];console.log("💭 Sending message...");let o=await n.sendMessage(c,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(Rt(o))}catch(t){te.stopSpinner(!1),console.error(te.formatError(t.message)),process.exit(1)}});var gn=He.command("auth").description("Authentication commands");gn.command("login").description("Login to Orion").action(async()=>{try{await new De().login()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});gn.command("logout").description("Logout from Orion").action(async()=>{try{await new De().logout()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});gn.command("status").description("Check authentication status").action(async()=>{try{await new De().status()}catch(c){console.error(te.formatError(c.message)),process.exit(1)}});He.command("models").description("List available AI models").action(()=>{te.printHeader("Available Models");for(let c of z)console.log(`${te.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?mn().catch(c=>{console.error(te.formatError(c.message)),process.exit(1)}):He.parse(process.argv);
|