@zinley/orion 1.2.13 → 1.2.14
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 +303 -211
- package/package.json +9 -4
package/dist/index.js
CHANGED
|
@@ -1,83 +1,84 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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 ${
|
|
2
|
+
var Xt=Object.defineProperty;var zn=Object.getOwnPropertyDescriptor;var Xn=Object.getOwnPropertyNames;var jn=Object.prototype.hasOwnProperty;var Kn=(l=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(l,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):l)(function(l){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+l+'" is not supported')});var O=(l,e)=>()=>(l&&(e=l(l=0)),e);var ge=(l,e)=>{for(var t in e)Xt(l,t,{get:e[t],enumerable:!0})},Vn=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xn(e))!jn.call(l,n)&&n!==t&&Xt(l,n,{get:()=>e[n],enumerable:!(s=zn(e,n))||s.enumerable});return l};var Qn=l=>Vn(Xt({},"__esModule",{value:!0}),l);var K,$e=O(()=>{"use strict";K=[{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}]});var jt,r,U=O(()=>{"use strict";jt=class l{static instance;logLevel=0;debugMode=!1;static getInstance(){return l.instance||(l.instance=new l),l.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=jt.getInstance()});var ye={};ge(ye,{UserDefaults:()=>Ee});import Je from"fs";import Kt from"path";import Jn from"os";var Vt,Ee,ue=O(()=>{"use strict";U();Vt=class l{static instance;preferencesPath;preferences={};constructor(){let e=Kt.join(Jn.homedir(),".orion");this.preferencesPath=Kt.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return l.instance||(l.instance=new l),l.instance}loadPreferences(){try{if(Je.existsSync(this.preferencesPath)){let e=Je.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=Kt.dirname(this.preferencesPath);Je.existsSync(e)||Je.mkdirSync(e,{recursive:!0}),Je.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)}},Ee=Vt.getInstance()});var le,Qt=O(()=>{"use strict";$e();ue();U();le=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){return["snowx-o4.5","snowx-o3-pro","snowx-5-pro"].includes(e)?1:0}static getCurrentUserTier(){let e=Ee.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Ee.set("userSubscriptionTier",e),r.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),n=t>=s;return r.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${s} (${this.getDisplayName(s)}), Access=${n}`),n}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return K.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 Yn from"axios";import{EventEmitter as Zn}from"events";var Ie,xe,pt=O(()=>{"use strict";Ie="firebase_timestamp",xe=class l extends Zn{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Yn.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:3e4})}static getInstance(){return l.instance||(l.instance=new l),l.instance}async getAccessToken(){let{UserDefaults:e}=await Promise.resolve().then(()=>(ue(),ye));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ie(),As));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let s=await this.getAccessToken();s&&(e.Authorization=s)}}async createDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",o,{headers:n})).data;if(!a.success){let c=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",c),new Error(c)}}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 s={};await this.addAuthorizationHeader(s);let n={collection:e};t&&(n.limit=t.toString());try{let i=(await this.client.get("/documents",{params:n,headers:s})).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,s,n,o,i,a){let c={};await this.addAuthorizationHeader(c);let u={collection:e,field:t,operator:s,value:String(n)};o&&(u.limit=o.toString()),i&&(u.orderBy=i),a&&(u.orderDirection=a);try{let h=(await this.client.get("/documents/query",{params:u,headers:c})).data;if(h.success)return Array.isArray(h.doc)?h.doc:h.doc&&typeof h.doc=="object"?[h.doc]:[];{let f=h.error||"Unknown error";throw new Error(f)}}catch(d){throw d}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let i=(await this.client.get(`/documents/${t}`,{params:n,headers:s})).data;return i.success?i.doc:null}catch(o){throw o}}async updateDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:n})).data;if(!a.success){let c=a.error||"Unknown error";throw new Error(c)}}catch(i){throw i}}async deleteDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let i=(await this.client.delete(`/documents/${t}`,{params:n,headers:s})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,s,n,o){let i=`${e}/${t}/${s}`;return this.createDocument(i,n,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let s=`snowx_conversations/${e}/messages`;try{let n=await this.getDocuments(s);for(let o of n)o.id&&await this.deleteDocument(s,o.id);for(let[o,i]of t.entries()){if(i.role==="system"||i.isStreaming)continue;let a=`message_${o}_${Date.now()}`,c={id:a,role:i.role,content:i.content,timestamp:i.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(s,a,c)}catch{}}}catch(n){throw n}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((n,o)=>{if(n.order!==void 0&&o.order!==void 0)return n.order-o.order;let i=new Date(n.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return i-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,updates:t};try{let i=(await this.client.put("/realtime",n,{headers:s})).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 s={path:e};try{let o=(await this.client.get("/realtime",{params:s,headers:t})).data;if(o.success)return o.doc;{let i=o.error||"Unknown error";throw new Error(i)}}catch(n){throw n}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let o=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!o.success){let i=o.error||"Unknown error";throw new Error(i)}}catch(n){throw n}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=await this.client.get("/realtime",{params:s,headers:t}),o=n.data;if(o.success)return n.data.data;{let i=o.error||"Unknown error";throw new Error(i)}}catch(n){throw n}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let i=(await this.client.post("/realtime",n,{headers:s})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let i=(await this.client.post("/realtime/push",n,{headers:s})).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 Jt={};ge(Jt,{DeviceRegistrationService:()=>ae});import{EventEmitter as eo}from"events";import{v4 as Ds}from"uuid";import Ye from"os";import Ps from"fs/promises";import to from"path";import{execSync as Ze}from"child_process";import so from"crypto";var ae,Ae=O(()=>{"use strict";pt();ie();U();ae=class l extends eo{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=xe.getInstance(),this.authService=G.getInstance(),this.configDir=to.join(Ye.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return l.instance||(l.instance=new l),l.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=Ye.platform();if(e==="darwin")try{let n=Ze("scutil --get ComputerName",{encoding:"utf8"}).trim();if(n)return r.debug(`[DEVICE REG] macOS ComputerName: ${n}`),n}catch{r.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let n=Ze('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(n&&n[1]){let o=n[1].trim();if(o)return r.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{r.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=Ye.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}`),Ye.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Ye.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 c=Ze("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);c&&c[1]&&(t=c[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 Ps.readFile("/etc/machine-id","utf-8").then(i=>i.trim()),r.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Ps.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),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(c=>c.trim()&&c.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=so.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:s}=await Promise.resolve().then(()=>(ue(),ye)),n="snowx_fallback_device_id",o=s.string(n);return o?r.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=Ds(),s.set(n,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:s}=await Promise.resolve().then(()=>(ue(),ye)),n="snowx_fallback_device_id",o=s.string(n);return o?r.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=Ds(),s.set(n,o),r.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,s){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,s);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,s){try{let n=await this.api.getDocument(this.devicesCollection,e);if(n&&n.devices){let o=n.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(c=>c.deviceId===t?{...c,lastSeenAt:Ie,computerName:s,type:"on-device"}:c);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:Ie,lastSeenAt:Ie};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let i={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:Ie,lastSeenAt:Ie}],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:s})}catch(n){throw r.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:n.message,code:n.code}),n}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let s=await this.api.getDocument(this.devicesCollection,e);if(!s||!s.devices||!Array.isArray(s.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let n=s.devices;if(!n.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let i=n.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 As={};ge(As,{AuthService:()=>G});import{EventEmitter as no}from"events";import{signInAnonymously as oo,signInWithEmailAndPassword as ro,createUserWithEmailAndPassword as io,signOut as ao,onAuthStateChanged as Ns,updateProfile as co,signInWithCustomToken as lo}from"firebase/auth";import De from"axios";import Yt from"fs/promises";import Rs from"path";import uo from"os";var G,ie=O(()=>{"use strict";Qt();U();G=class l extends no{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=Rs.join(uo.homedir(),".orion-cli","auth.json")}static getInstance(){return l.instance||(l.instance=new l),l.instance}async initializeTokenFile(){try{let e=Rs.dirname(this.tokenFilePath);await Yt.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ue(),ye)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let n=await Yt.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(n);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,s=o.token,await Yt.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&s){let n={token:s,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=n,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(n)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(n)}this.emit("authenticated",n)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ue(),ye));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(()=>(ue(),ye));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,Ns(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}le.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(ue(),ye));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),r.debug(`User tier updated: ${le.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 oo(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await ro(this.auth,e,t);return this.currentUser=s.user,!0}catch(s){return console.error("❌ Failed to sign in with email:",s.message),!1}}async signUpWithEmail(e,t,s){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await io(this.auth,e,t);return this.currentUser=n.user,s&&await co(n.user,{displayName:s}),!0}catch(n){return console.error("❌ Failed to sign up with email:",n.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(Ae(),Jt));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await ao(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(()=>(Ae(),Jt));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ue(),ye)),s=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let i of s)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 De.post(`${this.snowxAuthEndpoint}/login`,e):t=await De.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let s={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(s),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await De.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(()=>(ue(),ye));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let s=await new Promise(n=>{let o=!1,i,a=Ns(this.auth,async c=>{if(!o)if(o=!0,clearTimeout(i),a(),c)try{let u=await c.getIdToken(!0);n(u)}catch{n(null)}else n(null)});i=setTimeout(()=>{o||(o=!0,a(),n(null))},2e3)});if(s)return s}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 s=this.parseFirebaseIdToken(t);return s&&Date.now()<=s.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(s){return r.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.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 lo(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 s=4-t;console.log(`📡 [AUTH-API] Attempt ${s}/3: Getting custom token for user: ${e}`),r.debug(`Getting custom token from API for user: ${e} (attempt ${s}/3)`);let n="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},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: ${n}`);try{let c=await De.post(n,o,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${c.status}`),c.status!==200){let d=c.data?.message||`HTTP ${c.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${d}`),new Error(`Custom token API failed: ${d}`)}let u=c.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(c){if(console.error(`❌ [AUTH-API] Request failed on attempt ${s}/3`),console.error(`❌ [AUTH-API] Error message: ${c.message}`),console.error(`❌ [AUTH-API] Error code: ${c.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${c.response?.status||"none"}`),c.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(c.response.data)}`),r.error("Failed to get custom token:",{attempt:s,error:c.message,code:c.code,status:c.response?.status,responseData:c.response?.data}),t>0&&(c.code==="ECONNABORTED"||c.code==="ETIMEDOUT"||c.code==="ECONNREFUSED"||c.code==="ENOTFOUND"||c.response?.status>=500&&c.response?.status<600)){let d=Math.pow(2,s)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),r.debug(`Retrying in ${d}ms...`),await new Promise(h=>setTimeout(h,d)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),c}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let s=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:s.user_id||s.sub,email:s.email,name:s.name,exp:s.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let s={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(s);try{let n=await this.getUserProfileWithIdToken(e,t.userId);n&&(this.authToken.tier=n.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let s=await De.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(s.data?.success&&s.data?.doc){let n=s.data.doc,o=n.subscription?.tier??0;return{id:t,email:n.email,tier:o}}return null}catch(s){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${s.response?.status||s.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await De.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let s=t.data.data,n=s.id||s.uid||s.user_id||s.userId||s.email;if(!n)throw new Error("No user ID found in API response");let o={token:e,userId:n,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=s,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(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",n),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await De.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),s=t===1?1:t===2?2:0;return le.isModelAccessible(e,s)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await De.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,s=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=s,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:s}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var Os={};ge(Os,{MessageQueueManager:()=>he});import{EventEmitter as po}from"events";var he,_e=O(()=>{"use strict";U();he=class l extends po{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return l.instance||(l.instance=new l),l.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 Fs,decode as $s,isWithinTokenLimit as _s,countTokens as mo}from"gpt-tokenizer/encoding/cl100k_base";var Me,go,ho,de,Le=O(()=>{"use strict";Me=25e3,go=1400,ho=17e3,de=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??Me,this.previewTokens=e?.previewTokens??go,this.maxContentTokens=e?.maxContentTokens??ho}count(e){return e?mo(e):0}encode(e){return e?Fs(e):[]}decode(e){return!e||e.length===0?"":$s(e)}isWithinLimit(e,t){return e?_s(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 s=t??this.maxResponseTokens,n=_s(e,s);if(n!==!1)return{text:e,tokens:n,truncated:!1};let i=Fs(e).slice(0,s);return{text:$s(i),tokens:s,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let s=t??this.previewTokens,n=this.count(e);if(n<=s)return{preview:e,totalTokens:n,previewTokens:n,remainingTokens:0};let{text:o,tokens:i}=this.truncate(e,s);return{preview:o,totalTokens:n,previewTokens:i,remainingTokens:n-i}}truncateContent(e,t){let s=t??this.maxContentTokens,n=this.truncate(e,s);return n.truncated?n.text+`
|
|
4
|
+
... [Content truncated at ${n.tokens.toLocaleString()} tokens]`:e}truncateOutput(e,t){let s=t??this.maxResponseTokens,n=this.truncate(e,s);return n.truncated?n.text+`
|
|
5
5
|
|
|
6
|
-
[Output truncated at ${
|
|
6
|
+
[Output truncated at ${n.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,s){let{preview:n,totalTokens:o,previewTokens:i,remainingTokens:a}=this.generatePreview(e,s?.previewTokens??this.previewTokens),c=`Response too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
|
|
7
7
|
|
|
8
|
-
`;return
|
|
9
|
-
`,
|
|
8
|
+
`;return c+=`TEMP FILE PATH: ${t}
|
|
9
|
+
`,c+=`Use read_file, grep, cat, or other tools to access the full content.
|
|
10
10
|
|
|
11
|
-
`,
|
|
12
|
-
`,
|
|
13
|
-
`,
|
|
14
|
-
${"─".repeat(50)}`,
|
|
15
|
-
... (${a.toLocaleString()} more tokens available in temp file)`),
|
|
11
|
+
`,c+=`PREVIEW (first ${i.toLocaleString()} tokens):
|
|
12
|
+
`,c+=`${"─".repeat(50)}
|
|
13
|
+
`,c+=n,a>0&&(c+=`
|
|
14
|
+
${"─".repeat(50)}`,c+=`
|
|
15
|
+
... (${a.toLocaleString()} more tokens available in temp file)`),c+=`
|
|
16
16
|
|
|
17
|
-
To read full content: use tools like 'read_file' with path above`,
|
|
17
|
+
To read full content: use tools like 'read_file' with path above`,c}formatLargeFileMessage(e,t,s){let{preview:n,totalTokens:o,previewTokens:i,remainingTokens:a}=this.generatePreview(e,s?.previewTokens??this.previewTokens),c=`File too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit).
|
|
18
18
|
|
|
19
|
-
`;return
|
|
19
|
+
`;return c+=`FILE PATH: ${t}
|
|
20
20
|
|
|
21
|
-
`,
|
|
21
|
+
`,c+=`This file is already on disk. Use Read tool with offset and limit parameters.
|
|
22
22
|
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
25
|
-
`,
|
|
26
|
-
${"─".repeat(50)}`,
|
|
27
|
-
... (${a.toLocaleString()} more tokens)`),
|
|
28
|
-
`);
|
|
29
|
-
|
|
23
|
+
`,c+=`PREVIEW (first ${i.toLocaleString()} tokens):
|
|
24
|
+
`,c+=`${"─".repeat(50)}
|
|
25
|
+
`,c+=n,a>0&&(c+=`
|
|
26
|
+
${"─".repeat(50)}`,c+=`
|
|
27
|
+
... (${a.toLocaleString()} more tokens)`),c}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as fo}from"events";var Ms,Ls,vo,bo,To,et,Us,Zt=O(()=>{"use strict";U();Ms=10,Ls=2e3,vo=5e3,bo=200,To=3e3,et=class l extends fo{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),r.debug("[SubAgentManager] Initialized")}static getInstance(){return l.instance||(l.instance=new l),l.instance}handleEvent(e){let{type:t}=e;switch(t){case"spawn_agents_started":this.handleSpawnStarted(e);break;case"sub_agent_started":this.handleAgentStarted(e);break;case"sub_agent_streaming":this.handleAgentStreaming(e);break;case"sub_agent_completed":this.handleAgentCompleted(e);break;case"spawn_agents_completed":this.handleSpawnCompleted(e);break;default:r.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:s}=e;if(!t||!s){r.debug("[SubAgentManager] Invalid spawn_agents_started event");return}this.cleanupOldOperations();let n={operationId:t,totalAgents:s,agents:new Map,status:"starting",startTime:new Date};for(let o=1;o<=s;o++)n.agents.set(o,{agentNumber:o,task:"",status:"pending"});this.operations.set(t,n),r.debug(`[SubAgentManager] Spawn started: ${t} with ${s} agents`),this.emit("spawn_started",{operationId:t,totalAgents:s}),this.emitProgressUpdate(t)}handleAgentStarted(e){let{operationId:t,agentNumber:s,task:n}=e;if(!t||!s)return;let o=this.operations.get(t);if(!o){r.debug(`[SubAgentManager] Operation not found: ${t}`);return}o.status==="starting"&&(o.status="running");let i=this.truncateString(n||"",bo);o.agents.set(s,{agentNumber:s,task:i,status:"running",startTime:new Date}),r.debug(`[SubAgentManager] Agent ${s} started: ${i.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:s,task:i}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:s,content:n}=e;if(!t||!s||!n)return;let o=this.operations.get(t);if(!o)return;let i=o.agents.get(s);if(!i)return;let c=(i.streamingContent||"")+n;c.length>Ls?i.streamingContent=c.slice(-Ls):i.streamingContent=c,this.emit("agent_streaming",{operationId:t,agentNumber:s,content:i.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:s,result:n,error:o}=e;if(!t||!s)return;let i=this.operations.get(t);if(!i)return;let a=i.agents.get(s);if(!a)return;let c=o?"failed":"completed";a.status=c,a.endTime=new Date,a.result=this.truncateString(n||"",vo),a.error=o;let u=a.startTime?(a.endTime.getTime()-a.startTime.getTime())/1e3:0;r.debug(`[SubAgentManager] Agent ${s} ${c} (${u.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:s,status:c,duration:u}),this.emitProgressUpdate(t)}handleSpawnCompleted(e){let{operationId:t}=e;if(!t)return;let s=this.operations.get(t);if(!s)return;let n=Array.from(s.agents.values()),o=n.some(d=>d.status==="failed"),i=n.every(d=>d.status==="completed"||d.status==="failed");s.status=o?"failed":"completed",s.endTime=new Date;let a=(s.endTime.getTime()-s.startTime.getTime())/1e3,c=n.filter(d=>d.status==="completed").length,u=n.filter(d=>d.status==="failed").length;r.debug(`[SubAgentManager] Spawn completed: ${c} success, ${u} failed (${a.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:s.status,duration:a,successCount:c,failCount:u,totalAgents:s.totalAgents}),this.emitProgressUpdate(t),this.scheduleCleanup(t)}emitProgressUpdate(e){let t=this.operations.get(e);if(!t)return;let s=Array.from(t.agents.values()),n=s.filter(c=>c.status==="pending").length,o=s.filter(c=>c.status==="running").length,i=s.filter(c=>c.status==="completed").length,a=s.filter(c=>c.status==="failed").length;this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:n,running:o,completed:i,failed:a,agents:s.map(c=>({agentNumber:c.agentNumber,task:c.task,status:c.status}))})}getProgressString(e){let t=this.operations.get(e);if(!t)return"";let s=Array.from(t.agents.values()),n=s.filter(d=>d.status==="pending").length,o=s.filter(d=>d.status==="running").length,i=s.filter(d=>d.status==="completed").length,a=s.filter(d=>d.status==="failed").length,u=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${i}/${t.totalAgents} complete`;return o>0&&(u+=` (${o} running)`),a>0&&(u+=` [${a} failed]`),u}getAgentListString(e){let t=this.operations.get(e);if(!t)return"";let s=[],n=Array.from(t.agents.values()).sort((o,i)=>o.agentNumber-i.agentNumber);for(let o of n){let i={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[o.status]||"❓",a=o.task?`: ${o.task.substring(0,60)}${o.task.length>60?"...":""}`:"";s.push(` ${i} Agent ${o.agentNumber}${a}`),o.error&&s.push(` └─ Error: ${o.error.substring(0,80)}${o.error.length>80?"...":""}`)}return s.join(`
|
|
28
|
+
`)}cleanupOldOperations(){if(this.operations.size<Ms)return;let e=[];for(let[s,n]of this.operations)(n.status==="completed"||n.status==="failed")&&e.push({id:s,endTime:n.endTime?.getTime()||n.startTime.getTime()});e.sort((s,n)=>s.endTime-n.endTime);let t=e.slice(0,Math.max(1,e.length-Ms+1));for(let{id:s}of t){this.operations.delete(s);let n=this.cleanupTimers.get(s);n&&(clearTimeout(n),this.cleanupTimers.delete(s)),r.debug(`[SubAgentManager] Cleaned up old operation: ${s}`)}}scheduleCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let s=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),r.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},To);this.cleanupTimers.set(e,s)}truncateString(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}getOperations(){return new Map(this.operations)}getActiveOperations(){return Array.from(this.operations.values()).filter(e=>e.status==="starting"||e.status==="running")}getOperation(e){return this.operations.get(e)}hasActiveOperations(){return this.getActiveOperations().length>0}clear(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),r.debug("[SubAgentManager] Cleared all operations")}},Us=et.getInstance()});var mt,Ws=O(()=>{"use strict";U();mt=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 s=e.toLowerCase();for(let[n,o]of this.tools.entries())if(n.toLowerCase()===s)return o}async executeTool(e,t,s,n){let o=this.getTool(e);if(!o)return 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,s,n),c=Date.now()-i;r.debug(`[ToolRegistry] Tool ${e} completed in ${c}ms`);let u=a.map(d=>d.text||"").join(`
|
|
29
|
+
`);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(),s=[];for(let n of this.tools.keys())n.toLowerCase()===t&&s.push(n);for(let n of s)this.tools.delete(n);r.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),r.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var Bs={};ge(Bs,{ToolDisplay:()=>$});import X from"chalk";var $,fe=O(()=>{"use strict";$=class l{static customUIMode=!1;static enableCustomUI(){l.customUIMode=!0}static disableCustomUI(){l.customUIMode=!1}static start(e,t,s){if(l.customUIMode)return;let n=this.getToolPrefix(e);if(console.log(X.cyan(`
|
|
30
|
+
${n} ${X.bold(e)}`)),t&&console.log(X.gray(` ${t}`)),s){let o=s.length>120?s.substring(0,120)+X.gray("..."):s;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(l.customUIMode)return;let{toolName:t,output:s,success:n,executionTime:o,truncateLines:i=50}=e,a=s||"";s&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(s,i):t.toLowerCase().includes("write")?a=this.formatWriteOutput(s,i):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(s,i):a=this.formatGenericOutput(s,i)),a&&a.trim()&&console.log(a);let c=n?X.green("✓"):X.red("✗"),u=n?X.green("SUCCESS"):X.red("FAILED"),d=o?X.gray(` (${o}ms)`):"";console.log(`${c} ${u}${d}
|
|
30
31
|
`)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
|
|
31
|
-
`),u=a.slice(0,20).map(
|
|
32
|
+
`),u=a.slice(0,20).map(d=>X.gray(" ")+d).join(`
|
|
32
33
|
`);return a.length>20&&(u+=`
|
|
33
|
-
`+X.gray(` ... (${a.length-20} more lines)`)),u}let
|
|
34
|
-
`),
|
|
35
|
-
`);let i=
|
|
34
|
+
`+X.gray(` ... (${a.length-20} more lines)`)),u}let s=e.split(`
|
|
35
|
+
`),n=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";n&&(o+=X.gray(" ")+X.dim(n[1])+`
|
|
36
|
+
`);let i=s.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
37
|
`),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
|
|
38
|
-
`).filter(i=>i.trim());if(
|
|
39
|
-
`);let o=
|
|
38
|
+
`+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 s=e.split(`
|
|
39
|
+
`).filter(i=>i.trim());if(s.length===0)return"";if(s.length<=t)return s.map(i=>X.gray(" ")+X.dim(i)).join(`
|
|
40
|
+
`);let o=s.slice(0,t).map(i=>X.gray(" ")+X.dim(i)).join(`
|
|
40
41
|
`);return o+=`
|
|
41
|
-
`+X.gray(` ... (${
|
|
42
|
-
${X.red("✗")} ${X.red.bold(e)} ${X.red("ERROR")}`),console.log(X.gray(" ")+X.white(t)),console.log(""))}}});import
|
|
42
|
+
`+X.gray(` ... (${s.length-t} more lines)`),o}static error(e,t){l.customUIMode||(console.log(`
|
|
43
|
+
${X.red("✗")} ${X.red.bold(e)} ${X.red("ERROR")}`),console.log(X.gray(" ")+X.white(t)),console.log(""))}}});import qs from"os";import es from"path";function gt(){return process.platform==="win32"}function Oe(l){if(!l)return l;let e=l.trim();return e.startsWith("~")&&(e=e.replace(/^~/,qs.homedir())),gt()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,qs.homedir())),!gt()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),gt()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Ue(l){if(!l||typeof l!="string")return{valid:!1,error:"File path is required"};let e=Oe(l);if(gt()){let s=es.basename(e).split(".")[0].toUpperCase();if(yo.includes(s))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${s}`}}return es.isAbsolute(e)?es.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${l}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${l}"
|
|
43
44
|
|
|
44
45
|
Path must be absolute (start with / on Unix or C:\\ on Windows)
|
|
45
46
|
|
|
46
47
|
Wrong: Downloads/file.pdf
|
|
47
|
-
Correct: /Users/username/Downloads/file.pdf`}}var
|
|
48
|
-
`),
|
|
48
|
+
Correct: /Users/username/Downloads/file.pdf`}}var yo,ht=O(()=>{"use strict";yo=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import Hs from"path";var wo,So,ft,Gs=O(()=>{"use strict";U();fe();ht();Le();wo=["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"},ft=class{toolNames=["read","Read"];async execute(e,t,s,n){let o=s.file_path||s.path,i=s.offset,a=s.limit;if(!o)throw new Error("Missing file_path or path argument");let c=Oe(o),u=Ue(c);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];r.debug(`[ReadFileTool] Reading file: ${c}${i!==void 0?`, offset: ${i}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();$.start("Read",s.description,c);try{let h=await import("fs/promises");try{await h.access(c)}catch{return[{type:"text",text:`Error: File does not exist at path: ${c}`}]}let f=await h.stat(c);if(f.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${c}`}];let y=Hs.extname(c).substring(1).toLowerCase();if(wo.includes(y)){r.debug(`[ReadFileTool] Image file detected: ${c}`);let D=(await h.readFile(c)).toString("base64"),P=So[y]||"application/octet-stream",v=Hs.basename(c);r.debug(`[ReadFileTool] Image converted to base64: ${v} (${D.length} chars)`);let A=Date.now()-d;return $.result({toolName:"Read",filePath:c,output:`Image loaded: ${v}`,success:!0,executionTime:A}),[{type:"image_url",image_url:{url:`data:${P};base64,${D}`}}]}let k=await h.readFile(c,"utf-8"),p=k.length,g=k.split(`
|
|
49
|
+
`),b=g.length,C=Math.max(i??0,0),S=new de;if(i===void 0&&a===void 0&&S.exceedsResponseLimit(k)){let _=S.count(k),D=f.size/1024,P=D/1024,v=P>=1?`${P.toFixed(2)} MB`:`${D.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
|
|
49
50
|
|
|
50
51
|
File Information:
|
|
51
|
-
- Path: ${
|
|
52
|
-
- Size: ${
|
|
53
|
-
- Total Lines: ${
|
|
54
|
-
- Token Limit: ${
|
|
52
|
+
- Path: ${c}
|
|
53
|
+
- Size: ${v} (${_.toLocaleString()} tokens)
|
|
54
|
+
- Total Lines: ${b}
|
|
55
|
+
- Token Limit: ${Me.toLocaleString()}
|
|
55
56
|
|
|
56
57
|
Suggested Solutions:
|
|
57
58
|
1. Read specific lines using offset and limit:
|
|
58
|
-
Read(path: "${
|
|
59
|
+
Read(path: "${c}", offset: 0, limit: 2000)
|
|
59
60
|
|
|
60
61
|
2. Search for specific content:
|
|
61
|
-
Grep(pattern: "your_search_term", path: "${
|
|
62
|
+
Grep(pattern: "your_search_term", path: "${c}")
|
|
62
63
|
|
|
63
64
|
3. Read in chunks:
|
|
64
|
-
- Lines 0-2000: Read(path: "${
|
|
65
|
-
- Lines 2000-4000: Read(path: "${
|
|
65
|
+
- Lines 0-2000: Read(path: "${c}", offset: 0, limit: 2000)
|
|
66
|
+
- Lines 2000-4000: Read(path: "${c}", offset: 2000, limit: 2000)
|
|
66
67
|
- And so on...
|
|
67
68
|
|
|
68
|
-
The file has ${
|
|
69
|
-
`),
|
|
69
|
+
The file has ${b.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(b===0||k.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(C>=b)return[{type:"text",text:`Error: Offset ${C} is beyond file length. File has ${b} total lines. Try a smaller offset (0 to ${b-1}).`}];let x=a!==void 0?Math.min(C+a,b):b,I=g.slice(C,x),w=I.map((_,D)=>`${(C+D+1).toString().padStart(6," ")} ${_}`).join(`
|
|
70
|
+
`),M=w;if(i!==void 0||a!==void 0){let _=`
|
|
70
71
|
|
|
71
|
-
[Read ${
|
|
72
|
+
[Read ${I.length} lines (${C+1}-${x}) of ${b} total lines]`;M=w+_}let j=Date.now()-d;return $.result({toolName:"Read",filePath:c,output:M,success:!0,executionTime:j}),[{type:"text",text:M}]}catch(h){r.debug(`[ReadFileTool] Failed to read file: ${h.message}`);let f;h.code==="ENOENT"?f=`Error: File does not exist at path: ${c}`:h.code==="EACCES"?f=`Error: Permission denied. Cannot read file: ${c}`:h.code==="EISDIR"?f=`Error: Path is a directory, not a file: ${c}`:f=`Error reading file: ${h.message}`;let y=Date.now()-d;return $.result({toolName:"Read",filePath:c,output:f,success:!1,executionTime:y}),[{type:"text",text:f}]}}}});import vt from"fs/promises";import Co from"form-data";import ts from"axios";import ss from"path";var bt,zs=O(()=>{"use strict";U();fe();ie();bt=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,s,n){let o=s.path;if(!o)throw new Error("Missing path argument");r.debug(`[ReadSpecialFileTool] Converting file: ${o}`);let i=Date.now();$.start("ReadSpecialFile",s.description,o);try{try{await vt.access(o)}catch{return[{type:"text",text:`Error: File does not exist at path: ${o}`}]}let a=ss.extname(o).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let C=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.
|
|
72
73
|
|
|
73
|
-
Supported file types: ${
|
|
74
|
+
Supported file types: ${C}`}]}let c=await vt.stat(o),u=ss.basename(o);if(r.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${c.size} bytes)`),this.imageExtensions.includes(a)){r.debug(`[ReadSpecialFileTool] Image file detected: ${o}`);let S=(await vt.readFile(o)).toString("base64"),x=this.imageMimeTypes[a]||"application/octet-stream";r.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${S.length} chars)`);let I=Date.now()-i;return $.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:I}),[{type:"image_url",image_url:{url:`data:${x};base64,${S}`}}]}let d=await this.uploadToBatchAPI(o,u);r.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let h=await this.pollBatchStatus(d);r.debug("[ReadSpecialFileTool] Conversion completed");let f=h.files[0];if(!f||f.status==="failed"){let C=f?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${C}`}]}let y=await this.fetchFileContent(f.file_id);if(!y.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let T=c.size/1024,k=T/1024,p=k>=1?`${k.toFixed(2)} MB`:`${T.toFixed(2)} KB`,g=`# File: ${u}
|
|
74
75
|
**Type:** ${a.toUpperCase()}
|
|
75
|
-
**Size:** ${
|
|
76
|
+
**Size:** ${p}
|
|
76
77
|
**Conversion:** ✅ Successful
|
|
77
78
|
|
|
78
79
|
---
|
|
79
80
|
|
|
80
|
-
${
|
|
81
|
+
${y.markdown_content}`,b=Date.now()-i;return $.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${p})`,success:!0,executionTime:b}),[{type:"text",text:g}]}catch(a){r.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let c=`Error converting file: ${a.message}
|
|
81
82
|
|
|
82
83
|
This could be due to:
|
|
83
84
|
• File corruption or invalid format
|
|
@@ -85,37 +86,37 @@ This could be due to:
|
|
|
85
86
|
• Unsupported document structure
|
|
86
87
|
• File is password-protected or encrypted
|
|
87
88
|
|
|
88
|
-
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-i;return
|
|
89
|
-
`),
|
|
90
|
-
`;a.length>8&&(
|
|
89
|
+
For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-i;return $.result({toolName:"ReadSpecialFile",filePath:o,output:c,success:!1,executionTime:u}),[{type:"text",text:c}]}}async uploadToBatchAPI(e,t){let s=await vt.readFile(e),n=ss.extname(t).substring(1).toLowerCase(),i=await G.getInstance().getFirebaseIdToken(),a=new Co;a.append("files",s,{filename:t,contentType:this.getMimeType(n)});try{let c={...a.getHeaders()};i&&(c.Authorization=`Bearer ${i}`);let u=await ts.post(`${this.baseEndpoint}/convert-batch`,a,{headers:c,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(c){throw c.response?new Error(`Upload failed (HTTP ${c.response.status}): ${JSON.stringify(c.response.data)}`):new Error(`Upload failed: ${c.message}`)}}async pollBatchStatus(e){let s=await G.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);for(let o=1;o<=this.maxPollAttempts;o++)try{let a=(await ts.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:n})).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 s=await G.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);try{let o=await ts.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:n});if(o.data.status==="failed")throw new Error(o.data.error||"Unknown conversion error");return o.data}catch(o){throw o.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${o.message}`)}}getMimeType(e){switch(e.toLowerCase()){case"pdf":return"application/pdf";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"doc":return"application/msword";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xls":return"application/vnd.ms-excel";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"ppt":return"application/vnd.ms-powerpoint";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var Tt,Xs=O(()=>{"use strict";U();fe();ht();Tt=class{toolNames=["write","Write","write_file"];async execute(e,t,s,n){let o=s.file_path,i=s.content,a=s.edits;if(!o)throw new Error("Missing file_path argument");let c=Oe(o),u=Ue(c);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let d=Date.now();return $.start("Write",s.description,c),i!=null?await this.executeSimpleWrite(c,i,d):await this.executeEditsMode(c,a,d)}async executeSimpleWrite(e,t,s){r.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let n=await import("fs/promises"),i=(await import("path")).dirname(e);await n.mkdir(i,{recursive:!0}),await n.writeFile(e,t,"utf-8");let a=t.split(`
|
|
90
|
+
`),c="";for(let h=0;h<Math.min(a.length,8);h++)c+=`+ ${a[h]}
|
|
91
|
+
`;a.length>8&&(c+=`+ ...
|
|
91
92
|
|
|
92
|
-
(${a.length-8} more lines)`);let u=
|
|
93
|
-
`),
|
|
94
|
-
`;return
|
|
93
|
+
(${a.length-8} more lines)`);let u=c.trim();r.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let d=Date.now()-s;return $.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:d}),[{type:"text",text:u}]}catch(n){r.debug(`[WriteFileTool] Failed to write file: ${n.message}`);let o=`Error writing file: ${n.message}`,i=Date.now()-s;return $.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:i}),[{type:"text",text:o}]}}async executeEditsMode(e,t,s){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");r.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let n=await import("fs/promises"),o=await import("path");for(let y=0;y<t.length;y++){let T=t[y];if(!T||typeof T!="object")throw new Error(`Edit operation ${y+1} must be an object with 'search' and 'replace' fields`);if(!T.hasOwnProperty("search")||typeof T.search!="string")throw new Error(`Edit operation ${y+1} missing required 'search' field (must be string)`);if(!T.hasOwnProperty("replace")||typeof T.replace!="string")throw new Error(`Edit operation ${y+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 y=o.dirname(e);await n.mkdir(y,{recursive:!0}),await n.writeFile(e,a,"utf-8");let T=a.split(`
|
|
94
|
+
`),k="";for(let p=0;p<Math.min(T.length,8);p++)k+=`+ ${T[p]}
|
|
95
|
+
`;return T.length>8&&(k+=`+ ...
|
|
95
96
|
|
|
96
|
-
(${
|
|
97
|
-
`),
|
|
98
|
-
`;return
|
|
97
|
+
(${T.length-8} more lines)`),r.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:k.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 n.readFile(e,"utf-8"),r.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(y){throw y.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: ${y.message}`)}}let c=0,u=a,d=[];for(let y=0;y<t.length;y++){let T=t[y];if(r.debug(`[WriteFileTool] Applying edit ${y+1}/${t.length}`),T.search==="")if(i){d.push({index:y+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{r.debug("[WriteFileTool] Rewriting entire existing file"),u=T.replace,d.push({index:y+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),c++;continue}let k=u.indexOf(T.search);if(k!==-1)u=u.substring(0,k)+T.replace+u.substring(k+T.search.length),r.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:y+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),c++;else{let p=`Search string not found: '${T.search}'`;return d.push({index:y+1,success:!1,message:p,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${y+1}: '${T.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(b=>b.success).length}\\n- Failed: ${d.filter(b=>!b.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(b=>`${b.success?"✅":"❌"} Edit ${b.index}: ${b.message}`).join("\\n")}]}}await n.writeFile(e,u,"utf-8"),r.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let h=u.split(`
|
|
98
|
+
`),f="";for(let y=0;y<Math.min(h.length,8);y++)f+=`+ ${h[y]}
|
|
99
|
+
`;return h.length>8&&(f+=`+ ...
|
|
99
100
|
|
|
100
|
-
(${
|
|
101
|
+
(${h.length-8} more lines)`),[{type:"text",text:f.trim()}]}catch(n){return r.debug(`[WriteFileTool] Failed to write file: ${n.message}`),[{type:"text",text:`Error writing file: ${n.message}`}]}}}});var yt,js=O(()=>{"use strict";U();fe();ht();yt=class{toolNames=["edit","Edit"];async execute(e,t,s,n){let o=s.file_path,i=s.old_string,a=s.new_string,c=s.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=Oe(o),d=Ue(u);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];r.debug(`[EditFileTool] Editing file: ${u}`);let h=Date.now();$.start("Edit",s.description,u);try{let f=await import("fs/promises"),y=await f.readFile(u,"utf-8"),T,k=0;if(c)for(T=y;T.includes(i);)T=T.replace(i,a),k++;else y.includes(i)?(T=y.replace(i,a),k=1):T=y;if(k===0){let S=`No matches found for the specified old_string in file: ${u}`,x=Date.now()-h;return $.result({toolName:"Edit",filePath:u,output:S,success:!1,executionTime:x}),[{type:"text",text:S}]}await f.writeFile(u,T,"utf-8");let p=`Successfully edited file: Replaced ${k} occurrence(s)`;r.debug(`[EditFileTool] ${p}`);let g=Date.now()-h,b=(await import("chalk")).default,C=`${b.red("- "+i.split(`
|
|
101
102
|
`).slice(0,5).join(`
|
|
102
103
|
- `))}
|
|
103
|
-
${
|
|
104
|
+
${b.green("+ "+a.split(`
|
|
104
105
|
`).slice(0,5).join(`
|
|
105
106
|
+ `))}
|
|
106
107
|
|
|
107
|
-
Replaced ${
|
|
108
|
+
Replaced ${k} occurrence(s)`;return $.result({toolName:"Edit",filePath:u,output:C,success:!0,executionTime:g}),[{type:"text",text:p}]}catch(f){r.debug(`[EditFileTool] Failed to edit file: ${f.message}`);let y=`Error editing file: ${f.message}`,T=Date.now()-h;return $.result({toolName:"Edit",filePath:u,output:y,success:!1,executionTime:T}),[{type:"text",text:y}]}}}});var wt,Ks=O(()=>{"use strict";U();wt=class{toolNames=["upload_file"];async execute(e,t,s,n){let o=s.file_path;if(!o)throw new Error("Missing file_path argument");return r.debug(`[UploadFileTool] Upload file not implemented for CLI: ${o}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${o}`}]}}});import ns from"fs/promises";import ko from"path";import Eo from"form-data";import xo from"axios";var St,Vs=O(()=>{"use strict";U();fe();ie();St=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let o=s.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let i=Date.now();$.start("DeployZipHTML",s.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let w=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 ${w} seconds.`)}r.debug(`[DeployZipHTML] Deploying HTML project: ${o}`);try{await ns.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 c=await ns.stat(o),u=100*1024*1024;if(c.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await ns.readFile(o),h=ko.basename(o).replace(/[\r\n\t"']/g,"_");r.debug(`[DeployZipHTML] File: ${h}, Size: ${c.size} bytes`);let y=await G.getInstance().getFirebaseIdToken();if(!y)throw new Error("User must be authenticated to deploy projects");let T=new Eo;T.append("zipFile",d,{filename:h,contentType:"application/zip"});let k="https://snowx.ai/api/v2/deploy-zip";r.debug(`[DeployZipHTML] Uploading to ${k}`);let p=await xo.post(k,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${y}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(p.status!==200&&p.status!==201)throw new Error(`Deployment failed with status ${p.status}: ${JSON.stringify(p.data)}`);let g=p.data;r.debug("[DeployZipHTML] Deployed successfully"),r.debug(`[DeployZipHTML] Response: ${JSON.stringify(g,null,2)}`);let b=g.data?.deployUrl||g.deployUrl||g.url||g.deploymentUrl||g.site_url||g.siteUrl||g.website_url,C=g.data?.deployId||g.deployId||g.projectId||g.deploymentId,S=g.data?.siteId||g.siteId;this.deployCount++;let x=`# HTML Project Deployed Successfully!
|
|
108
109
|
|
|
109
|
-
**Deployment URL**: ${
|
|
110
|
+
**Deployment URL**: ${b}
|
|
110
111
|
|
|
111
|
-
**Project**: ${
|
|
112
|
+
**Project**: ${h}
|
|
112
113
|
**Type**: Static HTML
|
|
113
|
-
${
|
|
114
|
-
`:""}${
|
|
114
|
+
${C?`**Deploy ID**: ${C}
|
|
115
|
+
`:""}${S?`**Site ID**: ${S}
|
|
115
116
|
`:""}
|
|
116
117
|
Your site is now live and accessible!
|
|
117
118
|
|
|
118
|
-
${
|
|
119
|
+
${g.message||""}`,I=Date.now()-i;return $.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${b}`,success:!0,executionTime:I}),[{type:"text",text:x}]}catch(a){r.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let c=`HTML deployment failed
|
|
119
120
|
|
|
120
121
|
${a.message}
|
|
121
122
|
|
|
@@ -126,18 +127,18 @@ Troubleshooting:
|
|
|
126
127
|
4. Check network connectivity
|
|
127
128
|
5. Ensure ZIP file is under 100MB
|
|
128
129
|
|
|
129
|
-
If the issue persists, contact support.`,u=Date.now()-i;return
|
|
130
|
+
If the issue persists, contact support.`,u=Date.now()-i;return $.result({toolName:"DeployZipHTML",filePath:o,output:c,success:!1,executionTime:u}),[{type:"text",text:c}]}}}});import os from"fs/promises";import Io from"path";import Ao from"form-data";import Do from"axios";var Ct,Qs=O(()=>{"use strict";U();fe();ie();Ct=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let o=s.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let i=Date.now();$.start("DeployZipReact",s.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let w=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 ${w} seconds.`)}r.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await os.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 c=await os.stat(o),u=100*1024*1024;if(c.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(c.size/1024/1024).toFixed(2)}MB`);let d=await os.readFile(o),h=Io.basename(o).replace(/[\r\n\t"']/g,"_");r.debug(`[DeployZipReact] File: ${h}, Size: ${c.size} bytes`);let y=await G.getInstance().getFirebaseIdToken();if(!y)throw new Error("User must be authenticated to deploy projects");let T=new Ao;T.append("zipFile",d,{filename:h,contentType:"application/zip"});let k="https://snowx.ai/api/v2/deploy-zip-react";r.debug(`[DeployZipReact] Uploading to ${k}`);let p=await Do.post(k,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${y}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(p.status!==200&&p.status!==201)throw new Error(`Deployment failed with status ${p.status}: ${JSON.stringify(p.data)}`);let g=p.data;r.debug("[DeployZipReact] Deployed successfully"),r.debug(`[DeployZipReact] Response: ${JSON.stringify(g,null,2)}`);let b=g.data?.deployUrl||g.deployUrl||g.url||g.deploymentUrl||g.site_url||g.siteUrl||g.website_url,C=g.data?.deployId||g.deployId||g.projectId||g.deploymentId,S=g.data?.siteId||g.siteId;this.deployCount++;let x=`# React Project Deployed Successfully!
|
|
130
131
|
|
|
131
|
-
**Deployment URL**: ${
|
|
132
|
+
**Deployment URL**: ${b}
|
|
132
133
|
|
|
133
|
-
**Project**: ${
|
|
134
|
+
**Project**: ${h}
|
|
134
135
|
**Type**: React / SPA
|
|
135
|
-
${
|
|
136
|
-
`:""}${
|
|
136
|
+
${C?`**Deploy ID**: ${C}
|
|
137
|
+
`:""}${S?`**Site ID**: ${S}
|
|
137
138
|
`:""}
|
|
138
139
|
Your React app is now live and accessible!
|
|
139
140
|
|
|
140
|
-
${
|
|
141
|
+
${g.message||""}`,I=Date.now()-i;return $.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${b}`,success:!0,executionTime:I}),[{type:"text",text:x}]}catch(a){r.error(`[DeployZipReact] Deployment failed: ${a.message}`);let c=`React deployment failed
|
|
141
142
|
|
|
142
143
|
${a.message}
|
|
143
144
|
|
|
@@ -148,9 +149,9 @@ Troubleshooting:
|
|
|
148
149
|
4. Check network connectivity
|
|
149
150
|
5. Ensure ZIP file is under 100MB
|
|
150
151
|
|
|
151
|
-
If the issue persists, contact support.`,u=Date.now()-i;return
|
|
152
|
-
`)&&
|
|
153
|
-
`).length>2)return
|
|
152
|
+
If the issue persists, contact support.`,u=Date.now()-i;return $.result({toolName:"DeployZipReact",filePath:o,output:c,success:!1,executionTime:u}),[{type:"text",text:c}]}}}});var Js=O(()=>{"use strict"});function tt(l){let e=l.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(l.includes("<<")&&(l.includes("EOF")||l.includes("'EOF'")||l.includes('"EOF"')||l.includes("END")||l.includes("SCRIPT")||l.includes("'END'")||l.includes('"END"')))return ve.extended;let s=["python","python3","python2","node ","nodejs","ruby","perl","php","java ","kotlin","scala","Rscript","julia"];for(let c of s)if(e.includes(c))return ve.extended;let n=["pandas","numpy","scipy","matplotlib","import ","from ","require(","import(","DataFrame","Series"];for(let c of n)if(l.includes(c))return ve.extended;if(l.includes(`
|
|
153
|
+
`)&&l.split(`
|
|
154
|
+
`).length>2)return ve.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)&&l.length<100?ve.fast:a.has(t)?ve.extended:l.length<20?ve.fast:l.includes("|")||l.includes(">")||l.includes("<")?l.length<200?ve.default:ve.extended:ve.default}var ve,rs=O(()=>{"use strict";Js();ve={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 No,execSync as Ro}from"child_process";import{promisify as Oo}from"util";function as(){return process.platform}function Ce(){return process.platform==="win32"}function _o(){return process.platform==="darwin"}function We(l,e="SIGTERM"){if(l)try{if(Ce())try{Ro(`taskkill /PID ${l} /T /F`,{timeout:5e3,stdio:"ignore"})}catch{}else try{process.kill(-l,e)}catch{try{process.kill(l,e)}catch{}}}catch(t){r.debug(`[killProcessTree] Failed for PID ${l}: ${t}`)}}function Mo(l){let e=l.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(Ce()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let n=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(n)return{isPrivileged:!0,reason:`Privileged command: ${n.trim()}`};let 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 Ys(){return Ce()?"PowerShell or Command Prompt":(_o(),"Terminal")}function Lo(l,e){let t=Ys();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
|
|
154
155
|
|
|
155
156
|
Reason: ${e}
|
|
156
157
|
|
|
@@ -161,10 +162,10 @@ The Bash tool cannot execute privileged commands because:
|
|
|
161
162
|
|
|
162
163
|
To run this command:
|
|
163
164
|
1. Open ${t}
|
|
164
|
-
2. Run the command manually: ${
|
|
165
|
+
2. Run the command manually: ${l}
|
|
165
166
|
3. Enter your password when prompted
|
|
166
167
|
|
|
167
|
-
Alternative: Break down the task into non-privileged commands if possible.`}function
|
|
168
|
+
Alternative: Break down the task into non-privileged commands if possible.`}function Uo(l){let e=l.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",s=[{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:d}of s)if(e.startsWith(u)||e.includes(`&& ${u}`)||e.includes(`; ${u}`))return{isInteractive:!0,reason:d};let n=[{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:d,reason:h}of n)if(e.startsWith(u)&&!d?.some(y=>e.startsWith(y)))return{isInteractive:!0,reason:h};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 c=["git push","git pull","git fetch","git clone"];for(let u of c)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 Wo(l,e){let t=Ys();return`This command requires interactive input and cannot run in the Bash tool.
|
|
168
169
|
|
|
169
170
|
Reason: ${e}
|
|
170
171
|
|
|
@@ -175,25 +176,41 @@ The Bash tool runs in a non-interactive shell without a TTY, so:
|
|
|
175
176
|
|
|
176
177
|
To run this command:
|
|
177
178
|
1. Open ${t}
|
|
178
|
-
2. Run the command manually: ${
|
|
179
|
+
2. Run the command manually: ${l}
|
|
179
180
|
3. Follow the interactive prompts
|
|
180
181
|
|
|
181
|
-
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}
|
|
182
|
+
Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function qo(l){for(let e of Bo){let t=e.pattern.exec(l);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function Ho(l,e){return!e.isCatastrophic||!e.pattern?"Unknown catastrophic command error":`🛑 BLOCKED: Catastrophic command detected!
|
|
182
183
|
|
|
183
|
-
|
|
184
|
-
|
|
184
|
+
Category: ${{filesystem_destruction:"Filesystem Destruction",disk_destruction:"Disk/Device Destruction",filesystem_formatting:"Filesystem Formatting",fork_bomb:"Fork Bomb / System Crash",permission_destruction:"Permission Destruction",root_modification:"Root Directory Modification",kernel_panic:"Kernel Panic Trigger",environment_destruction:"System Environment Destruction",partition_destruction:"Partition Table Destruction"}[e.pattern.category]||"Unknown Category"}
|
|
185
|
+
Reason: ${e.pattern.description}
|
|
186
|
+
Matched: "${e.matchedText}"
|
|
185
187
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
+
This command has been HARD BLOCKED because it could cause:
|
|
189
|
+
- Irreversible data loss
|
|
190
|
+
- System corruption or failure
|
|
191
|
+
- Complete loss of system functionality
|
|
188
192
|
|
|
189
|
-
|
|
190
|
-
`).length;w=N.text+`
|
|
193
|
+
The Bash tool will NEVER execute commands that could destroy your system.
|
|
191
194
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
+
If you believe this is a false positive, please:
|
|
196
|
+
1. Review the command carefully
|
|
197
|
+
2. Run it manually in your terminal if you're certain it's safe
|
|
198
|
+
3. Consider breaking down the operation into safer steps`}function Zs(l){let e=qo(l);if(e.isCatastrophic)return Ho(l,e);let t=Mo(l);if(t.isPrivileged)return Lo(l,t.reason||"Privileged command detected");let s=Uo(l);return s.isInteractive?Wo(l,s.reason||"Interactive command detected"):null}function en(l){let e=l.trim();for(let t of Go)if(t.test(e))return{isDelete:!0,paths:zo(e),category:Xo(e)};return{isDelete:!1,paths:[]}}function zo(l){let e=[],t=l.split(/\s+/),s=!1;for(let n=1;n<t.length;n++){let o=t[n];if(s){s=!1;continue}if(o.startsWith("-")){["-f","-o","-t","--target","--output"].includes(o)&&(s=!0);continue}o.length>0&&!o.startsWith("-")&&e.push(o)}return e}function Xo(l){let e=l.toLowerCase();return/^(rm|rmdir|unlink|del|rd|erase|remove-item)/i.test(e)?"File/Directory Deletion":/^git\s+/.test(e)?"Git Operation":/^docker/.test(e)||/^podman/.test(e)?"Docker/Container Operation":/^kubectl/.test(e)||/^helm/.test(e)?"Kubernetes Operation":/^aws\s+/.test(e)||/^gcloud/.test(e)||/^az\s+/.test(e)?"Cloud Resource Deletion":/^(terraform|pulumi|cdk)/.test(e)?"Infrastructure Destruction":/drop\s+(table|database|schema)/i.test(e)||/^(dropdb|dropuser)/.test(e)?"Database Deletion":/^(npm|yarn|pnpm|bun|pip|brew|apt|apt-get|yum|dnf|pacman|snap)/.test(e)?"Package Removal":/^(kill|pkill|killall|taskkill)/i.test(e)?"Process Termination":"Delete Operation"}var Fo,$o,st,is,se,nt,Bo,Go,Be=O(()=>{"use strict";rs();Le();U();Fo=Oo(No),$o=8500,st=new de({maxResponseTokens:$o});is=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),r.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),r.debug(`[BackgroundProcessManager] Removed process: ${e}`)}getAllProcesses(){return Array.from(this.processes.values())}getRunningProcesses(){return Array.from(this.processes.values()).filter(e=>e.status==="running")}getCompletedProcesses(){return Array.from(this.processes.values()).filter(e=>e.status!=="running")}updateProcess(e,t){let s=this.processes.get(e);return s?(Object.assign(s,t),r.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${s.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],s=Array.from(this.processes.entries());for(let i=0;i<s.length;i++){let[a,c]=s[i];c.status!=="running"&&c.endTime&&t.push({id:a,endTime:c.endTime.getTime()})}let n=0;for(let i=0;i<t.length;i++){let{id:a,endTime:c}=t[i];e-c>this.COMPLETED_PROCESS_TTL&&(this.processes.delete(a),n++)}n>0&&r.debug(`[BackgroundProcessManager] Cleaned up ${n} old processes by TTL`);let o=t.filter(i=>e-i.endTime<=this.COMPLETED_PROCESS_TTL);if(o.length>this.MAX_COMPLETED_PROCESSES){o.sort((a,c)=>a.endTime-c.endTime);let i=o.slice(0,o.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<i.length;a++){let{id:c}=i[a];this.processes.delete(c)}r.debug(`[BackgroundProcessManager] Cleaned up ${i.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let s=0;s<t.length;s++){let[n,o]=t[s];o.status!=="running"&&(this.processes.delete(n),e++)}return r.debug(`[BackgroundProcessManager] Force cleaned ${e} completed processes`),e}getStats(){let e=this.getAllProcesses(),t=e.filter(s=>s.status==="running").length;return{total:e.length,running:t,completed:e.length-t}}clear(){this.processes.clear(),r.debug("[BackgroundProcessManager] Cleared all processes")}},se=new is;nt=class l{static instance;constructor(){}static getInstance(){return l.instance||(l.instance=new l),l.instance}async executeCommand(e,t,s,n,o="new",i){let a=i||tt(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Ce())await Fo(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(s=>{let n=Date.now(),o=as(),i,a;Ce()?(i="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(i="/bin/bash",a=["-c",e]);let c=Po(i,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Ce()}),u="",d="",h=!1,f=!1,y=!1,T=null,k=null,p=null,g=C=>{f||(f=!0,clearTimeout(b),k&&clearTimeout(k),p&&clearTimeout(p),s(C))},b=setTimeout(async()=>{f||(h=!0,c.pid&&await this.killProcessTree(c.pid,"SIGTERM"),k=setTimeout(async()=>{f||(c.pid&&await this.killProcessTree(c.pid,"SIGKILL"),this.cleanupStreams(c),setTimeout(()=>{if(!f){let C=Date.now()-n;g({output:u+d+`
|
|
195
199
|
|
|
196
|
-
❌ Command timed out after `+t.maxTimeout+"
|
|
200
|
+
❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:C,platform:o})}},1e3))},1500))},t.maxTimeout);c.stdout?.on("data",C=>{u+=C.toString()}),c.stderr?.on("data",C=>{d+=C.toString()}),c.on("exit",(C,S)=>{y=!0,T=C,p=setTimeout(()=>{if(f)return;clearTimeout(b),k&&clearTimeout(k),this.cleanupStreams(c);let x=Date.now()-n,I=(u+d).trim();if(st.exceedsResponseLimit(I)){let w=st.truncate(I),M=w.text.split(`
|
|
201
|
+
`);I=w.text+`
|
|
202
|
+
|
|
203
|
+
[Output truncated at `+w.tokens.toLocaleString()+` tokens]
|
|
204
|
+
[Showing first `+M.length+" lines of output]"}g(h?{output:I+`
|
|
205
|
+
|
|
206
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:x,platform:o}:{output:I,exitCode:C||0,isSuccess:(C||0)===0,duration:x,platform:o})},1500)}),c.on("close",C=>{if(f)return;p&&clearTimeout(p),clearTimeout(b),k&&clearTimeout(k);let S=Date.now()-n,x=(u+d).trim();if(st.exceedsResponseLimit(x)){let I=st.count(x),w=st.truncate(x),j=w.text.split(`
|
|
207
|
+
`).length;x=w.text+`
|
|
208
|
+
|
|
209
|
+
[Output truncated at `+w.tokens.toLocaleString()+` tokens]
|
|
210
|
+
[Showing first `+j+` lines of output]
|
|
211
|
+
[Total output was `+I.toLocaleString()+" tokens]"}g(h?{output:x+`
|
|
212
|
+
|
|
213
|
+
❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:S,platform:o}:{output:x,exitCode:C||0,isSuccess:(C||0)===0,duration:S,platform:o})}),c.on("error",C=>{if(f)return;let S=Date.now()-n;g({output:"Process execution failed: "+C.message,exitCode:-1,isSuccess:!1,duration:S,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`)}};Bo=[{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\*/,description:"rm -rf /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[rR]\s+-[fF]\s+\/\*/,description:"rm -r -f /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+-[fF]\s+-[rR]\s+\/\*/,description:"rm -f -r /* (wipes entire system)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/\s*$/,description:"rm -r / targeting root directory",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\*/,description:"rm -rf ~/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\/\.\*/,description:"rm -rf ~/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+~\*/,description:"rm -rf ~* (wipes home)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\*/,description:"rm -rf $HOME/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$HOME\/\.\*/,description:"rm -rf $HOME/.* (wipes home hidden files)",category:"filesystem_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\$\{HOME\}\/\*/,description:"rm -rf ${HOME}/* (wipes home directory)",category:"filesystem_destruction"},{pattern:/\brm\s+.*--no-preserve-root/,description:"rm with --no-preserve-root",category:"filesystem_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/\bdd\b.*\bof\s*=\s*\/dev\/disk\d*/,description:"dd writing to disk device",category:"disk_destruction"},{pattern:/>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d|vd[a-z]|xvd[a-z]|mmcblk\d)\b/,description:"redirect to disk device",category:"disk_destruction"},{pattern:/\bcat\b.*>\s*\/dev\/(sd[a-z]|hd[a-z]|nvme\d)\b/,description:"cat to disk device",category:"disk_destruction"},{pattern:/\bmkfs\.[a-z0-9]+\s+/,description:"mkfs.* filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkfs\s+-t\s+/,description:"mkfs -t filesystem format command",category:"filesystem_formatting"},{pattern:/\bmkswap\s+\/dev\//,description:"mkswap on device",category:"filesystem_formatting"},{pattern:/\bwipefs\s+(-a|--all)\s+/,description:"wipefs -a (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/\bwipefs\s+--all\s+/,description:"wipefs --all (wipes filesystem signatures)",category:"filesystem_formatting"},{pattern:/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/,description:"fork bomb :(){ :|:& };:",category:"fork_bomb"},{pattern:/\bfork\s*\(\s*\)\s*while/,description:"fork bomb pattern",category:"fork_bomb"},{pattern:/while\s*\(\s*true\s*\)\s*;\s*do\s+fork/,description:"fork loop",category:"fork_bomb"},{pattern:/>\s*\/dev\/sda.*&.*>\s*\/dev\/sda/,description:"parallel disk destruction",category:"fork_bomb"},{pattern:/\.\(\)\s*\{\s*\.\s*\|\s*\.\s*&\s*\}/,description:"fork bomb variant",category:"fork_bomb"},{pattern:/bomb\s*\(\)\s*\{.*bomb.*\|.*bomb.*&/,description:"named fork bomb",category:"fork_bomb"},{pattern:/\bchmod\s+.*\b0{3}\s+\/\s*$/,description:"chmod 000 / (locks entire system)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b0{3}\s+\//,description:"chmod -R 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b0{3}\s+\//,description:"chmod --recursive 000 / (recursive permission destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+.*-[rR].*\b777\s+\/\s*$/,description:"chmod -R 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchmod\s+--recursive\s+.*\b777\s+\/\s*$/,description:"chmod --recursive 777 / (security destruction)",category:"permission_destruction"},{pattern:/\bchown\s+.*-[rR].*\s+\S+\s+\/\s*$/,description:"chown -R on root",category:"permission_destruction"},{pattern:/\bchown\s+--recursive\s+.*\s+\S+\s+\/\s*$/,description:"chown --recursive on root",category:"permission_destruction"},{pattern:/\bmv\s+\/\*\s+\/dev\/null/,description:"mv /* /dev/null",category:"root_modification"},{pattern:/\bmv\s+\/\s+\S/,description:"mv / (moving root directory)",category:"root_modification"},{pattern:/>\s*\/proc\/sysrq-trigger/,description:"sysrq trigger (can cause kernel panic)",category:"kernel_panic"},{pattern:/>\s*\/proc\/sys\/kernel\/panic/,description:"kernel panic trigger",category:"kernel_panic"},{pattern:/\becho\s+[co]\s*>\s*\/proc\/sysrq/,description:"sysrq crash/oom trigger",category:"kernel_panic"},{pattern:/\becho\s+[bsuc]\s*>\s*\/proc\/sysrq-trigger/,description:"sysrq dangerous trigger (b=reboot, s=sync, u=remount, c=crash)",category:"kernel_panic"},{pattern:/\brm\s+(-[a-zA-Z]*\s+)*\/bin\/(bash|sh|zsh)\b/,description:"deleting system shell",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/bin\/?(\s|$)/,description:"deleting /bin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/usr\/?(\s|$)/,description:"deleting /usr directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/etc\/?(\s|$)/,description:"deleting /etc directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/var\/?(\s|$)/,description:"deleting /var directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib\/?(\s|$)/,description:"deleting /lib directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/boot\/?(\s|$)/,description:"deleting /boot directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/sbin\/?(\s|$)/,description:"deleting /sbin directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/lib64\/?(\s|$)/,description:"deleting /lib64 directory",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/System\/?(\s|$)/,description:"deleting /System directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Library\/?(\s|$)/,description:"deleting /Library directory (macOS)",category:"environment_destruction"},{pattern:/\brm\s+.*-[a-zA-Z]*[rR].*\s+\/Applications\/?(\s|$)/,description:"deleting /Applications directory (macOS)",category:"environment_destruction"},{pattern:/\bfdisk\s+\/dev\//,description:"fdisk on device (partition modification)",category:"partition_destruction"},{pattern:/\bparted\s+.*\brm\b/,description:"parted rm (partition deletion)",category:"partition_destruction"},{pattern:/\bgdisk\s+.*\bd\b/,description:"gdisk delete partition",category:"partition_destruction"},{pattern:/\bsgdisk\s+.*(-d|--delete|-Z|--zap-all)/,description:"sgdisk partition deletion",category:"partition_destruction"},{pattern:/\bcfdisk\s+\/dev\//,description:"cfdisk on device",category:"partition_destruction"},{pattern:/\bsfdisk\s+.*--delete/,description:"sfdisk partition deletion",category:"partition_destruction"},{pattern:/\byes\s*\|\s*(rm|dd|mkfs|fdisk|parted)/,description:"yes piped to destructive command",category:"filesystem_destruction"},{pattern:/\bshred\s+.*\/(dev|bin|usr|etc|var|lib|boot)/,description:"shred on system directories",category:"environment_destruction"},{pattern:/set\s+\+o\s+noclobber.*>\s*\/dev\//,description:"noclobber bypass to device",category:"disk_destruction"}];Go=[/^rm\s+/,/^rm\s+-[rRfFiIvd]+/,/^rmdir\s+/,/^unlink\s+/,/^shred\s+/,/^wipe\s+/,/^srm\s+/,/^trash\s+/,/^trash-put\s+/,/^gio\s+trash/,/^gvfs-trash\s+/,/^del\s+/i,/^del\s+\/[fqsaP]+/i,/^rd\s+/i,/^rd\s+\/s/i,/^rmdir\s+\/s/i,/^erase\s+/i,/^Remove-Item\s+/i,/^ri\s+/i,/\|\s*xargs\s+(rm|del|erase|unlink)/i,/&&\s*rm\s+/,/;\s*rm\s+/,/\|\s*rm\s+/,/^find\s+.*-delete/,/^find\s+.*-exec\s+(rm|del|unlink)/i,/^git\s+rm\s+/,/^git\s+rm\s+-[rfcached]+/,/^git\s+branch\s+-[dD]\s+/,/^git\s+branch\s+--delete/,/^git\s+push\s+.*--delete/,/^git\s+push\s+.*:\s*\w+/,/^git\s+push\s+.*--force/,/^git\s+push\s+-f\s+/,/^git\s+tag\s+-d\s+/,/^git\s+tag\s+--delete/,/^git\s+remote\s+(remove|rm)\s+/,/^git\s+stash\s+drop/,/^git\s+stash\s+clear/,/^git\s+clean\s+-[fdxXe]+/,/^git\s+reset\s+--hard/,/^git\s+checkout\s+--\s+\./,/^git\s+restore\s+--staged/,/^git\s+rebase\s+/,/^git\s+filter-branch/,/^git\s+reflog\s+expire/,/^git\s+reflog\s+delete/,/^git\s+gc\s+--prune/,/^git\s+worktree\s+remove/,/^docker\s+rm\s+/,/^docker\s+rm\s+-[fv]+/,/^docker\s+rmi\s+/,/^docker\s+rmi\s+-f/,/^docker\s+image\s+rm\s+/,/^docker\s+image\s+prune/,/^docker\s+container\s+rm\s+/,/^docker\s+container\s+prune/,/^docker\s+container\s+kill/,/^docker\s+volume\s+rm\s+/,/^docker\s+volume\s+prune/,/^docker\s+network\s+rm\s+/,/^docker\s+network\s+prune/,/^docker\s+system\s+prune/,/^docker-compose\s+down/,/^docker-compose\s+rm/,/^docker\s+compose\s+down/,/^docker\s+compose\s+rm/,/^docker\s+builder\s+prune/,/^docker\s+secret\s+rm/,/^docker\s+config\s+rm/,/^docker\s+stack\s+rm/,/^docker\s+service\s+rm/,/^docker\s+plugin\s+rm/,/^docker\s+context\s+rm/,/^podman\s+rm/,/^podman\s+rmi/,/^podman\s+.*\s+prune/,/^crictl\s+rm/,/^nerdctl\s+rm/,/^kubectl\s+delete\s+/,/^kubectl\s+delete\s+-[fAR]+/,/^kubectl\s+drain\s+/,/^kubectl\s+cordon\s+/,/^k\s+delete\s+/,/^helm\s+uninstall\s+/,/^helm\s+delete\s+/,/^helm\s+rollback\s+/,/^kustomize\s+.*delete/,/^oc\s+delete\s+/,/^argocd\s+app\s+delete/,/^aws\s+s3\s+rm\s+/,/^aws\s+s3\s+rb\s+/,/^aws\s+ec2\s+terminate-instances/,/^aws\s+ec2\s+delete-/,/^aws\s+rds\s+delete-/,/^aws\s+lambda\s+delete-/,/^aws\s+dynamodb\s+delete-/,/^aws\s+iam\s+delete-/,/^aws\s+.*\s+delete-/,/^aws\s+.*\s+remove-/,/^aws\s+.*\s+terminate-/,/^gcloud\s+.*\s+delete\s*/,/^gcloud\s+.*\s+remove\s*/,/^gsutil\s+rm\s+/,/^gsutil\s+-m\s+rm/,/^gsutil\s+rb\s+/,/^bq\s+rm\s+/,/^firebase\s+.*delete/i,/^az\s+.*\s+delete/,/^az\s+group\s+delete/,/^az\s+.*\s+remove/,/^doctl\s+.*\s+delete/,/^doctl\s+.*\s+remove/,/^linode-cli\s+.*\s+delete/,/^vultr-cli\s+.*\s+delete/,/^hcloud\s+.*\s+delete/,/^terraform\s+destroy/,/^terraform\s+apply\s+.*-destroy/,/^tf\s+destroy/,/^pulumi\s+destroy/,/^pulumi\s+stack\s+rm/,/^cdk\s+destroy/,/^cdktf\s+destroy/,/^serverless\s+remove/,/^sls\s+remove/,/^sam\s+delete/,/^amplify\s+delete/,/^copilot\s+.*\s+delete/,/^cloudformation\s+delete-stack/,/drop\s+table\s+/i,/drop\s+database\s+/i,/drop\s+schema\s+/i,/drop\s+index\s+/i,/drop\s+view\s+/i,/drop\s+function\s+/i,/drop\s+procedure\s+/i,/drop\s+trigger\s+/i,/drop\s+sequence\s+/i,/drop\s+type\s+/i,/drop\s+user\s+/i,/drop\s+role\s+/i,/drop\s+tablespace\s+/i,/drop\s+keyspace\s+/i,/truncate\s+table\s+/i,/truncate\s+/i,/delete\s+from\s+/i,/^mongo.*\.drop\(/,/^mongosh.*\.drop\(/,/^mongo.*\.remove\(/,/^mongosh.*\.deleteMany\(/,/^redis-cli.*\s+del\s+/i,/^redis-cli.*\s+flushdb/i,/^redis-cli.*\s+flushall/i,/^redis-cli.*\s+unlink\s+/i,/^dropdb\s+/,/^dropuser\s+/,/^mysqladmin\s+drop/,/^cqlsh.*drop/i,/^influx.*delete/i,/^etcdctl\s+del/,/^npm\s+(uninstall|remove|rm|un|unlink)\s+/,/^npm\s+cache\s+clean/,/^yarn\s+remove\s+/,/^yarn\s+cache\s+clean/,/^pnpm\s+(remove|rm|uninstall|un)\s+/,/^pnpm\s+store\s+prune/,/^bun\s+(remove|rm|uninstall)\s+/,/^deno\s+uninstall/,/^pip\s+uninstall\s+/,/^pip3\s+uninstall\s+/,/^pipx\s+uninstall\s+/,/^conda\s+remove\s+/,/^conda\s+uninstall\s+/,/^conda\s+env\s+remove/,/^poetry\s+remove\s+/,/^pdm\s+remove\s+/,/^uv\s+pip\s+uninstall/,/^gem\s+uninstall\s+/,/^bundle\s+remove\s+/,/^rvm\s+remove\s+/,/^rbenv\s+uninstall/,/^cargo\s+uninstall\s+/,/^cargo\s+remove\s+/,/^rustup\s+.*\s+uninstall/,/^rustup\s+.*\s+remove/,/^go\s+clean\s+/,/^composer\s+remove\s+/,/^dotnet\s+remove\s+/,/^nuget\s+delete\s+/,/^mvn\s+.*:clean/,/^gradle\s+clean/,/^gradlew\s+clean/,/^brew\s+(uninstall|remove|rm)\s+/,/^brew\s+cleanup/,/^apt\s+(remove|purge|autoremove)\s+/,/^apt-get\s+(remove|purge|autoremove)\s+/,/^dpkg\s+(-r|--remove|-P|--purge)\s+/,/^yum\s+(remove|erase|autoremove)\s+/,/^dnf\s+(remove|erase|autoremove)\s+/,/^rpm\s+-e\s+/,/^pacman\s+-R/,/^pacman\s+-S.*--clean/,/^zypper\s+(remove|rm)\s+/,/^apk\s+del\s+/,/^emerge\s+--unmerge/,/^xbps-remove\s+/,/^nix-env\s+-e\s+/,/^nix-collect-garbage/,/^snap\s+remove\s+/,/^flatpak\s+uninstall\s+/,/^port\s+uninstall\s+/,/^pkgin\s+remove\s+/,/^pkg\s+delete\s+/,/^pkg\s+remove\s+/,/^choco\s+uninstall\s+/i,/^scoop\s+uninstall\s+/i,/^winget\s+uninstall\s+/i,/^gh\s+repo\s+delete/,/^gh\s+release\s+delete/,/^gh\s+run\s+delete/,/^gh\s+gist\s+delete/,/^gh\s+issue\s+delete/,/^gh\s+pr\s+close/,/^gitlab.*delete/i,/^vercel\s+rm\s+/,/^vercel\s+remove\s+/,/^vercel\s+.*--yes/,/^netlify\s+.*delete/,/^heroku\s+.*destroy/,/^heroku\s+apps:destroy/,/^heroku\s+addons:destroy/,/^fly\s+apps\s+destroy/,/^fly\s+.*destroy/,/^railway\s+delete/,/^render\s+.*delete/,/^wrangler\s+delete/,/^cf\s+delete/,/^virsh\s+(destroy|undefine)/,/^vboxmanage\s+unregistervm/i,/^VBoxManage\s+unregistervm/,/^vagrant\s+destroy/,/^multipass\s+delete/,/^multipass\s+purge/,/^lima\s+delete/,/^qemu.*-drive.*if=none/,/^kill\s+-9\s+/,/^kill\s+-KILL\s+/,/^kill\s+-SIGKILL\s+/,/^pkill\s+-9\s+/,/^pkill\s+-KILL\s+/,/^killall\s+-9\s+/,/^killall\s+-KILL\s+/,/^systemctl\s+(stop|disable|mask)\s+/,/^service\s+.*\s+stop/,/^launchctl\s+(unload|remove|bootout)/,/^sc\s+delete\s+/i,/^taskkill\s+/i,/^crontab\s+-r/,/^crontab\s+-ir/,/^at\s+-d\s+/,/^atrm\s+/,/^schtasks\s+\/delete/i,/^ssh-keygen\s+-R\s+/,/^ssh-keygen\s+-r\s+/,/^gpg\s+--delete-key/,/^gpg\s+--delete-secret-key/,/^security\s+delete-/,/^keyctl\s+unlink/,/^pass\s+rm\s+/,/^vault\s+delete/,/^vault\s+kv\s+delete/,/^ip\s+link\s+delete/,/^ip\s+route\s+(delete|del)\s+/,/^ip\s+addr\s+(delete|del)\s+/,/^iptables\s+-D\s+/,/^iptables\s+-F/,/^iptables\s+-X/,/^ip6tables\s+-D\s+/,/^nft\s+delete/,/^firewall-cmd\s+--remove-/,/^ufw\s+delete\s+/,/^netsh.*delete/i,/^make\s+clean/,/^make\s+distclean/,/^make\s+mrproper/,/^ninja\s+-t\s+clean/,/^ninja\s+.*clean/,/^bazel\s+clean/,/^buck\s+clean/,/^cmake\s+--build\s+.*--target\s+clean/,/^scons\s+-c/,/^ant\s+clean/,/^lein\s+clean/,/^mix\s+clean/,/^stack\s+clean/,/^cabal\s+clean/,/^swift\s+package\s+clean/,/^xcodebuild\s+clean/,/^svn\s+delete\s+/,/^svn\s+rm\s+/,/^svn\s+remove\s+/,/^hg\s+remove\s+/,/^hg\s+strip\s+/,/^hg\s+purge\s+/,/^p4\s+delete\s+/,/^fossil\s+delete/,/^bzr\s+remove\s+/,/^darcs\s+remove\s+/,/^dd\s+.*of=/,/^mkfs\s+/,/^mkfs\.[a-z0-9]+\s+/,/^format\s+/i,/^fdisk\s+/,/^parted\s+/,/^gdisk\s+/,/^wipefs\s+/,/^blkdiscard\s+/,/^hdparm\s+.*--security-erase/,/^truncate\s+/,/^:\s*>\s*\S+/,/^>\s*\S+/,/^cp\s+\/dev\/null\s+/,/^mv\s+.*\s+\/dev\/null/,/^rsync\s+.*--delete/,/^rsync\s+.*--remove-source-files/,/^ssh\s+.*\s+(rm|del|unlink)\s+/,/^scp\s+.*:.*\s+\/dev\/null/,/^curl\s+.*-X\s*DELETE/i,/^curl\s+.*--request\s*DELETE/i,/^wget\s+.*--delete-after/,/^httpie\s+DELETE\s+/i,/^http\s+DELETE\s+/i,/^rclone\s+delete/,/^rclone\s+purge/,/^restic\s+forget/,/^borg\s+delete/,/^borg\s+prune/,/^duplicity\s+remove/,/^tmutil\s+delete/]});var cs={};ge(cs,{ToolCallingService:()=>ot});import{EventEmitter as jo}from"events";import tn from"axios";import{exec as Ko,spawn as sn}from"child_process";import{promisify as Vo}from"util";import ee from"fs/promises";import we from"fs";import qe from"path";import Qo from"os";var wc,ot,kt=O(()=>{"use strict";Be();rs();Le();wc=Vo(Ko),ot=class _ToolCallingService extends jo{static instance;tools=new Map;executionHistory=[];tokenCounter=new de;shellSessionManager=nt.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.
|
|
197
214
|
|
|
198
215
|
🔧 SESSION MODE SELECTION (REQUIRED):
|
|
199
216
|
• Use session: "existing" for workflows that need persistent state:
|
|
@@ -227,25 +244,48 @@ Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive)
|
|
|
227
244
|
4. LLM receives prompt details and makes decision
|
|
228
245
|
5. LLM uses provide_input to send appropriate response
|
|
229
246
|
6. Command execution continues with provided input
|
|
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}
|
|
247
|
+
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(l){this.tools.set(l.name,l)}unregisterTool(l){let e=this.tools.delete(l);return e}async executeTool(l){let e=Date.now(),t=l.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:l});let s={};try{s=JSON.parse(l.function.arguments)}catch(o){throw new Error(`Invalid arguments for tool '${t}': ${o}`)}let{ToolDisplay:n}=await Promise.resolve().then(()=>(fe(),Bs));n.start(t,s.description,s.command||s.file_path);try{let o=this.tools.get(t);if(!o)throw new Error(`Tool '${t}' not found`);if(!o.enabled)throw new Error(`Tool '${t}' is disabled`);let i=await o.handler(s),a=Date.now()-e,c=this.handleLargeResponse(i,t);return this.executionHistory.push({toolName:t,args:s,result:c,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:c,executionTime:a}),n.result({toolName:t,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(c),success:c.success,executionTime:a}),await this.captureFrontendToolResult(t,c),c}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}),n.error(t,o.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(l){return l.success?l.result?typeof l.result=="string"?l.result:typeof l.result=="object"&&"stdout"in l.result?l.result.stdout||l.result.stderr||"":typeof l.result=="object"&&"content"in l.result?l.result.content||"":JSON.stringify(l.result,null,2):"":l.error||"Unknown error"}async captureFrontendToolResult(l,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Se(),He)),s=t.getInstance(),n=this.extractOutputForDisplay(e);s.captureFrontendToolResult(l,n,e.success)}async webSearch(l){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(l.query)}&format=json&no_html=1&skip_disambig=1`,s=(await tn.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,n=[];if(s.AbstractText&&n.push({title:s.Heading||"Instant Answer",content:s.AbstractText,url:s.AbstractURL||"",type:"instant_answer"}),s.RelatedTopics&&s.RelatedTopics.length>0)for(let o of s.RelatedTopics.slice(0,l.num_results||5))o.Text&&n.push({title:o.Text.split(" - ")[0]||"Related Topic",content:o.Text,url:o.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:l.query,results:n,total_results:n.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(l){try{let e=await ee.readFile(l.file_path,"utf-8");return this.cacheFileState(l.file_path,e),{success:!0,result:{file_path:l.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(l){try{let{file_path:e,content:t,mode:s="write"}=l;if(e.endsWith(".ipynb")&&we.existsSync(e)){let o=await ee.readFile(e,"utf-8"),i=JSON.parse(o);if(i.cells.length>0&&i.cells[0].id){let a=i.cells.findIndex(c=>c.id===i.cells[0].id);if(a!==-1)return i.cells[a].source=t,await ee.writeFile(e,JSON.stringify(i,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}we.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let n=qe.dirname(e);return await ee.mkdir(n,{recursive:!0}),s==="append"?await ee.appendFile(e,t):await ee.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:s}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(l){try{let e=await ee.readdir(l.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!l.include_hidden&&s.name.startsWith("."))continue;let n=await ee.stat(qe.join(l.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:n.size,modified:n.mtime.toISOString()})}return{success:!0,result:{directory_path:l.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(l){try{let e=nt.parseSessionMode(l.session),t=tt(l.command),s={activityTimeout:l.timeout||t.activityTimeout,maxTimeout:l.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},n=await this.shellSessionManager.executeCommand(l.command,`tool-${Date.now()}`,this.currentUserId,l.session||"new",e,s);return{success:n.isSuccess,result:{command:l.command,stdout:n.output,stderr:"",exit_code:n.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:l.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(l){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:l.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(l){return{success:!1,error:`Calculation failed: ${l.message}`}}}async httpRequest(l){try{let e=await tn({method:l.method||"GET",url:l.url,headers:l.headers,data:l.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:l.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:l.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(l){try{let e=new Date,t={};switch(l.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=l.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(l){try{let{command:e,timeout:t,run_in_background:s=!1}=l;if(s){this.backgroundProcessCounter++;let i=`bg-${this.backgroundProcessCounter}`,a=sn("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),c={process:a,command:e,startTime:new Date,stdout:"",stderr:""};a.stdout.on("data",d=>{let h=d.toString();if(h){let f=this.backgroundProcesses.get(i);f&&(f.stdout+=h,this.backgroundProcesses.set(i,f))}}),a.stderr.on("data",d=>{let h=d.toString();if(h){let f=this.backgroundProcesses.get(i);f&&(f.stderr+=h,this.backgroundProcesses.set(i,f))}}),a.on("close",d=>{let h=this.backgroundProcesses.get(i);h&&(h.exitCode=d||0,this.backgroundProcesses.set(i,h))}),this.backgroundProcesses.set(i,c);let u=`Command started in background with ID: ${i}
|
|
231
248
|
PID: ${a.pid}
|
|
232
249
|
Command: ${e}
|
|
233
250
|
|
|
234
251
|
Note: The process will continue running in the background.
|
|
235
|
-
Output will be collected automatically.`;return{success:!0,result:{process_id:i,pid:a.pid,message:u}}}let
|
|
236
|
-
`).filter(
|
|
237
|
-
|
|
252
|
+
Output will be collected automatically.`;return{success:!0,result:{process_id:i,pid:a.pid,message:u}}}let n=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:tt(e),o=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",n);return{success:o.isSuccess,result:{command:e,stdout:o.output,stderr:"",exit_code:o.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(l){try{let{file_path:e,old_string:t,new_string:s,replace_all:n=!1}=l;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&we.existsSync(e)){let a=await ee.readFile(e,"utf-8"),c=JSON.parse(a);for(let u=0;u<c.cells.length;u++){let d=c.cells[u],h=Array.isArray(d.source)?d.source.join(""):d.source;if(h.includes(t)){let f=n?h.replaceAll(t,s):h.replace(t,s);return c.cells[u].source=f,await ee.writeFile(e,JSON.stringify(c,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:n?h.split(t).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(e);let o=await ee.readFile(e,"utf-8");if(!o.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let i=n?o.replaceAll(t,s):o.replace(t,s);if(i===o)throw new Error("Edit failed: File content unchanged after replacement");return await ee.writeFile(e,i,"utf-8"),this.cacheFileState(e,i),{success:!0,result:{file_path:e,replacements:n?o.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(l){try{let{pattern:e,path:t=process.cwd(),glob:s,output_mode:n="files_with_matches",case_insensitive:o=!1}=l,i=[];return o&&i.push("-i"),n==="files_with_matches"?i.push("-l"):n==="count"&&i.push("-c"),s&&i.push("--glob",s),i.push(e,t),new Promise(a=>{let c=sn("rg",i,{stdio:["ignore","pipe","pipe"]}),u="",d="";c.stdout.on("data",h=>{u+=h.toString()}),c.stderr.on("data",h=>{d+=h.toString()}),c.on("close",h=>{if(h!==0&&h!==1){a({success:!1,error:`ripgrep failed: ${d||"Unknown error"}`});return}let f=u.trim().split(`
|
|
253
|
+
`).filter(T=>T),y=f.length;a({success:!0,result:{pattern:e,num_files:y,files:f,output:u.trim()}})}),c.on("error",h=>{a({success:!1,error:`Failed to execute ripgrep: ${h.message}. Make sure ripgrep is installed.`})})})}catch(e){return{success:!1,error:`Grep failed: ${e.message}`}}}async globFiles(l){try{let{pattern:e,path:t=process.cwd()}=l,n=(a=>{let c=a;return c=c.replace(/[.+^${}()|[\]\\]/g,"\\$&"),c=c.replace(/\*\*/g,"<DOUBLESTAR>"),c=c.replace(/\*/g,"[^/]*"),c=c.replace(/<DOUBLESTAR>/g,".*"),c=c.replace(/\?/g,"."),new RegExp(`^${c}$`)})(e),o=[],i=async a=>{try{let c=await ee.readdir(a,{withFileTypes:!0});for(let u of c){if(u.name.startsWith("."))continue;let d=qe.join(a,u.name),h=qe.relative(t,d);u.isDirectory()?await i(d):(n.test(h)||n.test(u.name))&&o.push(d)}}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(l){try{let{notebook_path:e,cell_id:t,new_source:s,cell_type:n="code",edit_mode:o="replace"}=l;if(!we.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 ee.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 c=a.cells.findIndex(u=>u.id===t);if(c===-1)throw new Error(`Cell with id ${t} not found`);a.cells[c].source=s;break}case"insert":{if(!n)throw new Error("cell_type is required for insert mode");let c={id:Math.random().toString(36).substring(2,15),cell_type:n,source:s,metadata:{},execution_count:n==="code"?null:void 0,outputs:n==="code"?[]:void 0};if(t){let u=a.cells.findIndex(d=>d.id===t);a.cells.splice(u+1,0,c)}else a.cells.unshift(c);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let c=a.cells.findIndex(u=>u.id===t);if(c===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(c,1);break}default:throw new Error(`Invalid edit_mode: ${o}`)}return await ee.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(l,e){try{let t=we.statSync(l);this.fileStateCache.set(l,{content:e,modificationDate:t.mtime,filePath:l})}catch{}}async validateFileNotModified(l){let e=this.fileStateCache.get(l);if(!e){if(we.existsSync(l)){let s=await ee.readFile(l,"utf-8");this.cacheFileState(l,s)}return}if(we.statSync(l).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let l=[];for(let[e,t]of this.tools.entries())t.enabled&&l.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return l}getToolsByCategory(l){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===l)}enableTool(l){let e=this.tools.get(l);return e?(e.enabled=!0,!0):!1}disableTool(l){let e=this.tools.get(l);return e?(e.enabled=!1,!0):!1}getExecutionHistory(l=10){return this.executionHistory.slice(-l)}getExecutionStats(){let l=this.executionHistory.length,e=this.executionHistory.filter(i=>i.result.success).length,t=l-e,s=l>0?this.executionHistory.reduce((i,a)=>i+a.executionTime,0)/l:0,n=new Map;this.executionHistory.forEach(i=>{n.set(i.toolName,(n.get(i.toolName)||0)+1)});let o=n.size>0?Array.from(n.entries()).reduce((i,a)=>a[1]>i[1]?a:i)[0]:null;return{total:l,successful:e,failed:t,averageTime:Math.round(s),mostUsed:o}}clearHistory(){this.executionHistory=[]}setUserId(l){this.currentUserId=l}getCurrentUserId(){return this.currentUserId}cleanupUserSession(l){}handleLargeResponse(l,e){if(!l.success||!l.result)return l;let t=typeof l.result=="string"?l.result:JSON.stringify(l.result);if(this.tokenCounter.exceedsResponseLimit(t)){let s=this.createTempFile(t,e);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(t,s)}:{success:!0,result:this.tokenCounter.truncateOutput(t)}}return l}createTempFile(l,e){try{let t=Qo.tmpdir(),s=qe.join(t,"orion_tool_responses");we.existsSync(s)||we.mkdirSync(s,{recursive:!0});let n=Math.floor(Date.now()/1e3),o=Math.random().toString(36).substring(2,10),i=`${e}_${n}_${o}.txt`,a=qe.join(s,i);return we.writeFileSync(a,l,"utf8"),a}catch{return null}}stopAllRunningTools(){}}});import{spawn as Jo}from"child_process";var Et,nn=O(()=>{"use strict";U();Be();Et=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,n){let o=s.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=s.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(s.timeout!==void 0&&s.timeout!==null){if(typeof s.timeout=="string"){let T=Number(s.timeout);if(Number.isNaN(T))throw new Error(`Timeout must be a valid number. Received string: "${s.timeout}"`);a=T}else if(typeof s.timeout=="number"){if(Number.isNaN(s.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(s.timeout))throw new Error(`Timeout must be finite. Received: ${s.timeout}`);a=s.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof s.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 c=s.description;c!=null&&typeof c!="string"&&r.debug(`[RunCommandTool] Invalid description type: ${typeof c}, ignoring`);let u=!1;if(s.run_in_background!==void 0&&s.run_in_background!==null)if(typeof s.run_in_background=="boolean")u=s.run_in_background;else if(typeof s.run_in_background=="string")u=s.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof s.run_in_background}`);let d=Zs(o);if(d)return r.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let h=en(o);if(h.isDelete){r.debug("[RunCommandTool] Delete command detected, requesting confirmation"),r.debug(`[RunCommandTool] Affected targets: ${h.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(Ge(),ls)),p=await T.getInstance().requestDeleteConfirmation(o,c);if(p==="declined")return r.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${o}
|
|
254
|
+
|
|
255
|
+
ALTERNATIVES (choose one):
|
|
256
|
+
• Rename instead: mv [file] [file].old or mv [file] [file].legacy
|
|
257
|
+
• Backup first: cp -r [path] [path].backup, then ask again
|
|
258
|
+
• Skip and continue: If not critical, move on to other tasks
|
|
259
|
+
• Ask user: Briefly confirm if they want to keep or remove it`}];if(p==="timeout")return r.debug("[RunCommandTool] Delete confirmation timed out"),[{type:"text",text:`No response (50s timeout). Command NOT executed: ${o}
|
|
260
|
+
|
|
261
|
+
User is likely busy or away. DON'T wait - choose an alternative:
|
|
238
262
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
263
|
+
IF NOT CRITICAL (old files, temp files, build artifacts):
|
|
264
|
+
• Rename to .legacy: mv [file] [file].legacy
|
|
265
|
+
• Rename to .bak: mv [file] [file].bak
|
|
266
|
+
• Just skip it and continue with your task
|
|
242
267
|
|
|
243
|
-
|
|
244
|
-
|
|
268
|
+
IF CRITICAL (user explicitly asked to delete):
|
|
269
|
+
• Create backup first: cp -r [path] [path].backup
|
|
270
|
+
• Then mention you'll need confirmation to delete later
|
|
245
271
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
272
|
+
DO NOT keep retrying the same delete command.`}];if(p==="error")return r.debug("[RunCommandTool] Delete confirmation failed"),[{type:"text",text:`Failed to show delete confirmation dialog. The command was NOT executed for safety.
|
|
273
|
+
|
|
274
|
+
Please try again or ask the user to confirm the deletion manually.`}];r.debug("[RunCommandTool] User confirmed delete command, proceeding")}let f=a||12e4,y=as();if(r.debug(`[RunCommandTool] Executing command on platform: ${y}`),r.debug(`[RunCommandTool] Command: ${o.substring(0,50)}${o.length>50?"...":""}`),c&&r.debug(`[RunCommandTool] Description: ${c}`),r.debug(`[RunCommandTool] Session: ${i}, Timeout: ${f}ms, Background: ${u}`),u)return this.executeBackground(e,o,f,n);try{let T=(await Promise.resolve().then(()=>(kt(),cs))).ToolCallingService.getInstance(),k={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:i,timeout:f})}},p=await T.executeTool(k),g="";if(p.success){let b=(p.result?.stdout||"").trim(),C=p.result?.exitCode??0;if(g=`Command: ${o}
|
|
275
|
+
`,g+=`Exit Code: ${C}
|
|
276
|
+
|
|
277
|
+
`,b.length>0){let S=b.split(`
|
|
278
|
+
`),x=S.slice(0,15);g+=x.join(`
|
|
279
|
+
`),S.length>15&&(g+=`
|
|
280
|
+
|
|
281
|
+
... (showing first 15 of ${S.length} lines)`)}else g+="(no output)";return[{type:"text",text:g}]}else{let b=p.error||"Unknown error",C=p.result?.exitCode??1;return g=`Command: ${o}
|
|
282
|
+
`,g+=`Exit Code: ${C}
|
|
283
|
+
|
|
284
|
+
`,g+=`Error:
|
|
285
|
+
${b}`,[{type:"text",text:g}]}}catch(T){return r.debug(`[RunCommandTool] Failed to execute bash command: ${T.message}`),[{type:"text",text:`Command: ${o}
|
|
286
|
+
Error: ${T.message}`}]}}async executeBackground(e,t,s,n){let o=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=n.workingDirectory||process.cwd();r.debug(`[RunCommandTool] Starting background process: ${o}`);let a,c;Ce()?(a="powershell.exe",c=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",c=["-c",t]);let u=Jo(a,c,{cwd:i,env:process.env,stdio:["ignore","pipe","pipe"],detached:!Ce()});u.unref();let d={id:o,command:t,startTime:new Date,status:"running",output:[],error:[],pid:u.pid};se.addProcess(d);let h=5*1024*1024,f=0,y=0;return u.stdout?.on("data",T=>{if(f<h){let k=T.toString();d.output.push(k),f+=k.length,f>=h&&d.output.push("[Output truncated - buffer limit reached]")}}),u.stderr?.on("data",T=>{if(y<h){let k=T.toString();d.error.push(k),y+=k.length,y>=h&&d.error.push("[Error output truncated - buffer limit reached]")}}),u.on("exit",T=>{r.debug(`[RunCommandTool] Background process ${o} exited with code ${T}`),se.updateProcess(o,{endTime:new Date,exitCode:T??0,status:(T??0)===0?"completed":"failed"})}),u.on("error",T=>{r.debug(`[RunCommandTool] Background process ${o} error: ${T.message}`),d.error.push(T.message),se.updateProcess(o,{endTime:new Date,status:"failed"})}),s&&setTimeout(()=>{let T=se.getProcess(o);T&&T.status==="running"&&(r.debug(`[RunCommandTool] Background process ${o} timed out, killing...`),We(u.pid,"SIGTERM"),setTimeout(()=>{let k=se.getProcess(o);k&&k.status==="running"&&We(u.pid,"SIGKILL")},3e3),se.updateProcess(o,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${s}ms`))},s),[{type:"text",text:`Background process started with ID: ${o}
|
|
287
|
+
PID: ${u.pid}
|
|
288
|
+
Use BashOutput tool to get output.`}]}ensureMeaningfulOutput(e,t,s){let n=(e||"").trim();return n.length===0?s?`✅ Command '${t}' executed successfully.
|
|
249
289
|
|
|
250
290
|
ℹ️ No output was produced, which may be expected for this operation. This typically means:
|
|
251
291
|
• The command completed without errors
|
|
@@ -262,102 +302,142 @@ If you expected output, the command may need different parameters or the operati
|
|
|
262
302
|
Consider:
|
|
263
303
|
• Checking the command syntax and parameters
|
|
264
304
|
• Verifying file permissions and paths
|
|
265
|
-
• Running the command with verbose flags for more details`:
|
|
305
|
+
• Running the command with verbose flags for more details`:n}}});var xt,on=O(()=>{"use strict";U();Be();xt=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,s,n){try{let o=s.bash_id||s.shell_id||s.task_id;if(!o)throw new Error("bash_id is required");if(typeof o!="string")throw new Error(`bash_id must be a string. Received: ${typeof o}`);r.debug(`[BashOutputTool] Retrieving output for process: ${o}`);let i=se.getProcess(o);if(!i)throw new Error(`Background process not found: ${o}`);let a=[...i.output,...i.error].join(""),c=i.status==="running",u=`Process ID: ${o}
|
|
306
|
+
`;if(u+=`Status: ${i.status}
|
|
307
|
+
`,u+=`PID: ${i.pid||"N/A"}
|
|
308
|
+
`,u+=`Command: ${i.command}
|
|
309
|
+
`,i.exitCode!==void 0&&(u+=`Exit Code: ${i.exitCode}
|
|
310
|
+
`),i.startTime&&(u+=`Started: ${i.startTime.toISOString()}
|
|
311
|
+
`),i.endTime){u+=`Ended: ${i.endTime.toISOString()}
|
|
312
|
+
`;let d=i.endTime.getTime()-i.startTime.getTime();u+=`Duration: ${d}ms
|
|
313
|
+
`}return u+=`
|
|
314
|
+
--- Output ---
|
|
315
|
+
`,a?u+=a:c?u+="(no output yet - process still running)":i.exitCode===0?u+=`Process completed successfully with no output.
|
|
316
|
+
|
|
317
|
+
Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:u+="(no output)",[{type:"text",text:u}]}catch(o){return r.debug(`[BashOutputTool] Error: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});var It,rn=O(()=>{"use strict";U();Be();It=class{toolNames=["kill_shell","KillShell"];async execute(e,t,s,n){try{let o=s.shell_id||s.bash_id||s.task_id;if(!o)throw new Error("shell_id is required");if(typeof o!="string")throw new Error(`shell_id must be a string. Received: ${typeof o}`);r.debug(`[KillShellTool] Killing process: ${o}`);let i=se.getProcess(o);if(!i)throw new Error(`Background process not found: ${o}`);if(i.status!=="running")throw new Error(`Process is not running (status: ${i.status})`);if(i.pid){We(i.pid,"SIGTERM"),setTimeout(()=>{i.status==="running"&&We(i.pid,"SIGKILL")},3e3),se.updateProcess(o,{status:"killed",endTime:new Date});let a=`Process ${o} (PID ${i.pid}) and its children killed successfully`;return r.debug(`[KillShellTool] ${a}`),[{type:"text",text:a}]}else throw new Error("Process has no PID")}catch(o){return r.debug(`[KillShellTool] Error: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});var us,Yo,At,an=O(()=>{"use strict";U();Be();us=class l{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){r.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return l.instance||(l.instance=new l),l.instance}startMonitoring(e,t,s){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let n=se.getProcess(e);if(!n)return{success:!1,error:`Process not found: ${e}`};if(n.status!=="running")return{success:!1,error:`Process already completed with status: ${n.status}`};let o=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:o,onComplete:s}),r.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),r.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let s=se.getProcess(e);if(!s){this.stopMonitoring(e);return}s.status!=="running"&&(r.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${s.status}`),t.onComplete&&t.onComplete(s),this.stopMonitoring(e),this.emitAutoPrompt(e,s,t.reason))}async emitAutoPrompt(e,t,s){try{let{FrontendWebSocketService:n}=await Promise.resolve().then(()=>(Ge(),ls)),o=n.getInstance();if(!o.isConnected()){r.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let i,a=t.output.join(`
|
|
318
|
+
`).substring(0,1e3),c=t.error.join(`
|
|
319
|
+
`).substring(0,500);t.status==="completed"?i=`Background process completed successfully (ID: ${e}, Exit: ${t.exitCode}).
|
|
320
|
+
|
|
321
|
+
Reason for monitoring: ${s}
|
|
266
322
|
|
|
267
|
-
|
|
268
|
-
|
|
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()||"")+`
|
|
323
|
+
Last output:
|
|
324
|
+
${a||"(no output)"}
|
|
272
325
|
|
|
273
|
-
|
|
326
|
+
Please review the output and continue with the task.`:t.status==="failed"?i=`Background process failed (ID: ${e}, Exit: ${t.exitCode}).
|
|
327
|
+
|
|
328
|
+
Reason for monitoring: ${s}
|
|
329
|
+
|
|
330
|
+
Error output:
|
|
331
|
+
${c||a||"(no output)"}
|
|
332
|
+
|
|
333
|
+
Please investigate the failure and suggest next steps.`:t.status==="killed"?i=`Background process was killed (ID: ${e}).
|
|
334
|
+
|
|
335
|
+
Reason for monitoring: ${s}
|
|
336
|
+
|
|
337
|
+
The process was terminated. Please check if this was intentional or if there was a timeout.`:i=`Background process ended with status: ${t.status} (ID: ${e}).
|
|
338
|
+
|
|
339
|
+
Reason for monitoring: ${s}`,o.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:s,message:i,timestamp:new Date().toISOString()}),r.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(n){r.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${n}`)}}getMonitoredCount(){return this.monitoredProcesses.size}getMonitoredIds(){return Array.from(this.monitoredProcesses.keys())}clear(){for(let[e,t]of this.monitoredProcesses)clearInterval(t.intervalId);this.monitoredProcesses.clear(),r.debug("[ProcessMonitoringService] Cleared all monitors")}},Yo=us.getInstance(),At=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,s,n){let o=s.shell_id,i=s.reason;if(!o||typeof o!="string"||o.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!i||typeof i!="string"||i.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(i.length>500)return[{type:"text",text:`Error: reason is too long (${i.length} characters). Maximum 500 characters allowed.`}];r.debug(`[MonitorRunningCliTool] Starting monitoring for ${o}`),r.debug(`[MonitorRunningCliTool] Reason: ${i}`);let a=Yo.startMonitoring(o,i);return a.success?(r.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${o}.
|
|
340
|
+
|
|
341
|
+
Reason: ${i}
|
|
342
|
+
|
|
343
|
+
You will be auto-prompted when the process completes. You can continue with other tasks in the meantime.
|
|
344
|
+
|
|
345
|
+
To check status manually, use BashOutput tool with shell_id: ${o}`}]):(r.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var Dt,cn=O(()=>{"use strict";U();Dt=class{toolNames=["grep","Grep"];async execute(e,t,s,n){let o=s.pattern,i=s.output_mode||"files_with_matches",a=s.path||process.cwd(),c=s.glob,u=s.type,d=s["-i"]===!0,h=s["-n"]===!0,f=s["-A"],y=s["-B"],T=s["-C"],k=s.multiline===!0,p=s.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:g}=await import("child_process"),{promisify:b}=await import("util"),C=b(g),S="rg",x=!0;try{await C("which rg")}catch{r.debug("[GrepTool] ripgrep not found, falling back to grep"),S="grep -r",x=!1}if(x){switch(d&&(S+=" -i"),h&&(S+=" -n"),i){case"files_with_matches":S+=" -l";break;case"count":S+=" -c";break;case"content":default:break}T!==void 0?S+=` -C ${T}`:(f!==void 0&&(S+=` -A ${f}`),y!==void 0&&(S+=` -B ${y}`)),k&&(S+=" -U --multiline-dotall"),S+=` "${o.replace(/"/g,'\\"')}"`,c&&(S+=` --glob="${c}"`),u&&(S+=` --type=${u}`),S+=` "${a}"`}else{switch(d&&(S+=" -i"),h&&(S+=" -n"),i){case"files_with_matches":S+=" -l";break;case"count":S+=" -c";break}T!==void 0?S+=` -C ${T}`:(f!==void 0&&(S+=` -A ${f}`),y!==void 0&&(S+=` -B ${y}`)),S+=` "${o.replace(/"/g,'\\"')}"`,c&&(S+=` --include="${c}"`),S+=` "${a}"`}p!==void 0&&p>0&&(S+=` | head -n ${p}`),r.debug(`[GrepTool] Executing: ${S}`);let{stdout:I,stderr:w}=await C(S,{maxBuffer:10*1024*1024});if(!I&&!w)return[{type:"text",text:"No matches found"}];let M=I||w;if(i==="content"&&M){let _=`
|
|
346
|
+
|
|
347
|
+
[Found ${M.trim().split(`
|
|
348
|
+
`).length} matching line(s)]`;return[{type:"text",text:M+_}]}return[{type:"text",text:M}]}catch(g){return g.code===1?[{type:"text",text:"No matches found"}]:(r.debug(`[GrepTool] Grep failed: ${g.message}`),g.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 Pt,ln=O(()=>{"use strict";U();Pt=class{toolNames=["glob","Glob"];async execute(e,t,s,n){let o=s.pattern,i=s.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:c}=await import("util"),u=c(a),d=o.replace(/\*\*/g,"*"),h=process.platform==="win32"?`dir /s /b "${i}\\${d}"`:`find "${i}" -name "${d}" 2>/dev/null`,{stdout:f}=await u(h);if(!f||f.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let y=f.trim().split(`
|
|
349
|
+
`);return[{type:"text",text:`Found ${y.length} file(s):
|
|
350
|
+
${y.join(`
|
|
351
|
+
`)}`}]}catch(a){return r.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Nt,un=O(()=>{"use strict";U();Nt=class{toolNames=["open_url"];async execute(e,t,s,n){let o=s.url;if(!o)throw new Error("Missing url argument");r.debug(`[OpenUrlTool] Opening URL: ${o}`),n.activeWebViewURLs.includes(o)||(n.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}"`,c=>{c?r.debug(`[OpenUrlTool] Failed to open URL in browser: ${c.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 Zo,execSync as Qc}from"child_process";import{promisify as er}from"util";function ze(){return process.platform==="win32"}function Rt(){return process.platform==="darwin"}function Ot(){return process.platform==="linux"}function ds(){return ze()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var Yc,dn=O(()=>{"use strict";Yc=er(Zo)});import*as W from"fs";import*as Y from"path";import*as q from"os";import{exec as pn}from"child_process";import{promisify as tr}from"util";var Ft,ps,ce,mn=O(()=>{"use strict";dn();Ft=tr(pn),ps=class l{static instance;fileName="device-knowledge.md";constructor(){this.ensureDirectoryExists()}static shared(){return l.instance||(l.instance=new l),l.instance}get orionDirectory(){return Y.join(q.homedir(),".orion")}getKnowledgeFilePath(){return Y.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!W.existsSync(this.orionDirectory))try{W.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),ze()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{pn(`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 W.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return W.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),W.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let s=(this.readDeviceKnowledge()||"")+`
|
|
352
|
+
|
|
353
|
+
`+e;return this.writeDeviceKnowledge(s)}getKnowledgeFileSize(){try{return W.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
|
|
274
354
|
|
|
275
355
|
`;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
|
|
276
356
|
|
|
277
357
|
`,e+=`## System Information
|
|
278
|
-
`,e+=`- **OS**: ${
|
|
279
|
-
`,e+=`- **Platform**: ${
|
|
280
|
-
`,e+=`- **Hostname**: ${
|
|
281
|
-
`,e+=`- **Architecture**: ${
|
|
282
|
-
`,e+=`- **CPU Cores**: ${
|
|
283
|
-
`,e+=`- **Memory**: ${this.formatBytes(
|
|
284
|
-
`,e+=`- **Username**: ${
|
|
285
|
-
`,e+=`- **Home Directory**: ${
|
|
286
|
-
|
|
287
|
-
`;let t=
|
|
358
|
+
`,e+=`- **OS**: ${q.type()} ${q.release()}
|
|
359
|
+
`,e+=`- **Platform**: ${q.platform()}
|
|
360
|
+
`,e+=`- **Hostname**: ${q.hostname()}
|
|
361
|
+
`,e+=`- **Architecture**: ${q.arch()}
|
|
362
|
+
`,e+=`- **CPU Cores**: ${q.cpus().length}
|
|
363
|
+
`,e+=`- **Memory**: ${this.formatBytes(q.totalmem())}
|
|
364
|
+
`,e+=`- **Username**: ${q.userInfo().username}
|
|
365
|
+
`,e+=`- **Home Directory**: ${q.homedir()}
|
|
366
|
+
|
|
367
|
+
`;let t=ds();e+=`## Shell Environment
|
|
288
368
|
`,e+=`- **Default Shell**: ${t}
|
|
289
369
|
`,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
|
|
290
370
|
`),e+=`
|
|
291
|
-
`;let
|
|
292
|
-
`,e+=
|
|
371
|
+
`;let s=[{command:"python3 --version",name:"Python 3"},{command:"python --version",name:"Python"},{command:"node --version",name:"Node.js"},{command:"npm --version",name:"npm"},{command:"pnpm --version",name:"pnpm"},{command:"yarn --version",name:"Yarn"},{command:"brew --version",name:"Homebrew"},{command:"git --version",name:"Git"},{command:"docker --version",name:"Docker"},{command:"java -version",name:"Java"},{command:"ruby --version",name:"Ruby"},{command:"php --version",name:"PHP"},{command:"go version",name:"Go"},{command:"rustc --version",name:"Rust"},{command:"cargo --version",name:"Cargo"},{command:"apt --version",name:"APT"},{command:"snap --version",name:"Snap"},{command:"flatpak --version",name:"Flatpak"},{command:"dnf --version",name:"DNF"},{command:"yum --version",name:"YUM"},{command:"pacman --version",name:"Pacman"},{command:"kubectl version --client",name:"kubectl"},{command:"podman --version",name:"Podman"},{command:"vagrant --version",name:"Vagrant"}],n=[];for(let u of s){let d=await this.getCommandVersion(u.command);d&&n.push(`- **${u.name}**: ${d}`)}n.length>0&&(e+=`## Development Tools
|
|
372
|
+
`,e+=n.join(`
|
|
293
373
|
`),e+=`
|
|
294
374
|
|
|
295
|
-
`);let o=[];if(
|
|
375
|
+
`);let o=[];if(Rt()){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 d of u)if(W.existsSync(d)){let h=Y.basename(d,".app");o.push(`- ${h}`)}}else if(ze()){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",Y.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",Y.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let d of u)if(W.existsSync(d)){let h=Y.basename(d).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");o.push(`- ${h}`)}}else if(Ot()){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:Y.join(q.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let f of u)W.existsSync(f.path)&&o.push(`- ${f.name}`);let d=["/usr/share/applications",Y.join(q.homedir(),".local/share/applications")],h=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let f of d)if(W.existsSync(f))try{let y=W.readdirSync(f);for(let T of y){let k=T.toLowerCase();for(let p of h)k.includes(p)&&!o.some(g=>g.toLowerCase().includes(p))&&o.push(`- ${T.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
|
|
296
376
|
`,e+=o.join(`
|
|
297
377
|
`),e+=`
|
|
298
378
|
|
|
299
379
|
`),e+=`## Important Directories
|
|
300
|
-
`,e+=`- **Home**: ${
|
|
301
|
-
`,e+=`- **Desktop**: ${
|
|
302
|
-
`,e+=`- **Documents**: ${
|
|
303
|
-
`,e+=`- **Downloads**: ${
|
|
304
|
-
`,
|
|
380
|
+
`,e+=`- **Home**: ${q.homedir()}
|
|
381
|
+
`,e+=`- **Desktop**: ${Y.join(q.homedir(),"Desktop")}
|
|
382
|
+
`,e+=`- **Documents**: ${Y.join(q.homedir(),"Documents")}
|
|
383
|
+
`,e+=`- **Downloads**: ${Y.join(q.homedir(),"Downloads")}
|
|
384
|
+
`,Rt()?(e+=`- **Applications**: /Applications
|
|
305
385
|
`,e+=`- **usr/local/bin**: /usr/local/bin
|
|
306
|
-
`):
|
|
386
|
+
`):ze()?(e+=`- **Program Files**: C:\\Program Files
|
|
307
387
|
`,e+=`- **Program Files (x86)**: C:\\Program Files (x86)
|
|
308
|
-
`,e+=`- **AppData**: ${
|
|
309
|
-
`,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||
|
|
310
|
-
`):
|
|
388
|
+
`,e+=`- **AppData**: ${Y.join(q.homedir(),"AppData")}
|
|
389
|
+
`,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||Y.join(q.homedir(),"AppData","Local")}
|
|
390
|
+
`):Ot()&&(e+=`- **/usr/bin**: /usr/bin
|
|
311
391
|
`,e+=`- **/usr/local/bin**: /usr/local/bin
|
|
312
392
|
`,e+=`- **/opt**: /opt
|
|
313
|
-
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||
|
|
314
|
-
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||
|
|
315
|
-
`,
|
|
316
|
-
`),
|
|
393
|
+
`,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||Y.join(q.homedir(),".config")}
|
|
394
|
+
`,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||Y.join(q.homedir(),".local/share")}
|
|
395
|
+
`,W.existsSync("/snap")&&(e+=`- **Snap**: /snap
|
|
396
|
+
`),W.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
|
|
317
397
|
`)),e+=`
|
|
318
398
|
`,e+=`## Network
|
|
319
|
-
`,e+=`- **Hostname**: ${
|
|
320
|
-
`;let i=
|
|
399
|
+
`,e+=`- **Hostname**: ${q.hostname()}
|
|
400
|
+
`;let i=q.networkInterfaces(),a=Object.values(i).flat().find(u=>u&&!u.internal&&u.family==="IPv4");a&&(e+=`- **IP Address**: ${a.address}
|
|
321
401
|
`),e+=`
|
|
322
|
-
`;let
|
|
323
|
-
`,e+=
|
|
402
|
+
`;let c=await this.detectEnvironment();return c&&(e+=`## Environment
|
|
403
|
+
`,e+=c,e+=`
|
|
324
404
|
`),e+=`## URL Handling Rules
|
|
325
405
|
`,e+=`- **Redirect URLs**: Any shortened URL should be resolved to get the actual destination URL.
|
|
326
406
|
`,e+=`- **File Downloads**: Always follow redirects to ensure proper file access and downloads.
|
|
327
407
|
|
|
328
|
-
`,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let
|
|
329
|
-
`),o=[],i=!1,a=!1;for(let u of
|
|
330
|
-
`);return this.writeDeviceKnowledge(
|
|
331
|
-
${t}`,i=this.readDeviceKnowledge()||"";if(i.includes(`## ${
|
|
332
|
-
`),
|
|
333
|
-
`);return this.writeDeviceKnowledge(
|
|
334
|
-
`):null}async getCommandVersion(e){try{let t=
|
|
335
|
-
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let
|
|
408
|
+
`,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let n=(this.readDeviceKnowledge()||"").split(`
|
|
409
|
+
`),o=[],i=!1,a=!1;for(let u of n)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 c=o.join(`
|
|
410
|
+
`);return this.writeDeviceKnowledge(c)}addNote(e,t,s="Notes"){let n=new Date().toLocaleString(),o=`### ${e} (${n})
|
|
411
|
+
${t}`,i=this.readDeviceKnowledge()||"";if(i.includes(`## ${s}`)){let a=i.split(`
|
|
412
|
+
`),c=[],u=!1,d=!1;for(let f of a)f.startsWith(`## ${s}`)?(u=!0,c.push(f)):f.startsWith("## ")&&u&&!d?(c.push(""),c.push(o),c.push(""),c.push(f),u=!1,d=!0):c.push(f);u&&!d&&(c.push(""),c.push(o));let h=c.join(`
|
|
413
|
+
`);return this.writeDeviceKnowledge(h)}else return this.updateKnowledgeSection(s,o)}deleteDeviceKnowledge(){try{return W.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return W.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=W.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(Ot()){try{let{stdout:s}=await Ft("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),n=s.trim();n&&n!=="none"&&e.push(`- **Virtualization**: ${n}`)}catch{}if(W.existsSync("/proc/cpuinfo"))try{W.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(n=>n.includes("Virtualization"))||e.push("- **Virtualization**: VM detected (hypervisor flag)"))}catch{}let t=["/sys/class/dmi/id/product_name","/sys/class/dmi/id/sys_vendor","/sys/class/dmi/id/board_vendor"];for(let s of t)if(W.existsSync(s))try{let n=W.readFileSync(s,"utf8").trim().toLowerCase();if(n.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(n.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(n.includes("kvm")||n.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(n.includes("hyper-v")||n.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(n.includes("xen")){e.push("- **VM Type**: Xen");break}else if(n.includes("amazon")||n.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(n.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(n.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(W.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),W.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),W.existsSync("/proc/version"))try{let s=W.readFileSync("/proc/version","utf8");(s.toLowerCase().includes("microsoft")||s.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(W.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),W.existsSync("/etc/os-release"))try{let n=W.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);n&&e.push(`- **Distribution**: ${n[1]}`)}catch{}}else if(Rt())try{let{stdout:t}=await Ft('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(ze())try{let{stdout:t}=await Ft('systeminfo | findstr /i "System Model"',{timeout:5e3}),s=t.toLowerCase();(s.includes("virtual")||s.includes("vmware")||s.includes("virtualbox"))&&e.push(`- **Environment**: ${t.split(":")[1]?.trim()||"Virtual Machine"}`)}catch{}(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)&&e.push("- **Access**: SSH Session"),process.env.TMUX&&e.push("- **Terminal Multiplexer**: tmux"),process.env.STY&&e.push("- **Terminal Multiplexer**: screen")}catch{}return e.length>0?e.join(`
|
|
414
|
+
`):null}async getCommandVersion(e){try{let t=ds(),{stdout:s,stderr:n}=await Ft(e,{timeout:5e3,shell:t,windowsHide:!0});return(s+n).trim().split(`
|
|
415
|
+
`)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let s=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,s)*100)/100+" "+t[s]}},ce=ps.shared()});var $t,gn=O(()=>{"use strict";U();fe();mn();$t=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,n){let o=s.action,i=Date.now();r.debug(`[ManageDeviceKnowledgeTool] Executing action: ${o}`),$.start("ManageDeviceKnowledge",o);try{let a,c=!0;switch(o){case"read":{let d=ce.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await ce.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${ce.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",c=!1);break}case"write":{let d=s.content;d?ce.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",c=!1):(a='Error: Missing "content" argument for write action.',c=!1);break}case"append":{let d=s.content;d?ce.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",c=!1):(a='Error: Missing "content" argument for append action.',c=!1);break}case"update_section":{let d=s.section,h=s.content;!d||!h?(a='Error: Missing "section" or "content" argument for update_section action.',c=!1):ce.updateKnowledgeSection(d,h)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,c=!1);break}case"add_note":{let d=s.title,h=s.content,f=s.category||"Notes";!d||!h?(a='Error: Missing "title" or "content" argument for add_note action.',c=!1):ce.addNote(d,h,f)?a=`Note "${d}" added to ${f} successfully.`:(a=`Failed to add note "${d}".`,c=!1);break}case"delete":{ce.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",c=!1);break}case"path":{a=ce.getKnowledgeFilePath();break}case"exists":{a=ce.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${ce.getKnowledgeFileSize()} bytes`;break}case"export":{let d=s.destination;d?ce.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,c=!1):(a='Error: Missing "destination" argument for export action.',c=!1);break}case"import":{let d=s.source;d?ce.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,c=!1):(a='Error: Missing "source" argument for import action.',c=!1);break}default:a=`Unknown action: ${o}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,c=!1}let u=Date.now()-i;return $.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:c,executionTime:u}),[{type:"text",text:a}]}catch(a){r.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let c=`Error managing device knowledge: ${a.message}`,u=Date.now()-i;return $.result({toolName:"ManageDeviceKnowledge",output:c,success:!1,executionTime:u}),[{type:"text",text:c}]}}}});var _t,hn=O(()=>{"use strict";U();_t=class{toolNames=["operator_status"];async execute(e,t,s,n){let o=s.taskId,i=s.status,a=s.message;return r.debug(`[OperatorStatusTool] Operator status - Task ${o}: ${i} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Mt,fn=O(()=>{"use strict";U();Mt=class{toolNames=["provide_input"];async execute(e,t,s,n){let o=s.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(()=>(kt(),cs))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:o})}},c=await i.executeTool(a);return c.success?[{type:"text",text:c.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${c.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 sr}from"child_process";import{promisify as nr}from"util";import*as Lt from"fs/promises";import*as vn from"path";import*as bn from"os";var or,Xe,ms=O(()=>{"use strict";U();or=nr(sr),Xe=class l{static instance;constructor(){}static getInstance(){return l.instance||(l.instance=new l),l.instance}async captureScreen(){try{let e=vn.join(bn.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;
|
|
336
416
|
[System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
|
|
337
417
|
Start-Sleep -Milliseconds 100;
|
|
338
418
|
$img = [System.Windows.Forms.Clipboard]::GetImage();
|
|
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
|
|
419
|
+
$img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return r.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await or(t);let s=await Lt.readFile(e),n=s.toString("base64");return await Lt.unlink(e).catch(()=>{}),r.debug(`[SCREENSHOT] Captured screenshot: ${s.length} bytes`),`data:image/jpeg;base64,${n}`}catch(e){return r.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
|
|
340
420
|
⚠️ 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
|
|
341
421
|
`)):process.platform==="darwin"&&(console.log(`
|
|
342
422
|
⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
|
|
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:`
|
|
423
|
+
`)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var Ut,Tn=O(()=>{"use strict";U();ms();Ut=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,s,n){r.debug("[TakeScreenshotTool] Capturing screenshot...");try{let i=await Xe.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 yn(l){l.register(new ft),l.register(new bt),l.register(new Tt),l.register(new yt),l.register(new wt),l.register(new St),l.register(new Ct),l.register(new Et),l.register(new xt),l.register(new It),l.register(new At),l.register(new Dt),l.register(new Pt),l.register(new Nt),l.register(new $t),l.register(new _t),l.register(new Mt),l.register(new Ut)}var wn=O(()=>{"use strict";Gs();zs();Xs();js();Ks();Vs();Qs();nn();on();rn();an();cn();ln();un();gn();hn();fn();Tn()});var Wt,Sn=O(()=>{"use strict";Wt=class{constructor(e,t,s,n,o){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=n;this.activeWebViewURLs=o}}});var ls={};ge(ls,{FrontendWebSocketService:()=>J});import{EventEmitter as rr}from"events";import{io as ir}from"socket.io-client";import Cn from"os";import ar from"path";var J,Ge=O(()=>{"use strict";U();Ae();ie();_e();Le();Zt();Ws();wn();Sn();J=class l extends rr{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";keepaliveWatchdog=null;lastKeepaliveTime=null;baseKeepaliveTimeout=12e4;extendedKeepaliveTimeout=6e5;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 de;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,s="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=ae.getInstance(),this.authService=G.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new mt,yn(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 l.instance||(l.instance=new l),l.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return 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){let s=this.sessionId;this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0?(r.debug("[FRONTEND WS] Session ID changing but active work exists"),r.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),r.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),r.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(s)):(r.debug("[FRONTEND WS] Session ID changed! Disconnecting old connection..."),this.disconnect("session_id_changed",!1))}if(this.sessionId=t,e&&e!==this.userId&&(this.userId=e),this.userId){let s=this.generateUniqueDeviceId(this.userId,"node");if(s&&this.deviceId!==s)r.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${s}`),this.deviceId=s;else if(!s)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(s){throw new Error(`Failed to get authentication token: ${s}`)}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=ir(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.stopKeepaliveWatchdog(),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,s)=>{let n=setTimeout(()=>{this.connectionPromise=null,s(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(n),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(n),this.connectionPromise=null,s(o)},timeoutId:n}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{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=>{r.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{r.debug("[FRONTEND WS] Shell cleanup request received"),this.handleShellCleanup(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("reconnection_requested",e=>{r.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{r.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("get_image_for_annotation",e=>{r.debug(`[FRONTEND WS] Image for annotation request received - ID: ${e.id}, Path: ${e.image_path}`),this.handleImageForAnnotationRequest(e)}),this.socket.on("delete_confirmation_response",e=>{this.handleDeleteConfirmationResponse(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.startKeepaliveWatchdog(),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.stopKeepaliveWatchdog(),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,s=t?.type||t?.stop_type||"all";switch(r.debug(`[FRONTEND WS] Stop type: ${s}`),s){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:r.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.session_id,s=e.reason||"backend_stop";if(r.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${s}`),t&&this.sessionId&&t!==this.sessionId){r.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(s)}stopAllActiveTools(e){r.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),r.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),r.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),r.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(r.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(r.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(r.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),r.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}handleCheckpointRequest(e){r.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,s=t.checkpoint_id,n=t.session_id,o=t.iteration;if(!s||!n||o===void 0){r.warn("[FRONTEND WS] Invalid checkpoint request format");return}r.debug(`[FRONTEND WS] Checkpoint request - ID: ${s}, Session: ${n}, Iteration: ${o}`);let i=he.getInstance(),a=i.getQueuedMessages(),c=a.map(d=>({content:d.content,timestamp:Math.floor(d.timestamp.getTime())})),u=c.length>0;r.debug(`[FRONTEND WS] Sending checkpoint response with ${c.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:s,session_id:n,has_feedback:u,feedback:c}),u&&(r.info(`Sent ${c.length} feedback message(s) to AI`),this.emit("feedback:sent",a),i.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,s=e.isNew;if(!t||s===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:s})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){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 handleReconnectionRequest(e){let t=e.reason||"unknown",s=e.lastPingAge||0;if(r.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),r.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(s/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){r.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){r.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){r.debug("[FRONTEND WS] Initiating forced reconnection...");let n=this.sessionId,o=this.userId,i=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(o,n)?(r.debug("[FRONTEND WS] Reconnection successful!"),r.debug(`[FRONTEND WS] Composite key: ${i}_${n}`)):r.error("[FRONTEND WS] Reconnection failed")}catch(a){r.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else r.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:s}=e;r.debug(`[FRONTEND WS] Sub-agent event: ${t}`,s);try{Us.handleEvent({type:t,...s}),r.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(n){r.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${n}`)}this.emit("subAgentEvent",{type:t,...s,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:s,timeout:n=3e4}=e;r.debug(`[FRONTEND WS] Processing image for annotation: ${s}`);try{let o=await import("fs/promises"),i=await import("path");try{await o.access(s)}catch{r.error(`[FRONTEND WS] Image file not found: ${s}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Image file not found: ${s}`});return}let c=(await o.readFile(s)).toString("base64"),u=i.extname(s).toLowerCase(),d="image/png";u===".jpg"||u===".jpeg"?d="image/jpeg":u===".gif"?d="image/gif":u===".webp"&&(d="image/webp"),this.socket?.emit("image_for_annotation_response",{id:t,success:!0,image_data:`data:${d};base64,${c}`,mime_type:d,file_path:s}),r.debug(`[FRONTEND WS] Image sent for annotation: ${s}`)}catch(o){r.error(`[FRONTEND WS] Failed to read image for annotation: ${o.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${o.message}`})}}async handleToolExecutionRequest(e){this.updateKeepalive();let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},s=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(r.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,s,e.data?.arguments)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){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,s){this.activeToolCount++;let n=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 Wt(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,s)}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()-n)/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(s){r.error(`[FRONTEND WS] Failed to send message: ${s}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;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(s){r.error(`[FRONTEND WS] Failed to send queued tool result: ${s}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,s,n,o){this.updateKeepalive();let i;if(n&&typeof n=="object"&&"content"in n&&Array.isArray(n.content))i=n.content;else{let a;typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),i=this.createContentBlocks(a,o,s)}if(o){let a=this.createDeviceKnowledgeReminderBlock();i.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:i,success:!0,error:null})}sendToolError(e,t,s,n){let o=this.createContentBlocks(n.message,!1,s);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:o,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
|
|
344
424
|
|
|
345
|
-
UPDATE DEVICE KNOWLEDGE: ${
|
|
425
|
+
UPDATE DEVICE KNOWLEDGE: ${ar.join(Cn.homedir(),".orion","device-knowledge.md")}
|
|
346
426
|
Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
|
|
347
|
-
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,
|
|
427
|
+
Actions: READ current file, ADD new learnings, REPLACE outdated info, ORGANIZE by categories.`}}createContentBlocks(e,t,s){let n=e.trim();n.length===0&&(t?n=`Command '${s}' executed successfully.
|
|
348
428
|
|
|
349
|
-
No output was produced, which may be expected for this operation.`:
|
|
350
|
-
`);try{let{PersonalAgentService:i}=await Promise.resolve().then(()=>(
|
|
429
|
+
No output was produced, which may be expected for this operation.`:n=`Command '${s}' failed but no error message was provided.`);try{let o=JSON.parse(n);if(Array.isArray(o)){let 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:n}]}async handleLargeResponse(e,t,s,n,o,i){let a;if(typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),s==="take_screenshot"||s==="take_current_screenshot"){await this.sendToolResult(e,t,s,n,o);return}if(["read","read_special_file","read_file","readspecialfile"].includes(s.toLowerCase())&&n?.metadata?.isImage===!0){r.debug(`[FRONTEND WS] Image file detected from ${s} tool, bypassing token limit`),await this.sendToolResult(e,t,s,n,o);return}if(this.tokenCounter.exceedsResponseLimit(a)){let u=this.tokenCounter.count(a);if(r.debug(`[FRONTEND WS] Response too large (${u} tokens), creating temp file`),s.toLowerCase()==="read"&&i?.file_path){let y=i.file_path,T=this.tokenCounter.formatLargeFileMessage(a,y);await this.sendToolResult(e,t,s,T,o);return}let h=await this.createTempFile(a,s);if(!h){r.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,s,this.tokenCounter.truncateOutput(a),o);return}let f=this.tokenCounter.formatLargeResponsePreview(a,h);await this.sendToolResult(e,t,s,f,o)}else await this.sendToolResult(e,t,s,a,o)}async createTempFile(e,t){try{let s=await import("fs/promises"),n=await import("path"),o=Math.floor(Date.now()/1e3),i=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${i}.txt`,c=Cn.homedir(),u=n.join(c,".orion","tool_outputs");await s.mkdir(u,{recursive:!0});let d=n.join(u,a);return await s.writeFile(d,e,"utf-8"),r.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(s){return r.error(`[FRONTEND WS] Failed to create temp file: ${s}`),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`)}}getKeepaliveTimeout(){return this.activeToolExecutions.size>0?this.extendedKeepaliveTimeout:this.baseKeepaliveTimeout}startKeepaliveWatchdog(){this.lastKeepaliveTime=new Date,this.stopKeepaliveWatchdog(),this.keepaliveWatchdog=setInterval(()=>{if(!this.lastKeepaliveTime)return;let e=this.getKeepaliveTimeout(),t=Date.now()-this.lastKeepaliveTime.getTime();r.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(r.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),r.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){r.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(r.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}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(s){r.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.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 requestDeleteConfirmation(e,t){if(!this.isConnected())return r.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let s=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return r.debug(`[FRONTEND WS] Requesting delete confirmation: ${s}`),r.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(n=>{let o=setTimeout(()=>{this.pendingDeleteConfirmations.get(s)&&(r.debug(`[FRONTEND WS] Delete confirmation timed out: ${s}`),this.pendingDeleteConfirmations.delete(s),n("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(s,{resolve:n,timeoutId:o}),this.socket?.emit("delete_confirmation_request",{confirmationId:s,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),r.debug(`[FRONTEND WS] Delete confirmation request sent: ${s}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:s}=e;r.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${s}`);let n=this.pendingDeleteConfirmations.get(t);if(!n){r.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(n.timeoutId),this.pendingDeleteConfirmations.delete(t);let o=s;n.resolve(["confirmed","declined","timeout","error"].includes(s)?o:"error")}async captureFrontendToolResultForHistory(e,t,s,n){let o=t.map(i=>i.text||"").join(`
|
|
430
|
+
`);try{let{PersonalAgentService:i}=await Promise.resolve().then(()=>(Se(),He)),a=i.getInstance(),c=n?`Error: ${n}`:o;a.captureFrontendToolResult(e,c,s),r.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(i){r.debug(`[FRONTEND WS] Could not capture tool result: ${i}`)}}scheduleOldSessionCleanup(e){let n=Date.now(),o=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){r.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-n>6e4){r.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(r.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(o,2e3)};r.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(o,2e3)}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.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=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 Pe,kn=O(()=>{"use strict";Pe=class{static contextRegex=/<context>[\s\S]*?<\/context>/gi;static agentSystemReminderRegex=/<agent_system_reminder>[\s\S]*?<\/agent_system_reminder>/gi;static systemReminderRegex=/<system-reminder>[\s\S]*?<\/system-reminder>/gi;static multipleNewlinesRegex=/\n{3,}/g;static cache=new Map;static MAX_CACHE_SIZE=50;static lastInput="";static lastOutput="";static quickHash(e){let t=e.length;if(t===0)return"0";if(t<100)return`${t}:${e.slice(0,20)}`;let s=Math.floor(t/2);return`${t}:${e.charCodeAt(0)}:${e.charCodeAt(s)}:${e.charCodeAt(t-1)}`}static remove(e){if(!e)return e;if(e===this.lastInput)return this.lastOutput;if(!(e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")))return this.lastInput=e,this.lastOutput=e,e;let s=this.quickHash(e),n=this.cache.get(s);if(n!==void 0)return this.lastInput=e,this.lastOutput=n,n;let o=e;if(e.includes("<context>")&&(o=o.replace(this.contextRegex,"")),e.includes("<agent_system_reminder>")&&(o=o.replace(this.agentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(o=o.replace(this.systemReminderRegex,"")),o=o.replace(this.multipleNewlinesRegex,`
|
|
351
431
|
|
|
352
|
-
`),
|
|
432
|
+
`),o=o.trim(),this.cache.size>=this.MAX_CACHE_SIZE){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}return this.cache.set(s,o),this.lastInput=e,this.lastOutput=o,o}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});var He={};ge(He,{PersonalAgentService:()=>ne});import{EventEmitter as cr}from"events";import gs from"axios";import lr from"http";import ur from"https";import{v4 as Ne}from"uuid";import be from"fs";import rt from"path";import je from"os";var it,ne,Se=O(()=>{"use strict";$e();ie();Ge();_e();Ae();U();kn();it=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code,n=e?.status||e?.statusCode||e?.response?.status,o=String(s||""),i=Number(n);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(o)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||i===401||i===403||o==="401"||o==="403"?"critical":"parsing"}},ne=class l extends cr{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;activeToolNames=new Set;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;constructor(){super(),this.authService=G.getInstance(),this.httpAgent=new lr.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new ur.Agent({keepAlive:!0,timeout:36e5}),r.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),J.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(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=Kn("fs");if(t.existsSync("/etc/os-release")){let n=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(n)return n[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return be.existsSync(e)?t=be.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
|
|
353
433
|
|
|
354
434
|
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.
|
|
355
435
|
|
|
356
|
-
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=
|
|
436
|
+
Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=rt.join(je.homedir(),".orion");return rt.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(be.existsSync(e))return;let t=rt.join(je.homedir(),"Documents","orion","orion-device-knowledge.md");if(be.existsSync(t)){r.info("📦 Migrating device knowledge to cross-platform location...");let s=rt.dirname(e);be.existsSync(s)||be.mkdirSync(s,{recursive:!0});let n=be.readFileSync(t,"utf8");be.writeFileSync(e,n,"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=rt.dirname(e);be.existsSync(t)||be.mkdirSync(t,{recursive:!0});let s=je.platform(),n=je.arch(),o=je.hostname(),i=je.userInfo(),a=`# Device Knowledge
|
|
357
437
|
|
|
358
438
|
## System Information
|
|
359
|
-
- **Platform**: ${
|
|
360
|
-
- **Architecture**: ${
|
|
439
|
+
- **Platform**: ${s}
|
|
440
|
+
- **Architecture**: ${n}
|
|
361
441
|
- **Hostname**: ${o}
|
|
362
442
|
- **Username**: ${i.username}
|
|
363
443
|
- **Home Directory**: ${i.homedir}
|
|
@@ -373,84 +453,96 @@ Remember to update memory about device if any new information is learned during
|
|
|
373
453
|
|
|
374
454
|
---
|
|
375
455
|
*Last updated: ${new Date().toISOString()}*
|
|
376
|
-
`;return
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
`,this.
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
`,this.
|
|
386
|
-
`,
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
`,this.
|
|
391
|
-
|
|
392
|
-
${
|
|
456
|
+
`;return be.writeFileSync(e,a,"utf8"),a}catch{return"Basic device knowledge initialization failed."}}static getInstance(){return l.instance||(l.instance=new l),l.instance}generateRequestHash(e,t){let s=`${e}:${t}:${Date.now()}`,n=0;for(let o=0;o<s.length;o++){let i=s.charCodeAt(o);n=(n<<5)-n+i,n=n&n}return n.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<500||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,s,n=.7,o=!0,i,a,c){let u=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(u))return r.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(u),this.lastRequestHash=u,this.lastRequestTime=Date.now(),this.currentPromptId=Ne(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=s;let d=c?.crossDeviceTaskId;d&&r.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),c?.mode==="new"&&(t=[],r.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let h=i||this.authService.getUserId();r.debug("🔌 WebSocket will connect after receiving sessionId from API...");let f=ae.getInstance().getCurrentDeviceId();if(!f)throw r.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let y={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:e},...a.map(T=>({type:"image_url",image_url:{url:T}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:f,model:s.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(c?.conversationId)y.conversationId=c.conversationId,r.debug(`[PERSONAL AGENT] Sending request with conversationId: ${c.conversationId}`),r.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let T=t.map(k=>{let p,g=k;g.metadata?.toolResults?p=g.metadata.toolResults:g.originalContent?p=g.originalContent:p=typeof k.content=="string"?k.content:JSON.stringify(k.content);let b=[{type:"text",text:p}];return g.imageUrls&&g.imageUrls.length>0&&b.push(...g.imageUrls.map(C=>({type:"image_url",image_url:{url:C}}))),{role:k.role,content:b}});for(let k=0;k<T.length;k++)T[k].role;y.messages=T,r.debug(`[PERSONAL AGENT] Sending request with ${T.length} messages (new conversation)`)}else r.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return o?this.performStreamingToolCall(y,u):this.performNonStreamingToolCall(y,u)}async performStreamingToolCall(e,t){let s=await this.getFirebaseIdToken();return s||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((n,o)=>{this.currentAbortController=new AbortController;let i="",a=Buffer.alloc(0),c="",u="",d=[],h=null,f=!1,y="";this.currentOutput="",this.completeOutputWithToolResults="";let T=new Map,k=new Set,p=this.authService.getUserId();gs.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 ${s||this.getAuthToken()}`}}).then(async g=>{let b=g.data,C=g.headers["x-session-id"]||g.headers["session-id"];if(C){h=C,this.currentSessionId=C,r.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${C}`);let S=J.getInstance();r.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await S.connectForConversation(p||void 0,C)?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");b.on("data",S=>{try{a=Buffer.concat([a,S]);let M="",j=0;for(let _=0;_<a.length;_++)try{M=a.slice(0,_+1).toString("utf8"),j=_+1}catch{break}if(j>0){let _=a.slice(0,j);a=a.slice(j),i+=_.toString("utf8")}}catch{i+=S.toString()}let x=[/\r?\n/,/\r/],I=[],w=i;I=w.split(/\r?\n/),w=I.pop()||"",i=w;for(let M of I){let j=M.trim();if(!(!j||j.startsWith(":"))){if(j.startsWith("event: keepalive")){r.debug("[PERSONAL AGENT] Received keepalive event"),this.emit("keepalive");continue}if(j.startsWith("data: ")){let _=j.slice(6).trim();if(_==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",c),n(c);return}try{let D=JSON.parse(_);if(D.type==="session_start"&&D.conversationId){let P=D.conversationId,v=D.isNewConversation||!1,A=D.title;r.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),r.debug(`[PERSONAL AGENT] conversationId: ${P}`),r.debug(`[PERSONAL AGENT] isNewConversation: ${v}`),A&&r.debug(`[PERSONAL AGENT] title: "${A}"`),this.emit("conversation_id_received",{conversationId:P,isNew:v,title:A||void 0});continue}if(D.type==="title_generated"&&D.title&&D.conversationId){let P=D.title,v=D.conversationId;r.debug("[PERSONAL AGENT] Received title_generated event!"),r.debug(`[PERSONAL AGENT] conversationId: ${v}`),r.debug(`[PERSONAL AGENT] title: "${P}"`),this.emit("conversation_title_updated",{conversationId:v,title:P});continue}if(D.type==="error"||D.error){let P=D.error||D,v=P.message||"Unknown error occurred",A=P.status||500,N=P.provider||"unknown";r.debug(`[PERSONAL AGENT] API Error - Status: ${A}, Provider: ${N}`),r.debug(`[PERSONAL AGENT] Error Message: ${v}`);let F=v;try{let z=JSON.parse(v);z.error?.message&&(F=z.error.message)}catch{}let L;A===503?L=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
|
|
457
|
+
|
|
458
|
+
Details: ${F}`:A>=500?L=`Server Error (${A}): The AI service encountered an internal error. Please try again.
|
|
459
|
+
|
|
460
|
+
Details: ${F}`:A===429?L="Rate Limit Exceeded: You've made too many requests. Please wait a moment before trying again.":L=`Error: ${F}`,this.emit("api_error",{status:A,provider:N,message:L,originalMessage:v}),u+=L+`
|
|
461
|
+
`,this.currentOutput+=L+`
|
|
462
|
+
`;continue}if(D.tool_response&&D.tool_response.content){let P=D.tool_response.content,v=D.tool_response.id||"unknown",A=D.tool_response.name||"unknown";this.emit("tool_completed",{toolName:A,toolId:v,result:P,todos:D.tool_response.todos||null}),this.emit("toolComplete",A);let N="";Array.isArray(P)?N=P.map(L=>typeof L=="string"?L:L&&typeof L=="object"&&(L.text||L.content)||"").join(""):typeof P=="string"?N=P:N=JSON.stringify(P),(!N||N.trim().length===0)&&(N="(empty tool result)");let F=`<context>
|
|
463
|
+
${N}
|
|
464
|
+
</context>`;d.push(F),c+=F+`
|
|
465
|
+
`,this.completeOutputWithToolResults+=F+`
|
|
466
|
+
`,this.currentOutput+=F+`
|
|
467
|
+
`;continue}if(D.tool_calls){r.debug("Processing tool calls:",D.tool_calls.length,"items");for(let[P,v]of D.tool_calls.entries())if(r.debug("Tool call ["+P+"]:"),v.id){r.debug("Processing tool call ID:",v.id);let A=T.get(v.id)||{};for(let[N,F]of Object.entries(v))if(N==="function"&&typeof F=="object"&&F!==null){let L=A.function||{},z=F;for(let[Q,te]of Object.entries(z))if(Q==="arguments"&&typeof te=="string"){let Te=L.arguments||"";L.arguments=Te+te}else L[Q]=te;A.function=L}else A[N]=F;if(T.set(v.id,A),A.function?.name&&!k.has(v.id)){let N=A.function.name;r.debug("[TOOL-DISPLAY] Showing tool call:",N,"ID:",v.id),this.activeToolNames.add(N);let F;if(A.function?.arguments)try{let L=A.function.arguments;(L.endsWith("}")||L.endsWith('"}'))&&(F=JSON.parse(L))}catch{}this.emit("toolExecuting",{toolCallId:v.id,name:N,arguments:F,startTime:new Date})}if(A.function?.arguments&&A.function?.name){let N=A.function.arguments;N.endsWith("}")||N.endsWith('"}')?(r.debug("Complete tool call accumulated:",v.id,"-",A.function.name),r.debug("Arguments:",N.substring(0,100)+(N.length>100?"...":"")),k.has(v.id)||(k.add(v.id),this.handleCompleteToolCall(A))):r.debug("Partial tool call:",v.id,"-",A.function.name)}}}else if(D.tool_response&&D.tool_response.content){let P=D.tool_response.content,v=D.tool_response.id||"unknown",A=D.tool_response.name||"unknown",N=D.tool_response.role||"unknown";r.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),r.debug(" Tool ID:",v),r.debug(" Tool Name:",A),r.debug(" Tool Role:",N),r.debug(" Content Length:",P.length),r.debug(" Content Preview:",P.substring(0,200)+"..."),this.activeToolNames.delete(A),this.emit("tool_completed",{toolName:A,toolId:v,result:P,todos:D.tool_response.todos||null}),this.emit("toolComplete",A),D.tool_response.todos&&Array.isArray(D.tool_response.todos)&&(r.debug("[PERSONAL AGENT] Tool response contains",D.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:D.tool_response.todos}));let F=`<context>
|
|
468
|
+
${P}
|
|
469
|
+
</context>`;d.push(F),c+=F+`
|
|
470
|
+
`,this.completeOutputWithToolResults+=F+`
|
|
471
|
+
`,this.currentOutput+=F+`
|
|
472
|
+
`,r.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",d.length)}else if(D.content!==void 0){let P=D.content;if(P&&P.length>0&&r.debug(`[STREAMING] Received content chunk: "${P}" (length: ${P.length})`),P&&P.includes('{"tool_response"'))try{let v,A=!1;try{v=JSON.parse(P),A=!0}catch{let N=P.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(N){let F=N[0];v=JSON.parse(F),A=!1}}if(v&&v.tool_response&&v.tool_response.content){let N=v.tool_response.content,F=v.tool_response.id||"unknown",L=v.tool_response.name||"unknown";this.emit("tool_completed",{toolName:L,toolId:F,result:N,todos:v.tool_response.todos||null}),this.emit("toolComplete",L),v.tool_response.todos&&Array.isArray(v.tool_response.todos)&&this.handleTodoUpdate({items:v.tool_response.todos});let z="";Array.isArray(N)?z=N.map(te=>te.text||"").join(""):typeof N=="string"?z=N:z=JSON.stringify(N);let Q=`<context>
|
|
473
|
+
${z}
|
|
474
|
+
</context>`;if(d.push(Q),c+=Q+`
|
|
475
|
+
`,this.completeOutputWithToolResults+=Q+`
|
|
476
|
+
`,this.currentOutput+=Q+`
|
|
477
|
+
`,!A){let te=P.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(te){let Te=P.replace(te[0],"").trim();if(Te.length>0){c+=Te,u+=Te,this.currentOutput+=Te,this.completeOutputWithToolResults+=Te;let me=Pe.remove(Te);this.emit("data",me)}}}continue}}catch{}if(P.includes("<think>")){f=!0;let v=P.split("<think>")[0];if(v){c+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let A=Pe.remove(v);this.emit("data",A)}}else if(P.includes("</think>")){f=!1,y+=P.split("</think>")[0],this.emit("thinking",y),y="";let v=P.split("</think>")[1]||"";if(v){c+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let A=Pe.remove(v);this.emit("data",A)}}else if(f)y+=P,this.emit("thinking",y);else{c+=P,u+=P,this.currentOutput+=P,this.completeOutputWithToolResults+=P;let v=Pe.remove(P);this.emit("data",v)}}else if(D.type==="checkpoint_reached"||D.event==="checkpoint_reached")r.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(D.type==="todo_update")this.handleTodoUpdate(D.data);else if(D.type==="webview_update")this.handleWebViewUpdate(D.data);else if(D.type==="operator_progress")this.handleOperatorProgress(D.data);else if(D.type==="stop"){this.handleStop(D.data),n(c);return}}catch{r.debug("Treating as plain text"),c+=_,u+=_,this.currentOutput+=_,this.completeOutputWithToolResults+=_;let P=Pe.remove(_);this.emit("data",P)}}}}}),b.on("end",()=>{this.inflightRequests.delete(t),this.activeToolNames.clear(),this.emit("done"),n(c)}),b.on("error",S=>{switch(r.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),it.classify(S)){case"parsing":let I={type:"tool_result",tool_call_id:`error_${Ne()}`,error:!0,content:`Streaming parsing error occurred: ${S.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(I)),J.getInstance().handleConversationComplete(),n(c);return;case"critical":J.getInstance().handleConversationComplete(),this.emit("error",S),o(S);break}})}).catch(g=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),g.code==="ERR_CANCELED")r.debug("Task was cancelled, disconnecting WebSocket"),J.getInstance().handleConversationComplete(),this.emit("canceled"),n(c);else switch(it.classify(g)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${Ne()}`,error:!0,content:`Request parsing error: ${g.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(C)),J.getInstance().handleConversationComplete(),n(c);break;case"critical":r.debug("Request failed, disconnecting WebSocket"),J.getInstance().handleConversationComplete(),o(g);break}})})}async performNonStreamingToolCall(e,t){try{let s=await this.getFirebaseIdToken();s||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let n=await gs.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),n.data?.content){if(this.currentOutput=n.data.content,this.completeOutputWithToolResults=n.data.completeOutput||n.data.content,n.data.toolResults)for(let o of n.data.toolResults)this.handleToolResult(o.tool,o.result);return n.data.content}throw new Error("No response content received")}catch(s){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),it.classify(s)){case"parsing":let o={type:"tool_result",tool_call_id:`error_${Ne()}`,error:!0,content:`Non-streaming API parsing error: ${s.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(o)),"";case"critical":throw this.emit("error",s),new Error(`Tool calling API Error: ${s.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",s=null;if(e.function?.arguments)try{s=JSON.parse(e.function.arguments)}catch{r.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:s,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,s)}async executeToolViaWebSocket(e,t,s){try{let n=J.getInstance(),o={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await n.sendToolRequest(o)}catch(n){r.debug(`Failed to execute tool via WebSocket: ${n.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:s,success:n,error:o}=e;if(r.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",n),n&&s){let a=`<context>
|
|
478
|
+
${s.map(c=>c.text||"").join("")}
|
|
393
479
|
</context>`;this.completeOutputWithToolResults+=a+`
|
|
394
480
|
`,this.currentOutput+=a+`
|
|
395
481
|
`,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>
|
|
396
482
|
Error: ${o}
|
|
397
483
|
</context>`;this.completeOutputWithToolResults+=i+`
|
|
398
|
-
`}}captureFrontendToolResult(e,t,n
|
|
484
|
+
`}}captureFrontendToolResult(e,t,s,n){let o=`<context>
|
|
399
485
|
Tool: ${e}
|
|
400
|
-
Success: ${
|
|
486
|
+
Success: ${s}
|
|
401
487
|
Output:
|
|
402
488
|
${t}
|
|
403
489
|
</context>`;this.completeOutputWithToolResults+=o+`
|
|
404
490
|
`,this.currentOutput+=o+`
|
|
405
|
-
`,r.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${
|
|
491
|
+
`,r.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),r.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:n,wrappedContent:o})}handleCheckpointReached(){let e=he.getInstance(),t=e.getQueuedMessages();if(t.length===0){r.debug("[CHECKPOINT] No queued messages to convert");return}let s=t.filter(o=>!o.isCrossDeviceTask),n=t.filter(o=>o.isCrossDeviceTask);if(r.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),r.debug(` - ${s.length} user messages -> convert to feedback`),r.debug(` - ${n.length} cross-device tasks -> keep in queue`),s.length>0){let o=s.map(i=>({id:i.id,content:i.content,timestamp:i.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",o),r.info(`[CHECKPOINT] Converted ${s.length} user messages to feedback`),s.forEach(i=>{e.removeFromQueueById(i.id)})}n.length>0&&r.debug(`[CHECKPOINT] Kept ${n.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||Ne(),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||Ne(),taskId:e.taskId||e.id||Ne(),sessionId:e.sessionId||Ne(),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..."),J.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,s)=>typeof s.content=="string"?t+Math.ceil(s.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let s=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",n=K.find(i=>i.name===s)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},o=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,o,n,.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(),J.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
|
|
406
492
|
|
|
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)
|
|
409
|
-
`);if(i!==-1)
|
|
410
|
-
`?this.buffer=this.buffer.substring(
|
|
493
|
+
[STOPPED] - Task was stopped by user`:s="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(n){r.debug("[PERSONAL AGENT] Firebase update failed for STOP:",n)}await this.completeConversation(s,"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",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.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 n=ae.getInstance().getCurrentDeviceId();n?(s.device_id=n,r.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):r.debug("[PERSONAL AGENT] No device_id available for stop request"),r.debug("[PERSONAL AGENT] Sending backend stop request");let o=await this.getFirebaseIdToken();o||r.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let i=await gs.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o||this.getAuthToken()}`}});i.status===200&&(r.debug("[PERSONAL AGENT] Backend stop successful:",i.data),i.data.stopped_sessions&&r.debug("[PERSONAL AGENT] Stopped sessions:",i.data.stopped_sessions),i.data.stopped_tools&&r.debug("[PERSONAL AGENT] Stopped tools:",i.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}`),J.getInstance().handleConversationComplete();let n={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",n),this.resetState(),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(),this.activeToolNames.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 En={};ge(En,{FirebaseNativeService:()=>at,TaskMode:()=>vs,TaskStatus:()=>bs});import{getDatabase as mr,ref as fs,onChildAdded as gr,update as hr,set as fr,serverTimestamp as vr}from"firebase/database";import{EventEmitter as br}from"events";var vs,bs,at,Ts=O(()=>{"use strict";U();pt();vs=(t=>(t.NEW="new",t.EXISTING="existing",t))(vs||{}),bs=(n=>(n.PENDING="pending",n.PROCESSING="processing",n.COMPLETED="completed",n.QUEUE_FULL="queue_full",n))(bs||{}),at=class l extends br{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=mr(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 l.instance||(l.instance=new l),l.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 s=`users/${e}/devices/${t}/tasks`;r.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let n=fs(this.database,s),o=this.auth?.currentUser;r.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=gr(n,i=>{let a=i.key,c=i.val();if(r.debug("[Firebase Native] Child added event received",{taskId:a,status:c?.status,exists:i.exists()}),!a||!c){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(c.status!=="pending"){r.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:c.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(h=>this.processedTaskIds.delete(h))}r.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,c)},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:s,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(s){r.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){r.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),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(()=>(Se(),He))).PersonalAgentService.getInstance()){r.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}r.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="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:s==="new"?"new":"existing"}),r.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(n){r.error("[FIREBASE-NATIVE] Task execution failed:",n.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Se(),He)),s=t.getInstance();await this.cleanupObservers(),this.completedObserver=n=>{this.currentTaskId===e&&(r.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=n=>{if(this.currentTaskId!==e)return;let o=n?.message||n||"Unknown error occurred";r.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=n=>{if(this.currentTaskId!==e)return;let o=n?.reason;r.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),r.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(Se(),He)),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,s){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 n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};s&&(o.result=s),r.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:n,status:t,hasResult:!!s});try{r.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(n,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:n,error:i.message}),r.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=fs(this.database,n),c={status:t,updatedAt:vr()};s&&(c.result=s),await hr(a,c),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,s,n){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:n});try{let i=fs(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:n,timestamp:Date.now(),status:"pending"};return await fr(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 Tr}from"events";var Ke,ys=O(()=>{"use strict";Ae();ie();pt();Ts();Se();U();Ke=class l extends Tr{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=ae.getInstance(),this.authService=G.getInstance(),this.firebaseAPI=xe.getInstance(),this.firebaseNative=at.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return l.instance||(l.instance=new l),l.instance}setupTaskCompletionListener(){let e=ne.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(ne.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 s=this.pendingTasksQueue.shift();r.debug(`📤 [CrossDevice] Processing next task from queue: ${s.taskId}`),this.executeTaskImmediately(s.taskId,s.prompt,s.mode)}async startListening(e,t){let s=t||this.deviceRegistrationService.getCurrentDeviceId();if(!s){r.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,r.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let n=this.authService.getFirebaseAuth();if(!n?.currentUser){r.error("No authenticated Firebase user - cannot start listeners");return}if(n.currentUser.uid!==e){r.error("SECURITY: User ID mismatch! Firebase UID:",n.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,s)}catch(n){throw r.error("Failed to start listener:",n.message),n}}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 s=await this.authService.getCustomTokenFromAPI(e);if(t){let n=await this.authService.signInWithCustomToken(s);r.debug("Firebase authenticated successfully - UID:",n.user.uid)}}catch(s){r.warn("Firebase authentication failed:",s.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(s){r.error("Failed to process task:",s.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 s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let n=s[1],o=s[2];return n.length!==13||!Number.isInteger(Number(n))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,n=t.prompt,o=t.status;if(!s||!n){r.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){r.debug("⏭️ [CrossDevice] Skipping non-pending task:",s,"Status:",o);return}this.incomingTaskQueue.push({taskId:s,prompt:n,snapshot:e}),r.debug(`📨 [CrossDevice] Task queued for processing: ${s}`),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:s}=this.incomingTaskQueue.shift();r.debug(`🔵 [CrossDevice] Processing task: ${e}`),r.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let n=s.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(ne.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=(_e(),Qn(Os)).MessageQueueManager.getInstance(),o=n.getQueueCount(),i=n.canAddToQueue();if(r.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${i}`),!i)return!1}return!0}async executeTask(e,t,s){if(r.debug(`Executing task: ${e} with mode: ${s}`),r.debug(`Prompt to execute: ${t}`),ne.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){r.debug(`System is busy - queueing cross-device task: ${e}`);let i={taskId:e,prompt:t,mode:s};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,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{r.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(n){r.error("Task execution failed:",n.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,n={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,n)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},s=o=>{this.currentTaskId===e&&this.cleanupObservers()},n=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",n)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,s="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let n=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:Ie,status:"pending"},i=`users/${this.currentUserId}/devices/${e}/tasks/${n}`;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(([s,n])=>({id:s,...n})).filter(s=>s.isOnline&&s.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 Fn={};ge(Fn,{SnowXStreamHandlerService:()=>Cs});import{EventEmitter as Lr}from"events";var Cs,$n=O(()=>{"use strict";Cs=class extends Lr{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,s,n,o){let i=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,c)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let d=this.byteBuffer.toString("utf8");this.buffer+=d,this.rawDataReceived+=d,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,n,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,n,o),this.printFinalStatistics(),!this.fullResponse&&!o){c(new Error("No response received"));return}a()}),e.on("error",u=>{c(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let n,o=this.buffer.indexOf(`\r
|
|
494
|
+
`);if(o!==-1)n=o;else{let i=this.buffer.indexOf(`
|
|
495
|
+
`);if(i!==-1)n=i;else{let a=this.buffer.indexOf("\r");if(a!==-1)n=a;else return}}for(;n!==-1;){if(this.isCancelled)return;let i=this.buffer.substring(0,n);this.linesProcessed++,this.buffer.substring(n,n+2)===`\r
|
|
496
|
+
`?this.buffer=this.buffer.substring(n+2):this.buffer=this.buffer.substring(n+1);let a=i.trim();if(!a){n=this.findNextLineEnd();continue}if(a.startsWith(":")){n=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),n=this.findNextLineEnd()}}processDataLine(e,t,s,n){if(this.isCancelled)return;this.dataLinesFound++;let o=e.substring(6).trim();if(o==="[DONE]"){this.emit("streamEnd");return}if(o)try{let 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 c of a.delta.tool_calls)n?.(c);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,s))}}catch{}}processThinkingContent(e,t,s){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let n=this.thinkingBuffer.indexOf("</think>");if(n!==-1){let o=this.thinkingBuffer.substring(0,n);o&&(this.thinkingContent+=o,s?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(n+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",s?.(this.thinkingContent));break}else{let n=this.thinkingBuffer.indexOf("<think>");if(n!==-1){let o=this.thinkingBuffer.substring(0,n);o&&(this.regularContent+=o,this.fullResponse+=o,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(n+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,s){if(this.rawDataReceived.startsWith("data: ")){let n=this.rawDataReceived.substring(6).trim();try{let o=JSON.parse(n);o.choices&&o.choices.length>0&&o.choices[0].delta.content&&this.processThinkingContent(o.choices[0].delta.content,e,t)}catch{}}else try{let n=JSON.parse(this.rawDataReceived);n.choices?.[0]?.message?.content&&this.processThinkingContent(n.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
|
|
411
497
|
`);if(e!==-1)return e;let t=this.buffer.indexOf(`
|
|
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
|
-
▸ ${
|
|
414
|
-
❌ Error:`,
|
|
415
|
-
|
|
416
|
-
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let
|
|
417
|
-
`).
|
|
498
|
+
`);if(t!==-1)return t;let s=this.buffer.indexOf("\r");return s!==-1?s:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import Ur from"axios";import{EventEmitter as Wr}from"events";import Br from"http";import qr from"https";var Ht,_n=O(()=>{"use strict";ie();Ht=class extends Wr{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Br.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new qr.Agent({keepAlive:!0,timeout:36e5}),this.client=Ur.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=G.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let s=0;s<t;s++)try{return await e()}catch(n){if(n.response?.status===429){if(s===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,s);await new Promise(i=>setTimeout(i,o*1e3))}else throw n}throw new Error("Max retries exceeded")}buildRequest(e,t,s,n=.7,o=.9,i,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:n,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:i,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,n=.9,o,i){let a=this.buildRequest(e,t,!1,s,n,o,i);try{let u=(await this.executeWithRetry(async()=>{let{data:d}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return d})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(c){throw this.emit("error",c),new Error(`API Error: ${c.message}`)}}async performStreamingRequest(e,t,s=.7,n=.9,o,i,a,c,u){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>($n(),Fn)),h=this.buildRequest(e,t,!0,s,n,o,i);return new Promise((f,y)=>{this.currentAbortController=new AbortController;let T=[],k=new Map,p=new d;this.client.post("/chat/completions",h,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async g=>{let b=g.data,C=g.headers["content-type"]||"",S=x=>{if(x?.index!==void 0){let I=x.index;k.has(I)||k.set(I,{});let w=k.get(I);x.id&&(w.id=x.id,w.type="function"),x.function&&(w.function||(w.function={name:"",arguments:""}),x.function.name&&(w.function.name=x.function.name),x.function.arguments&&(w.function.arguments+=x.function.arguments))}u?.(x),this.emit("tool_call_delta",x)};p.on("streamEnd",()=>{k.forEach((x,I)=>{x.id&&x.function?.name&&T.push(x)}),this.emit("done"),f({content:p.getFinalResponse(),toolCalls:T.length>0?T:void 0})}),p.on("cancelled",()=>{this.emit("canceled"),f({content:p.getFinalResponse(),toolCalls:T.length>0?T:void 0})});try{await p.processStreamingResponse(b,C,a||(()=>{}),c,S),k.forEach((x,I)=>{x.id&&x.function?.name&&T.push(x)}),this.emit("done"),f({content:p.getFinalResponse(),toolCalls:T.length>0?T:void 0})}catch(x){this.emit("error",x),y(x)}}).catch(g=>{g.code==="ERR_CANCELED"?(this.emit("canceled"),f({content:"",toolCalls:T.length>0?T:void 0})):y(g)})})}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 Hr}from"socket.io-client";import{EventEmitter as Gr}from"events";var Gt,Mn=O(()=>{"use strict";Ae();Gt=class l extends Gr{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=ae.getInstance()}static getInstance(){return l.instance||(l.instance=new l),l.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let s={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=Hr(t,s),this.setupEventHandlers(),new Promise((n,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"),n(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(i),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(s){return console.error("❌ Failed to connect WebSocket:",s),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let s={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,s)}sendCrossDeviceMessage(e,t,s){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:s,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,s){this.send("conversation_sync",{conversationId:e,action:t,data:s,timestamp:Date.now()})}syncToolExecution(e,t,s){this.send("tool_execution",{toolName:e,status:t,result:s,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var Ln,Un=O(()=>{"use strict";Ln={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 Bn={};ge(Bn,{ServiceManager:()=>lt});import{EventEmitter as zr}from"events";import{initializeApp as Xr,getApps as Wn}from"firebase/app";import{getAuth as jr}from"firebase/auth";var lt,ks=O(()=>{"use strict";Se();_n();ie();Ae();Mn();Ge();ys();kt();$e();U();Un();lt=class l extends zr{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=ne.getInstance(),this.networkClient=new Ht,this.authService=G.getInstance(),this.deviceRegistration=ae.getInstance(),this.webSocketService=Gt.getInstance(),this.frontendWebSocketService=J.getInstance(),this.crossDeviceService=Ke.getInstance(),this.toolCalling=ot.getInstance()}static getInstance(){return l.instance||(l.instance=new l),l.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||Ln;if(Wn().length===0?(this.firebaseApp=Xr(e),r.debug("Firebase app initialized")):(this.firebaseApp=Wn()[0],r.debug("Using existing Firebase app")),this.firebaseAuth=jr(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(()=>(Ts(),En));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=K[0],s={}){let{usePersonalAgent:n=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:i=.7,stream:a=!0}=s;try{let c=[];if(n)return await this.personalAgent.sendMessageWithToolCalling(e,c,t,i,a,this.authService.getUserId()||void 0);{let u=o?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,h)=>{let f="";this.networkClient.on("data",y=>{f+=y}),this.networkClient.on("done",()=>{d(f)}),this.networkClient.on("error",h),this.networkClient.performStreamingRequest([...c,{role:"user",content:e}],t,i,.9,u)}):(await this.networkClient.performNonStreamingRequest([...c,{role:"user",content:e}],t,i,.9,u)).content}}catch(c){throw c}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:s}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return K.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((s,n)=>{let o=setTimeout(()=>{n(new Error(`Device registration timeout after ${e}ms`))},e),i=c=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",i),s()};this.deviceRegistration.on("DeviceRegistrationComplete",i),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",i),s())})}}});import*as Is from"@sentry/node";Is.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as ei}from"commander";import Vr from"react";import{render as Qr}from"ink";ie();import m,{useState as Nn,useEffect as Ve,useCallback as Ss,useRef as Ir}from"react";import{Box as R,Text as E,useInput as Ar,useApp as Dr}from"ink";import Pr from"ink-spinner";import Rn from"ink-select-input";Se();ms();import pe from"chalk";import dr from"ora";var oe=class{static spinner=null;static formatUserMessage(e){return pe.cyan("You: ")+e}static formatAssistantMessage(e){return pe.green("Assistant: ")+e}static formatError(e){return pe.red("Error: ")+e}static formatWarning(e){return pe.yellow("Warning: ")+e}static formatInfo(e){return pe.blue("Info: ")+e}static formatSuccess(e){return pe.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=dr(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(pe.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(pe.bold.cyan(e)),console.log(pe.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return pe.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return pe.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(pe.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};U();_e();Le();import{EventEmitter as pr}from"events";import hs from"chalk";var Bt=class extends pr{delegate=null;personalAgentService=ne.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",s=console.log;this.delegate?.usesCustomUI||(console.log=(...n)=>{let o=String(n[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),s.apply(console,n)}),this.personalAgentService.on("data",n=>{if(t+=n,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=n:o.content+=n),i&&i.isStreaming&&(!i.content||i.content===""?i.content=n:i.content+=n)}}),this.personalAgentService.on("thinking",n=>{}),this.personalAgentService.on("toolExecuting",n=>{this.delegate?.usesCustomUI||console.log(`
|
|
499
|
+
▸ ${n}`)}),this.personalAgentService.on("tool_completed",n=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:i,error:a}=n;console.log(i!==!1?`✓ ${o}`:`✗ ${o} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",n=>{}),this.personalAgentService.on("todo_update",n=>{}),this.personalAgentService.on("operator_progress",n=>{}),this.personalAgentService.on("webview_update",n=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(n.isStreaming=!1),o&&o.isStreaming&&(o.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",n=>{console.error(`
|
|
500
|
+
❌ Error:`,n.message||n),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",n=>{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&&(n.content&&n.content.trim()?(r.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${n.content.substring(0,50)}..."`),o.content=n.content,o.originalContent=n.content):r.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),n.completeWithTools&&(o.metadata={toolResults:n.completeWithTools}),o.isStreaming=!1,r.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),i&&i.isStreaming&&(n.content&&n.content.trim()?(r.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${n.content.substring(0,50)}..."`),i.content=n.content,i.originalContent=n.content):r.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),n.completeWithTools&&(i.metadata={toolResults:n.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 s=new de,n=e.trim(),o=s.count(n);if(o>Me){console.log(oe.formatError(`Prompt too large (${o.toLocaleString()} tokens). Please reduce it to ${Me.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let a=he.getInstance();a.addToQueue({content:n,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(hs.blue(`⚡ Message queued (${a.getQueueCount()} in queue)`)),console.log(hs.dim(" Your feedback will be sent when AI completes current task"))):console.log(hs.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let i=null;this.delegate.isVisionEnabled&&(i=await Xe.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(oe.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})),s=this.delegate.fullConversationHistory.filter(o=>o.role==="user"),n=s[s.length-1];if(n)try{let o=e?[e]:void 0,i={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(n.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(n=>n.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let o=t.content;o.trim().length>0&&(o+=`
|
|
501
|
+
|
|
502
|
+
`),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let n=this.delegate.fullConversationHistory.find(o=>o.isStreaming);n&&(n.content=t.content,n.isStreaming=!1)}this.delegate.isLoading=!1,ne.getInstance().stopStreaming().catch(n=>{r.error("[MESSAGE HANDLER] Error in comprehensive stop:",n)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Se();Qt();_e();Ge();ys();$e();ue();fe();import ws from"terminal-link";import{homedir as yr}from"os";function xn(l){let e=l.trim();return e.startsWith("~")&&(e=e.replace("~",yr())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function wr(l){return l.startsWith("http://")||l.startsWith("https://")||l.startsWith("mailto:")}function qt(l){let e=l;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,n)=>{let o=n;return!wr(n)&&!n.startsWith("file://")&&(n.startsWith("/")||n.startsWith("~")||/\.[a-z]{2,4}$/i.test(n))&&(o=xn(n)),ws(s,o,{fallback:(i,a)=>`${i} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return s.test(n)?t:ws(t,t,{fallback:(o,i)=>i})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(s.test(n)||n.includes("http"))return t;let o=xn(t);return ws(t,o,{fallback:(i,a)=>i})}),e}import re from"react";import{Box as ct,Text as Fe}from"ink";import Sr from"ink-spinner";function Cr(l,e){let t=l.toLowerCase(),s=e?.description;if(t==="bash"||t==="command"||t==="run_command"){let n=e?.command;return s&&s.length<60?{title:s,details:n?`$ ${n.substring(0,80)}${n.length>80?"...":""}`:void 0}:{title:"Running command",details:n?`$ ${n.substring(0,80)}${n.length>80?"...":""}`:void 0}}if(t==="read"||t==="readfile"){let n=e?.file_path,o=e?.offset,i=e?.limit,a=n||void 0;if(n&&(o!==void 0||i!==void 0)){let c=o||0,u=i?c+i:"end";a=`${n} (lines ${c}-${u})`}return{title:"Reading file",details:a}}if(t==="write"||t==="writefile"){let n=e?.file_path,o=e?.content,i=n;if(o&&n){let a=o.split(`
|
|
503
|
+
`).length;i=`${n} (${a} lines)`}return{title:"Writing file",details:i}}if(t==="edit"||t==="editfile"){let n=e?.file_path,o=e?.old_string,i=e?.new_string,a=n;if(n&&o&&i&&o.length<50&&i.length<50){let c=o.replace(/\n/g,"\\n").substring(0,45),u=i.replace(/\n/g,"\\n").substring(0,45);a=`${n}
|
|
504
|
+
"${c}" → "${u}"`}return{title:"Editing file",details:a}}if(t==="grep"){let n=e?.pattern,o=e?.path,i=e?.glob,a=e?.type,c=n?`Pattern: ${n}`:"Searching...";return o&&(c+=`
|
|
505
|
+
In: ${o}`),i&&(c+=` (${i})`),a&&(c+=` [${a} files]`),{title:"Searching content",details:c}}if(t==="glob"){let n=e?.pattern,o=e?.path,i=n?`Pattern: ${n}`:"Finding files...";return o&&o!=="."&&(i+=`
|
|
506
|
+
In: ${o}`),{title:"Finding files",details:i}}if(t==="webfetch"||t==="web_fetch")return{title:"Fetching URL",details:e?.url};if(t==="task"){let n=e?.description,o=e?.prompt,i=n||o;return{title:"Running agent",details:i?i.length>60?i.substring(0,57)+"...":i:void 0}}if(t==="websearch"||t==="web_search"){let n=e?.query;return{title:"Searching web",details:n?`"${n}"`:void 0}}return t==="todowrite"?{title:"Updating tasks",details:void 0}:s&&s.length<60?{title:s}:{title:l}}function In({tool:l}){let{title:e,details:t}=Cr(l.name,l.arguments);return re.createElement(ct,{flexDirection:"column"},re.createElement(ct,null,l.state==="running"?re.createElement(Fe,{color:"cyan"},re.createElement(Sr,{type:"dots"})):l.state==="completed"?re.createElement(Fe,{color:"#5AD8A6"},"✓"):re.createElement(Fe,{color:"#F5716C"},"✗"),re.createElement(Fe,null," "),re.createElement(Fe,{color:"whiteBright"},e)),t&&re.createElement(ct,{flexDirection:"column",marginLeft:2},t.split(`
|
|
507
|
+
`).map((s,n)=>re.createElement(ct,{key:n},re.createElement(Fe,{color:"#6B7280"},s)))))}function An({activeTools:l}){if(l.size===0)return null;let e=Array.from(l.entries()).filter(([o,i])=>i.name.toLowerCase()!=="todowrite");if(e.length===0)return null;let t=e.filter(([o,i])=>i.state==="running"),s=e.filter(([o,i])=>i.state==="completed"),n=s.slice(-2);return re.createElement(ct,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1},t.map(([o,i])=>re.createElement(In,{key:o,tool:i})),n.map(([o,i])=>re.createElement(In,{key:o,tool:i})),s.length>2&&re.createElement(Fe,{color:"#6B7280"}," +",s.length-2," more"))}import H from"react";import{Box as ke,Text as Z}from"ink";import Dn from"ink-spinner";function kr(l,e=60){return l?l.length<=e?l:l.substring(0,e-3)+"...":"Processing..."}function Er({agent:l}){let e=kr(l.task||"Working..."),s=(n=>{switch(n){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}})(l.status);return H.createElement(ke,{flexDirection:"column",marginLeft:2},H.createElement(ke,null,l.status==="running"?H.createElement(Z,{color:"cyan"},H.createElement(Dn,{type:"dots"})):l.status==="completed"?H.createElement(Z,{color:"#5AD8A6"},"✓"):l.status==="failed"?H.createElement(Z,{color:"#F5716C"},"✗"):l.status==="timeout"?H.createElement(Z,{color:"#FBBF24"},"⏱"):H.createElement(Z,{color:"#6B7280"},"○"),H.createElement(Z,{color:s,bold:!0}," Agent #",l.agentNumber)),H.createElement(ke,{marginLeft:2},H.createElement(Z,{color:"#9CA3AF"},e)),l.error&&H.createElement(ke,{marginLeft:2},H.createElement(Z,{color:"#F5716C"},"Error: ",l.error.substring(0,60),l.error.length>60?"...":"")),l.streamingContent&&l.status==="running"&&H.createElement(ke,{marginLeft:2},H.createElement(Z,{color:"#6B7280"},l.streamingContent.split(`
|
|
508
|
+
`)[0]?.substring(0,50),"...")))}function xr({operation:l}){let e=Array.from(l.agents.values()).sort((c,u)=>c.agentNumber-u.agentNumber),t=e.filter(c=>c.status==="completed").length,s=e.filter(c=>c.status==="failed").length,n=e.filter(c=>c.status==="running").length,o=l.totalAgents,i=()=>l.status==="starting"||l.status==="running"?`Spawning ${o} agents`:l.status==="completed"?`${o} agents completed`:"Operation failed",a=l.status==="completed"?"#5AD8A6":l.status==="failed"?"#F5716C":"cyan";return H.createElement(ke,{flexDirection:"column"},H.createElement(ke,null,l.status==="running"||l.status==="starting"?H.createElement(Z,{color:"cyan"},H.createElement(Dn,{type:"dots"})):l.status==="completed"?H.createElement(Z,{color:"#5AD8A6"},"✓"):H.createElement(Z,{color:"#F5716C"},"✗"),H.createElement(Z,{color:a,bold:!0}," ",i()),H.createElement(Z,{color:"#6B7280"}," "),H.createElement(Z,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",t,"/",o," "),n>0&&H.createElement(Z,{color:"cyan"}," (",n," running)"),s>0&&H.createElement(Z,{color:"#F5716C"}," [",s," failed]")),H.createElement(ke,{flexDirection:"column",marginTop:1},e.map(c=>H.createElement(Er,{key:c.agentNumber,agent:c}))))}function Pn({operations:l}){if(l.size===0)return null;let e=Array.from(l.entries()).filter(([t,s])=>s.status==="running"||s.status==="starting"?!0:s.endTime?Date.now()-s.endTime.getTime()<1e4:!0);return e.length===0?null:H.createElement(ke,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,s])=>H.createElement(xr,{key:t,operation:s})))}Zt();var Nr=0;function V(){return`msg-${Date.now()}-${++Nr}`}function Rr(l){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],s;for(;(s=e.exec(l))!==null;){let i=s[1].split(`
|
|
509
|
+
`).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 n=l.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return n=n.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:n}}function Or(l){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],s=new Set,n;for(;(n=e.exec(l))!==null;){let i=n[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,c;for(;(c=a.exec(i))!==null;){let u=c[1],d=c[2];s.has(d)||(s.add(d),t.push({name:u,path:d}))}}let o=l.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return o=o.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:o}}function On(){let{exit:l}=Dr(),e=G.getInstance(),t=ne.getInstance(),s=he.getInstance(),n=J.getInstance(),o=Ke.getInstance(),i=et.getInstance();Ve(()=>($.enableCustomUI(),()=>$.disableCustomUI()),[]);let[a,c]=Nn({messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
418
510
|
|
|
419
511
|
Your autonomous on-device AI agent.
|
|
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:
|
|
512
|
+
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:K.find(p=>p.name===Ee.string("selectedPersonalModel"))||K.find(p=>p.name==="snowx-c5")||K[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1,activeTools:new Map,subAgentOperations:new Map}),u=Ir(null),[d]=Nn(()=>{let p={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:K.find(g=>g.name===Ee.string("selectedPersonalModel"))||K.find(g=>g.name==="snowx-c5")||K[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Bt(p)}),h=Ss(async()=>{},[]);Ve(()=>{let p=a.messages.map(b=>({role:b.role,content:b.content,timestamp:new Date(b.timestamp||Date.now()),...b.tool&&{tool:b.tool},...b.toolOutput&&{toolOutput:b.toolOutput}})),g={messages:p,fullConversationHistory:p,isLoading:a.isLoading,currentInput:a.input,selectedModel:a.selectedModel,isVisionEnabled:a.isVisionEnabled,conversationId:a.conversationId,usesCustomUI:!0,updateCurrentConversation:h};d.setDelegate(g)},[a.messages,a.selectedModel,a.isVisionEnabled,a.isLoading,a.input,a.conversationId,d,h]);let f=Ss(async p=>{if(p.startsWith("/")){let I=p.toLowerCase().trim();if(I==="/help"||I==="/?"){c(w=>({...w,showCommandMenu:!0,input:""}));return}if(I==="/model"){c(w=>({...w,showModelMenu:!0,input:""}));return}if(I==="/clear"||I==="/new"){c(w=>({...w,messages:[{id:V(),role:"system",content:`Welcome to Orion
|
|
421
513
|
|
|
422
514
|
Your intelligent AI assistant.
|
|
423
|
-
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(
|
|
424
|
-
|
|
425
|
-
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(
|
|
426
|
-
|
|
427
|
-
${
|
|
428
|
-
</context>`;
|
|
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
|
|
432
|
-
`)
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
❌ Authentication
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
❌ Failed to initialize services:`,n.message),console.error(`
|
|
515
|
+
Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(I==="/vision"){c(w=>({...w,isVisionEnabled:!w.isVisionEnabled,messages:[...w.messages,{id:V(),role:"system",content:`Vision mode ${w.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(I==="/exit"||I==="/quit"){l();return}if(I==="/stop"){a.isLoading?(t.stopStreaming(),c(w=>({...w,isLoading:!1,messages:[...w.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):c(w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(I==="/signout"){c(w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:"🔄 Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(c(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:"✅ Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>l(),1e3)):c(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:"⚠️ Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(w){c(M=>({...M,messages:[...M.messages,{id:V(),role:"system",content:`❌ Error: ${w.message}`,timestamp:Date.now()}]}))}return}c(w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:`Unknown command: ${p}
|
|
516
|
+
|
|
517
|
+
Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(a.isLoading){let I=s.addToQueue({content:p,imageUrls:[],attachments:[],model:a.selectedModel.name});c(I?w=>({...w,input:""}):w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:"⚠️ Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let g=Date.now(),b={id:V(),role:"user",content:p,timestamp:g},C={id:V(),role:"assistant",content:"",timestamp:g+1},S=[...a.messages,b,C];c(I=>({...I,messages:S,input:"",isLoading:!0,loadingMessage:"Processing"}));let x=S.map(I=>({role:I.role,content:I.content,timestamp:new Date(I.timestamp||Date.now()),...I.tool&&{tool:I.tool},...I.toolOutput&&{toolOutput:I.toolOutput}}));d.setDelegate({messages:x,fullConversationHistory:x,isLoading:!1,currentInput:"",selectedModel:a.selectedModel,isVisionEnabled:a.isVisionEnabled,conversationId:a.conversationId,usesCustomUI:!0,updateCurrentConversation:h});try{await d.sendMessage(p)}catch(I){c(w=>({...w,messages:[...w.messages,{id:V(),role:"system",content:`Error: ${I.message}`,timestamp:Date.now()}],isLoading:!1}))}},[a.isLoading,a.isVisionEnabled,a.selectedModel,s,d,e,l]),y=Ss(()=>{if(!s.hasQueuedMessages())return;let p=s.processNextMessage();p&&(s.startProcessing(),f(p.content))},[s,f]);Ve(()=>{let p="",g=!1,b=!1,C=100,S=v=>{c(A=>({...A,conversationId:v.conversationId,conversationTitleGenerated:!!v.title}))},x=v=>{},I=()=>{c(v=>({...v,loadingMessage:"Processing"}))},w=()=>{if(b=!1,!g)return;g=!1;let v=p;c(A=>{let N=A.messages.map((F,L)=>F.role==="assistant"&&!A.messages.slice(L+1).some(Q=>Q.role==="assistant")?{...F,content:v}:F);return{...A,messages:N}})},M=v=>{p+=v,g=!0,b||(b=!0,setTimeout(w,C))},j=v=>{let A=typeof v=="string"?v:v.name,N=typeof v=="string"?`tool-${Date.now()}`:v.toolCallId,F=typeof v=="string"?void 0:v.arguments;c(L=>{let z=new Map(L.activeTools);return z.set(N,{toolCallId:N,name:A,arguments:F,startTime:new Date,state:"running"}),{...L,activeTools:z,loadingMessage:A}})},_=v=>{if(v&&v.toolName){let A=v.toolId||`tool-${v.toolName}-${Date.now()}`,N="";v.result&&(typeof v.result=="string"?N=v.result:Array.isArray(v.result)?N=v.result.map(z=>typeof z=="string"?z:z&&typeof z=="object"?z.text||z.content||JSON.stringify(z):"").join(""):v.result.output?N=typeof v.result.output=="string"?v.result.output:JSON.stringify(v.result.output,null,2):v.result.content?N=v.result.content:N=JSON.stringify(v.result,null,2));let F=N.length>500?N.substring(0,500)+`
|
|
518
|
+
...(truncated)`:N,L=`<context>
|
|
519
|
+
${N}
|
|
520
|
+
</context>`;c(z=>{let Q=new Map(z.activeTools),te=A;if(!Q.has(A)){for(let[me,ut]of Q.entries())if(ut.name===v.toolName&&ut.state==="running"){te=me;break}}if(Q.has(te)){let me=Q.get(te);Q.set(te,{...me,state:"completed",output:F})}else Q.set(te,{toolCallId:te,name:v.toolName,arguments:void 0,startTime:new Date,state:"completed",output:F});let Te=z.messages.map((me,ut)=>{if(me.role==="assistant"&&!z.messages.slice(ut+1).some(dt=>dt.role==="assistant")){let dt=me.metadata?.toolResults;return{...me,metadata:{...me.metadata,toolResults:dt?dt+`
|
|
521
|
+
`+L:L}}}return me});return{...z,messages:Te,activeTools:Q}})}},D=()=>{if(g){g=!1,b=!1;let v=p;c(A=>{let N=A.messages.map((F,L)=>F.role==="assistant"&&!A.messages.slice(L+1).some(Q=>Q.role==="assistant")?{...F,content:v}:F);return{...A,messages:N,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}})}else c(v=>({...v,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}));p=""},P=v=>{c(A=>({...A,messages:[...A.messages,{id:V(),role:"system",content:`Error: ${v.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),p=""};return t.on("conversation_id_received",S),t.on("conversation_title_updated",x),t.on("thinking",I),t.on("data",M),t.on("toolExecuting",j),t.on("tool_completed",_),t.on("done",D),t.on("error",P),()=>{t.off("conversation_id_received",S),t.off("conversation_title_updated",x),t.off("thinking",I),t.off("data",M),t.off("toolExecuting",j),t.off("tool_completed",_),t.off("done",D),t.off("error",P)}},[t,y]),Ve(()=>{let p=S=>{c(x=>({...x,queuedMessages:S}))},g=S=>{},b=S=>{u.current=S,c(x=>({...x,todoList:S}))},C=S=>{if(a.isLoading){s.addToQueue({content:S.prompt,imageUrls:[],attachments:[],model:a.selectedModel.name,isCrossDeviceTask:!0,crossDeviceTaskId:S.taskId})||c(I=>({...I,messages:[...I.messages,{id:V(),role:"system",content:"⚠️ Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}f(S.prompt)};return s.on("queue:updated",p),n.on("feedback:sent",g),t.on("todo_update",b),o.on("CrossDeviceTaskSendMessage",C),()=>{s.off("queue:updated",p),n.off("feedback:sent",g),t.off("todo_update",b),o.off("CrossDeviceTaskSendMessage",C)}},[s,n,t,o,f,a.isLoading,a.selectedModel.name]),Ve(()=>{let p=()=>{let g=i.getOperations();c(b=>({...b,subAgentOperations:new Map(g)}))};return i.on("spawn_started",p),i.on("agent_started",p),i.on("agent_streaming",p),i.on("agent_completed",p),i.on("spawn_completed",p),i.on("progress",p),()=>{i.off("spawn_started",p),i.off("agent_started",p),i.off("agent_streaming",p),i.off("agent_completed",p),i.off("spawn_completed",p),i.off("progress",p)}},[i]),Ve(()=>{!a.isLoading&&s.hasQueuedMessages()&&y()},[a.isLoading,s,y]),Ar((p,g)=>{if(g.escape){if(a.isLoading){t.stopStreaming(),c(b=>({...b,isLoading:!1,messages:[...b.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(a.showModelMenu||a.showCommandMenu){c(b=>({...b,showModelMenu:!1,showCommandMenu:!1,input:b.showCommandMenu&&b.input==="/"?"":b.input}));return}if(a.showHelp){c(b=>({...b,showHelp:!1}));return}}if(!a.showModelMenu){if(g.ctrl&&p==="c"){a.isLoading?(t.stopStreaming(),c(b=>({...b,isLoading:!1,messages:[...b.messages,{id:V(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):l();return}if(p==="?"&&a.input===""){c(b=>({...b,showHelp:!b.showHelp}));return}if(g.return&&!a.showCommandMenu){a.input.trim()&&f(a.input);return}if(g.delete||g.backspace){c(b=>{let C=b.input.slice(0,-1);return b.showCommandMenu&&!C.startsWith("/")?{...b,input:C,showCommandMenu:!1}:{...b,input:C}});return}!g.ctrl&&!g.meta&&p&&c(b=>{let C=b.input+p;return C==="/"&&!b.showCommandMenu?{...b,input:C,showCommandMenu:!0}:{...b,input:C}})}});let T=e.getUserEmail()||"User",k=le.getDisplayName(le.getCurrentUserTier());return m.createElement(R,{flexDirection:"column",width:"100%"},m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,width:"100%"},m.createElement(E,{color:"whiteBright"},a.selectedModel.displayName),m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{color:"#9CA3AF"},T),m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{color:"whiteBright"},k),a.queuedMessages.length>0&&m.createElement(m.Fragment,null,m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{backgroundColor:"#3F3F46",color:"whiteBright",bold:!0}," ",a.queuedMessages.length," "),m.createElement(E,{color:"#9CA3AF"}," queued")),a.queuedMessages.filter(p=>p.isCrossDeviceTask).length>0&&m.createElement(m.Fragment,null,m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{backgroundColor:"#0E7490",color:"whiteBright",bold:!0}," 📱 ",a.queuedMessages.filter(p=>p.isCrossDeviceTask).length," "),m.createElement(E,{color:"#9CA3AF"}," cross-device"))),m.createElement(R,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},a.messages.map(p=>m.createElement(Mr,{key:p.id,message:p,onSuggestionClick:g=>{c(b=>({...b,input:g}))}}))),a.todoList&&a.todoList.todos.length>0&&a.todoList.todos.some(p=>p.status!=="completed")&&m.createElement(R,{paddingX:2,marginBottom:1},m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},m.createElement(R,{marginBottom:1},m.createElement(E,{color:"whiteBright",bold:!0},"Tasks"),m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{color:"#9CA3AF"},a.todoList.todos.filter(p=>p.status==="completed").length,"/",a.todoList.todos.length)),a.todoList.todos.map((p,g)=>{let b=p.status==="completed"?"✓":p.status==="in_progress"?"⋯":"○",C=p.status==="completed"?"#5AD8A6":p.status==="in_progress"?"cyan":"#6B7280";return m.createElement(R,{key:p.id||g},m.createElement(E,{color:C},b),m.createElement(E,{color:"#6B7280"}," "),m.createElement(E,{color:p.status==="completed"?"#6B7280":"whiteBright"},p.status==="in_progress"&&p.activeForm?p.activeForm:p.text))}))),a.activeTools.size>0&&m.createElement(R,{paddingX:2,marginBottom:1},m.createElement(An,{activeTools:a.activeTools})),a.subAgentOperations.size>0&&m.createElement(R,{paddingX:2,marginBottom:1},m.createElement(Pn,{operations:a.subAgentOperations})),a.isLoading&&a.activeTools.size===0&&m.createElement(R,{paddingX:0,marginBottom:1,flexDirection:"column"},m.createElement(R,null,m.createElement(E,{color:"cyan"},m.createElement(Pr,{type:"dots"})),m.createElement(E,{color:"whiteBright"}," ",a.loadingMessage,"… "),m.createElement(E,{color:"#9CA3AF"},"(esc to interrupt)")),m.createElement(R,{marginLeft:2},m.createElement(E,{color:"#FBBF24"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),a.showHelp&&m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},m.createElement(E,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),m.createElement(R,{marginTop:1,flexDirection:"column"},m.createElement(E,{color:"#9CA3AF"},"• ",m.createElement(E,{color:"whiteBright",bold:!0},"Enter")," ",m.createElement(E,{color:"#9CA3AF"},"Submit message")),m.createElement(E,{color:"#9CA3AF"},"• ",m.createElement(E,{color:"whiteBright",bold:!0},"?")," ",m.createElement(E,{color:"#9CA3AF"},"Toggle this help")),m.createElement(E,{color:"#9CA3AF"},"• ",m.createElement(E,{color:"whiteBright",bold:!0},"Esc")," ",m.createElement(E,{color:"#9CA3AF"},"Stop generation / Close menus")),m.createElement(E,{color:"#9CA3AF"},"• ",m.createElement(E,{color:"whiteBright",bold:!0},"Ctrl+C")," ",m.createElement(E,{color:"#9CA3AF"},"Stop generation / Exit"))),m.createElement(R,{marginTop:1},m.createElement(E,{color:"#6B7280"},"Press Esc to close"))),a.showModelMenu&&(()=>{let p=le.getCurrentUserTier(),g=w=>{switch(w){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},b=K.filter(w=>w.name.startsWith("snowx-o4")||w.name.startsWith("snowx-c")||w.name.startsWith("snowx-h")),C=K.filter(w=>w.name.startsWith("snowx-5")||w.name.startsWith("snowx-o3")||w.name.startsWith("snowx-4")),S=K.filter(w=>w.name.startsWith("snowx-g")),x=w=>w.map(M=>{let j=le.isModelAccessible(M.name,p),_=g(M.creditMultiplier);return{label:`${j?"":"🔒 "}${M.displayName} ${_}`,value:M.name,isAccessible:j,creditMultiplier:M.creditMultiplier}}),I=[{label:"── Claude ──",value:"_claude_header",isAccessible:!1,creditMultiplier:1},...x(b),{label:"── GPT ──",value:"_gpt_header",isAccessible:!1,creditMultiplier:1},...x(C),{label:"── Gemini ──",value:"_gemini_header",isAccessible:!1,creditMultiplier:1},...x(S)];return m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},m.createElement(E,{bold:!0,color:"whiteBright"},"Select Model"),m.createElement(R,null,m.createElement(E,{color:"#6B7280"},"Tier: ",le.getDisplayName(p)," • "),m.createElement(E,{color:"#5AD8A6"},"[0.5x]"),m.createElement(E,{color:"#6B7280"}," "),m.createElement(E,{color:"#9CA3AF"},"[1x]"),m.createElement(E,{color:"#6B7280"}," "),m.createElement(E,{color:"#FBBF24"},"[2x]"),m.createElement(E,{color:"#6B7280"}," credits")),m.createElement(R,{marginTop:1},m.createElement(Rn,{items:I.map(w=>({label:w.label,value:w.value})),onSelect:w=>{if(w.value.startsWith("_"))return;if(!I.find(_=>_.value===w.value)?.isAccessible){c(_=>({..._,messages:[..._.messages,{id:V(),role:"system",content:le.getAccessDeniedMessage(w.value),timestamp:Date.now()}]}));return}let j=K.find(_=>_.name===w.value);j&&(Ee.set("selectedPersonalModel",j.name),c(_=>({..._,selectedModel:j,showModelMenu:!1,messages:[..._.messages,{id:V(),role:"system",content:`Switched to ${j.displayName}`,timestamp:Date.now()}]})))}})),m.createElement(R,{marginTop:1},m.createElement(E,{color:"#6B7280"},"Esc to cancel")))})(),a.showCommandMenu&&(()=>{let p=[{label:"/model — Change AI model",value:"model"},{label:"/new — Start new conversation",value:"new"},{label:"/clear — Clear conversation",value:"clear"},{label:"/stop — Stop current generation",value:"stop"},{label:"/vision — Toggle vision mode",value:"vision"},{label:"/signout — Sign out and exit",value:"signout"},{label:"/exit — Exit Orion",value:"exit"},{label:"/help — Show this menu",value:"help"}],g=a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",b=g?p.filter(C=>C.value.toLowerCase().includes(g)):p;return m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},m.createElement(E,{bold:!0,color:"whiteBright"},"Available Commands ",g&&`(filtered: "${g}")`),m.createElement(R,{marginTop:1},m.createElement(Rn,{items:b.length>0?b:[{label:"No matching commands",value:""}],onSelect:C=>{C.value&&(c(S=>({...S,showCommandMenu:!1,input:""})),f(`/${C.value}`))}})),m.createElement(R,{marginTop:1},m.createElement(E,{color:"#6B7280"},"Esc to cancel")))})(),a.queuedMessages.length>0&&m.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},a.queuedMessages.map((p,g)=>m.createElement(R,{key:p.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},m.createElement(R,null,m.createElement(E,{color:"whiteBright",bold:!0},g+1),m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{color:"#9CA3AF"},p.content.length>60?p.content.substring(0,60)+"...":p.content)))),m.createElement(R,null,m.createElement(E,{color:"#9CA3AF"},a.queuedMessages.length," message",a.queuedMessages.length>1?"s":""," queued"))),a.queuedMessages.filter(p=>p.isCrossDeviceTask).length>0&&m.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},a.queuedMessages.filter(p=>p.isCrossDeviceTask).map((p,g)=>m.createElement(R,{key:`cross-${p.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},m.createElement(R,null,m.createElement(E,{color:"#22D3EE",bold:!0},"📱 ",g+1),m.createElement(E,{color:"#6B7280"}," • "),m.createElement(E,{color:"#9CA3AF"},p.content.length>60?p.content.substring(0,60)+"...":p.content)))),m.createElement(R,null,m.createElement(E,{color:"#22D3EE"},a.queuedMessages.filter(p=>p.isCrossDeviceTask).length," cross-device task",a.queuedMessages.filter(p=>p.isCrossDeviceTask).length>1?"s":""," waiting"))),m.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},m.createElement(R,null,m.createElement(E,{color:"cyan"},"▶ "),m.createElement(E,{color:"whiteBright"},a.input,!a.isLoading&&m.createElement(E,{color:"whiteBright",inverse:!0}," "))),m.createElement(R,{marginTop:0},m.createElement(E,{color:"#6B7280"},a.isLoading?"Send feedback or press Enter to queue · esc to stop":"/help · ? · enter to submit"))),m.createElement(R,{paddingX:2,paddingY:0},m.createElement(E,{color:"#6B7280"},"? help · Ctrl+C exit")))}function Fr(l){let e=l;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=qt(e),e}function $r({suggestions:l,onSelect:e}){return l.length===0?null:m.createElement(R,{flexDirection:"column",marginTop:1},l.map((t,s)=>m.createElement(R,{key:`sug-block-${s}-${t.options.join(",").slice(0,20)}`,flexWrap:"wrap",gap:1},t.options.map(n=>m.createElement(R,{key:`sug-opt-${n.slice(0,30)}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},m.createElement(E,{color:"#22D3EE"},n))))),e&&m.createElement(R,{marginTop:0},m.createElement(E,{color:"#6B7280"},"Type a suggestion to use it")))}function _r({workingFiles:l}){return l.length===0?null:m.createElement(R,{flexDirection:"column",marginTop:1},m.createElement(R,{marginBottom:0},m.createElement(E,{color:"#9CA3AF",bold:!0},"Working Files"),m.createElement(E,{color:"#6B7280"}," (",l.length,")")),m.createElement(R,{flexWrap:"wrap",gap:1},l.map(e=>m.createElement(R,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},m.createElement(E,{color:"white"},e.name)))))}function Mr({message:l,onSuggestionClick:e}){let{role:t,content:s,tool:n}=l;if(t==="system"){let o=s.split(`
|
|
522
|
+
`);return m.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},m.createElement(R,null,m.createElement(E,{color:"#6B7280"},"System")),m.createElement(R,{paddingLeft:1,flexDirection:"column"},o.map((i,a)=>m.createElement(E,{key:`sys-${a}-${i.slice(0,20)}`,color:"#9CA3AF"},i))))}if(t==="user")return m.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},m.createElement(R,null,m.createElement(E,{color:"#60A5FA",bold:!0},"You")),m.createElement(R,{paddingLeft:1},m.createElement(E,{color:"whiteBright"},s)));if(t==="assistant"){let{suggestions:o,cleanedContent:i}=Rr(s),{workingFiles:a,cleanedContent:c}=Or(i),d=c.replace(/\[TOOL:[^\]]+\]/g,"").trim().split(`
|
|
523
|
+
`);return m.createElement(R,{marginBottom:1,flexDirection:"column"},m.createElement(R,{marginBottom:0},m.createElement(E,{color:"#5AD8A6",bold:!0},"Orion")),m.createElement(R,{flexDirection:"column",paddingLeft:1},d.map((h,f)=>h.trim()===""?m.createElement(E,{key:`ln-${f}-empty`}," "):m.createElement(E,{key:`ln-${f}-${h.slice(0,15)}`,color:"whiteBright"},Fr(h)))),a.length>0&&m.createElement(_r,{workingFiles:a}),o.length>0&&m.createElement($r,{suggestions:o,onSelect:e}))}return null}ks();ie();ie();import B from"chalk";import Kr from"inquirer";var Re=class{authService;constructor(){this.authService=G.getInstance()}async login(){console.log(B.blue(`
|
|
524
|
+
🔐 Orion Authentication`)),console.log(B.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(B.yellow(`
|
|
525
|
+
📋 To authenticate, please follow these steps:`)),console.log(B.white("1. Open this URL in a browser (on any device):")),console.log(B.cyan.underline(` ${e}`)),console.log(B.white("2. Log in with your Orion account")),console.log(B.white("3. Copy the access token shown after login")),console.log(B.white("4. Paste the token below")),console.log(B.yellow(`
|
|
526
|
+
Paste your access token here:`));let{accessToken:t}=await Kr.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(B.gray(`
|
|
527
|
+
Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let n=await this.authService.getUserInfo();console.log(B.green(`
|
|
528
|
+
✅ Authentication successful!`)),n&&(console.log(B.gray(`Logged in as: ${n.email||n.username||"User"}`)),console.log(B.gray(`Subscription: ${this.getSubscriptionDisplay(n.subscription?.tier)}`)))}else console.log(B.red(`
|
|
529
|
+
❌ Authentication failed. Please try again.`))}catch(s){console.log(B.red(`
|
|
530
|
+
❌ Authentication error: ${s.message}`))}}async logout(){console.log(B.yellow(`
|
|
531
|
+
🔄 Signing out...`)),console.log(B.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(B.green(`
|
|
532
|
+
✅ Successfully signed out`)),console.log(B.gray("All authentication data and settings have been cleared.")),console.log(B.gray('Run "orion auth login" to sign in again.'))):(console.log(B.red(`
|
|
533
|
+
❌ Logout failed`)),console.log(B.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(B.green(`
|
|
534
|
+
✅ Authenticated`)),t){console.log(B.gray("─".repeat(50))),console.log(B.white("User:",t.name||t.username||"N/A")),console.log(B.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(B.white("Subscription:",s)),t.usage&&(console.log(B.gray(`
|
|
535
|
+
Usage:`)),console.log(B.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(B.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(B.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(B.yellow(`
|
|
536
|
+
⚠️ Not authenticated`)),console.log(B.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"}}};fe();var qn=!1;async function Es(){if(qn){console.log("Already running...");return}qn=!0,$.enableCustomUI();let l=lt.getInstance(),e=G.getInstance();if(!l.isInitialized()){console.log("🔧 Initializing Orion services...");try{await l.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(s){console.error(`
|
|
537
|
+
❌ Failed to initialize services:`,s.message),console.error(`
|
|
447
538
|
💡 Tip: Check your internet connection and Firebase configuration.
|
|
448
539
|
`),process.exit(1)}}(!await e.autoAuthenticate()||!e.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
|
|
449
|
-
`),await new
|
|
540
|
+
`),await new Re().login(),e.isAuthenticated()||(console.error(`
|
|
450
541
|
❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
|
|
451
542
|
✨ Starting Orion CLI...
|
|
452
543
|
`)),e.isFirebaseAuthenticated()||(console.error(`
|
|
453
544
|
❌ 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(`
|
|
454
545
|
Please check your connection and try again.
|
|
455
|
-
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),
|
|
456
|
-
|
|
546
|
+
`),process.exit(1)),console.log("✅ Authentication verified"),process.stdout.write("\x1B[2J\x1B[H"),Qr(Vr.createElement(On),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1})}$e();U();import{EventEmitter as Jr}from"events";import Yr from"axios";import{execSync as Zr}from"child_process";import Hn from"chalk";var zt=class l extends Jr{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;constructor(e){super(),this.currentVersion=e}static getInstance(e){return l.instance||(l.instance=new l(e)),l.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 Yr.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let s=e.split(".").map(Number),n=t.split(".").map(Number);for(let o=0;o<3;o++){let i=s[o]||0,a=n[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}`),Zr(t,{stdio:"pipe",encoding:"utf8"}),console.log(Hn.green(`
|
|
547
|
+
✓ Updated to v${e}`)+Hn.gray(` - restart CLI to use new version
|
|
548
|
+
`)),this.emit("updated",{from:this.currentVersion,to:e})}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 ti from"dotenv";import{fileURLToPath as si}from"url";import{dirname as ni,join as oi}from"path";import{readFileSync as ri}from"fs";ti.config();var ii=si(import.meta.url),ai=ni(ii),Gn=JSON.parse(ri(oi(ai,"..","package.json"),"utf8")),ci=process.argv[1]?.includes("tsx")||process.argv[1]?.includes("/orion-cli/")||!process.argv[1]?.includes("node_modules")||!1;ci||zt.getInstance(Gn.version).checkAndUpdate().catch(()=>{});var Qe=new ei;Qe.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Gn.version);Qe.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Es()}catch(l){console.error(oe.formatError(l.message)),process.exit(1)}});Qe.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(l,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(ks(),Bn)),s=t.getInstance();console.log("🔧 Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let n=K.find(i=>i.name===e.model)||K[0];console.log("💭 Sending message...");let o=await s.sendMessage(l,n,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(qt(o))}catch(t){oe.stopSpinner(!1),console.error(oe.formatError(t.message)),process.exit(1)}});var xs=Qe.command("auth").description("Authentication commands");xs.command("login").description("Login to Orion").action(async()=>{try{await new Re().login()}catch(l){console.error(oe.formatError(l.message)),process.exit(1)}});xs.command("logout").description("Logout from Orion").action(async()=>{try{await new Re().logout()}catch(l){console.error(oe.formatError(l.message)),process.exit(1)}});xs.command("status").description("Check authentication status").action(async()=>{try{await new Re().status()}catch(l){console.error(oe.formatError(l.message)),process.exit(1)}});Qe.command("models").description("List available AI models").action(()=>{oe.printHeader("Available Models");for(let l of K)console.log(`${oe.formatModelName(l.name)} - ${l.displayName}`)});process.argv.length===2?Es().catch(l=>{console.error(oe.formatError(l.message)),process.exit(1)}):Qe.parse(process.argv);
|