@zinley/orion 1.2.18 → 1.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +63 -63
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- var ls=Object.defineProperty;var Ci=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var xi=Object.prototype.hasOwnProperty;var Ei=(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 M=(c,e)=>()=>(c&&(e=c(c=0)),e);var Se=(c,e)=>{for(var t in e)ls(c,t,{get:e[t],enumerable:!0})},Ii=(c,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ki(e))!xi.call(c,n)&&n!==t&&ls(c,n,{get:()=>e[n],enumerable:!(s=Ci(e,n))||s.enumerable});return c};var Pi=c=>Ii(ls({},"__esModule",{value:!0}),c);var Q,je=M(()=>{"use strict";Q=[{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 us,o,W=M(()=>{"use strict";us=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},o=us.getInstance()});var Ee={};Se(Ee,{UserDefaults:()=>Fe});import ct from"fs";import ds from"path";import Di from"os";var ps,Fe,ve=M(()=>{"use strict";W();ps=class c{static instance;preferencesPath;preferences={};constructor(){let e=ds.join(Di.homedir(),".orion");this.preferencesPath=ds.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(ct.existsSync(this.preferencesPath)){let e=ct.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),o.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{o.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=ds.dirname(this.preferencesPath);ct.existsSync(e)||ct.mkdirSync(e,{recursive:!0}),ct.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),o.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){o.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),o.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),o.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Fe=ps.getInstance()});var ge,ms=M(()=>{"use strict";je();ve();W();ge=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=Fe.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Fe.set("userSubscriptionTier",e),o.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),n=t>=s;return o.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 Q.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 Ai from"axios";import{EventEmitter as Ni}from"events";var $e,Oe,Ct=M(()=>{"use strict";$e="firebase_timestamp",Oe=class c extends Ni{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Ai.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(()=>(ve(),Ee));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ue(),Js));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 i={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",i,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};t&&(n.limit=t.toString());try{let r=(await this.client.get("/documents",{params:n,headers:s})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async queryDocuments(e,t,s,n,i,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:s,value:String(n)};i&&(u.limit=i.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let m=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(m.success)return Array.isArray(m.doc)?m.doc:m.doc&&typeof m.doc=="object"?[m.doc]:[];{let S=m.error||"Unknown error";throw new Error(S)}}catch(d){throw d}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:n,headers:s})).data;return r.success?r.doc:null}catch(i){throw i}}async updateDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let i={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,i,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:n,headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async createDocumentInSubcollection(e,t,s,n,i){let r=`${e}/${t}/${s}`;return this.createDocument(r,n,i)}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 i of n)i.id&&await this.deleteDocument(s,i.id);for(let[i,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${i}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:i,conversationId:e};try{await this.createDocument(s,a,l)}catch{}}}catch(n){throw n}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((n,i)=>{if(n.order!==void 0&&i.order!==void 0)return n.order-i.order;let r=new Date(n.timestamp||0).getTime(),a=new Date(i.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,updates:t};try{let r=(await this.client.put("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let i=(await this.client.get("/realtime",{params:s,headers:t})).data;if(i.success)return i.doc;{let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let i=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!i.success){let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=await this.client.get("/realtime",{params:s,headers:t}),i=n.data;if(i.success)return n.data.data;{let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime/push",n,{headers:s})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}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 gs={};Se(gs,{DeviceRegistrationService:()=>de});import{EventEmitter as Ri}from"events";import{v4 as Ys}from"uuid";import lt from"os";import Zs from"fs/promises";import Fi from"path";import{execSync as ut}from"child_process";import Oi from"crypto";var de,_e=M(()=>{"use strict";Ct();ue();W();de=class c extends Ri{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Oe.getInstance(),this.authService=X.getInstance(),this.configDir=Fi.join(lt.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){o.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{o.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{o.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();o.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(o.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){o.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),o.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(o.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,o.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),o.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw o.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}o.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),o.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){o.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return o.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=lt.platform();if(e==="darwin")try{let n=ut("scutil --get ComputerName",{encoding:"utf8"}).trim();if(n)return o.debug(`[DEVICE REG] macOS ComputerName: ${n}`),n}catch{o.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let n=ut('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(n&&n[1]){let i=n[1].trim();if(i)return o.debug(`[DEVICE REG] Windows ComputerName: ${i}`),i}}catch{o.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=lt.hostname();return o.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return o.debug(`[DEVICE REG] Error getting computer name: ${e}`),lt.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=lt.platform();try{let t=null;switch(e){case"darwin":try{let a=ut("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],o.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=ut("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],o.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Zs.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),o.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Zs.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),o.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{o.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=ut("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
- `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),o.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:o.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=Oi.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return o.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee)),n="snowx_fallback_device_id",i=s.string(n);return i?o.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${i}`):(i=Ys(),s.set(n,i),o.debug(`[DEVICE REG] Generated NEW fallback UUID: ${i}`)),i}catch(t){o.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee)),n="snowx_fallback_device_id",i=s.string(n);return i?o.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${i}`):(i=Ys(),s.set(n,i),o.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${i}`)),i}}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 i=n.devices;if(i.some(a=>a.deviceId===t)){let a=i.map(l=>l.deviceId===t?{...l,lastSeenAt:$e,computerName:s,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:$e,lastSeenAt:$e};i.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:i})}}else{let r={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:$e,lastSeenAt:$e}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}o.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:s})}catch(n){throw o.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:n.message,code:n.code}),n}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let s=await this.api.getDocument(this.devicesCollection,e);if(!s||!s.devices||!Array.isArray(s.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let n=s.devices;if(!n.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=n.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Js={};Se(Js,{AuthService:()=>X});import{EventEmitter as $i}from"events";import{signInAnonymously as _i,signInWithEmailAndPassword as Mi,createUserWithEmailAndPassword as Li,signOut as Ui,onAuthStateChanged as en,updateProfile as Wi,signInWithCustomToken as Bi}from"firebase/auth";import Me from"axios";import hs from"fs/promises";import tn from"path";import Hi from"os";var X,ue=M(()=>{"use strict";ms();W();X=class c extends $i{static instance;auth=null;currentUser=null;authToken=null;userProfile=null;tokenFilePath;snowxAuthEndpoint="https://snowx.ai/api/auth";snowxApiEndpoint="https://snowx.ai/api-beta/api";constructor(){super(),this.tokenFilePath=tn.join(Hi.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=tn.dirname(this.tokenFilePath);await hs.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ve(),Ee)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let n=await hs.readFile(this.tokenFilePath,"utf-8"),i=JSON.parse(n);i.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",i.userId),e.set("snowx_access_token",i.token),t=i.userId,s=i.token,await hs.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,o.debug("Session restored from UserDefaults");try{let i=await this.getUserProfile();i&&i.tier!==void 0?this.authToken.tier=i.tier:await this.updateUserTierFromToken(n)}catch(i){console.warn("⚠️ Failed to fetch user profile during session restore:",i instanceof Error?i.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(()=>(ve(),Ee));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(()=>(ve(),Ee));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,en(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}ge.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),o.debug(`User tier updated: ${ge.getDisplayName(t)} (${e.tier})`),o.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await _i(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 Mi(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 Li(this.auth,e,t);return this.currentUser=n.user,s&&await Wi(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(()=>(_e(),gs));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ui(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(()=>(_e(),gs));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ve(),Ee)),s=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of s)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let i=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of i)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Me.post(`${this.snowxAuthEndpoint}/login`,e):t=await Me.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 Me.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(()=>(ve(),Ee));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 i=!1,r,a=en(this.auth,async l=>{if(!i)if(i=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);n(u)}catch{n(null)}else n(null)});r=setTimeout(()=>{i||(i=!0,a(),n(null))},2e3)});if(s)return s}let e=await this.getAccessTokenFromStorage();return e?(o.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){o.debug("Using existing authentication token"),o.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?(o.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(o.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 o.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.response?.status===404?(o.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):o.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),o.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),o.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),o.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),o.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),o.debug("Signing into Firebase with custom token...");let t=await Bi(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),o.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),o.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let s=4-t;console.log(`📡 [AUTH-API] Attempt ${s}/3: Getting custom token for user: ${e}`),o.debug(`Getting custom token from API for user: ${e} (attempt ${s}/3)`);let n="https://snowx.ai/api-beta/api/fb/custom-token",i={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${n}`);try{let l=await Me.post(n,i,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let d=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${d}`),new Error(`Custom token API failed: ${d}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),o.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${s}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),o.error("Failed to get custom token:",{attempt:s,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let d=Math.pow(2,s)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),o.debug(`Retrying in ${d}ms...`),await new Promise(m=>setTimeout(m,d)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let s=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:s.user_id||s.sub,email:s.email,name:s.name,exp:s.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let s={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(s);try{let n=await this.getUserProfileWithIdToken(e,t.userId);n&&(this.authToken.tier=n.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let s=await Me.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,i=n.subscription?.tier??0;return{id:t,email:n.email,tier:i}}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 Me.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 i={token:e,userId:n,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(i),this.userProfile=s,await this.updateUserTierFromToken(i);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(o.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):o.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",i),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 Me.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 ge.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 Me.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 sn={};Se(sn,{MessageQueueManager:()=>Ce});import{EventEmitter as qi}from"events";var Ce,Xe=M(()=>{"use strict";W();Ce=class c extends qi{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),o.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),o.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});import{encode as nn,decode as on,isWithinTokenLimit as rn,countTokens as zi}from"gpt-tokenizer/encoding/cl100k_base";var Ve,Gi,ji,be,Ke=M(()=>{"use strict";Ve=25e3,Gi=1400,ji=17e3,be=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??Ve,this.previewTokens=e?.previewTokens??Gi,this.maxContentTokens=e?.maxContentTokens??ji}count(e){return e?zi(e):0}encode(e){return e?nn(e):[]}decode(e){return!e||e.length===0?"":on(e)}isWithinLimit(e,t){return e?rn(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=rn(e,s);if(n!==!1)return{text:e,tokens:n,truncated:!1};let r=nn(e).slice(0,s);return{text:on(r),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:i,tokens:r}=this.truncate(e,s);return{preview:i,totalTokens:n,previewTokens:r,remainingTokens:n-r}}truncateContent(e,t){let s=t??this.maxContentTokens,n=this.truncate(e,s);return n.truncated?n.text+`
2
+ var cs=Object.defineProperty;var Ci=Object.getOwnPropertyDescriptor;var ki=Object.getOwnPropertyNames;var xi=Object.prototype.hasOwnProperty;var Ei=(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 M=(c,e)=>()=>(c&&(e=c(c=0)),e);var Se=(c,e)=>{for(var t in e)cs(c,t,{get:e[t],enumerable:!0})},Ii=(c,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ki(e))!xi.call(c,n)&&n!==t&&cs(c,n,{get:()=>e[n],enumerable:!(s=Ci(e,n))||s.enumerable});return c};var Pi=c=>Ii(cs({},"__esModule",{value:!0}),c);var Q,je=M(()=>{"use strict";Q=[{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 ls,o,W=M(()=>{"use strict";ls=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},o=ls.getInstance()});var Ee={};Se(Ee,{UserDefaults:()=>Fe});import ct from"fs";import us from"path";import Di from"os";var ds,Fe,ve=M(()=>{"use strict";W();ds=class c{static instance;preferencesPath;preferences={};constructor(){let e=us.join(Di.homedir(),".orion");this.preferencesPath=us.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(ct.existsSync(this.preferencesPath)){let e=ct.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),o.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{o.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=us.dirname(this.preferencesPath);ct.existsSync(e)||ct.mkdirSync(e,{recursive:!0}),ct.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),o.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){o.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),o.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),o.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Fe=ds.getInstance()});var ge,ps=M(()=>{"use strict";je();ve();W();ge=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=Fe.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){Fe.set("userSubscriptionTier",e),o.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),n=t>=s;return o.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 Q.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 Ai from"axios";import{EventEmitter as Ni}from"events";var $e,Oe,Ct=M(()=>{"use strict";$e="firebase_timestamp",Oe=class c extends Ni{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Ai.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(()=>(ve(),Ee));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ue(),Qs));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 i={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",i,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};t&&(n.limit=t.toString());try{let r=(await this.client.get("/documents",{params:n,headers:s})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async queryDocuments(e,t,s,n,i,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:s,value:String(n)};i&&(u.limit=i.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let m=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(m.success)return Array.isArray(m.doc)?m.doc:m.doc&&typeof m.doc=="object"?[m.doc]:[];{let S=m.error||"Unknown error";throw new Error(S)}}catch(d){throw d}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:n,headers:s})).data;return r.success?r.doc:null}catch(i){throw i}}async updateDocument(e,t,s){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let i={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,i,{headers:n})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let s={};await this.addAuthorizationHeader(s);let n={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:n,headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async createDocumentInSubcollection(e,t,s,n,i){let r=`${e}/${t}/${s}`;return this.createDocument(r,n,i)}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 i of n)i.id&&await this.deleteDocument(s,i.id);for(let[i,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${i}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:i,conversationId:e};try{await this.createDocument(s,a,l)}catch{}}}catch(n){throw n}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((n,i)=>{if(n.order!==void 0&&i.order!==void 0)return n.order-i.order;let r=new Date(n.timestamp||0).getTime(),a=new Date(i.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,updates:t};try{let r=(await this.client.put("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let i=(await this.client.get("/realtime",{params:s,headers:t})).data;if(i.success)return i.doc;{let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let i=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!i.success){let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=await this.client.get("/realtime",{params:s,headers:t}),i=n.data;if(i.success)return n.data.data;{let r=i.error||"Unknown error";throw new Error(r)}}catch(n){throw n}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime",n,{headers:s})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let n={path:e,data:t};try{let r=(await this.client.post("/realtime/push",n,{headers:s})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(i){throw i}}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 ms={};Se(ms,{DeviceRegistrationService:()=>de});import{EventEmitter as Ri}from"events";import{v4 as Js}from"uuid";import lt from"os";import Ys from"fs/promises";import Fi from"path";import{execSync as ut}from"child_process";import Oi from"crypto";var de,_e=M(()=>{"use strict";Ct();ue();W();de=class c extends Ri{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Oe.getInstance(),this.authService=X.getInstance(),this.configDir=Fi.join(lt.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){o.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{o.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{o.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();o.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(o.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){o.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),o.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(o.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,o.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),o.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw o.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}o.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),o.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){o.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return o.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=lt.platform();if(e==="darwin")try{let n=ut("scutil --get ComputerName",{encoding:"utf8"}).trim();if(n)return o.debug(`[DEVICE REG] macOS ComputerName: ${n}`),n}catch{o.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let n=ut('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(n&&n[1]){let i=n[1].trim();if(i)return o.debug(`[DEVICE REG] Windows ComputerName: ${i}`),i}}catch{o.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=lt.hostname();return o.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return o.debug(`[DEVICE REG] Error getting computer name: ${e}`),lt.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=lt.platform();try{let t=null;switch(e){case"darwin":try{let a=ut("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],o.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=ut("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],o.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Ys.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),o.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Ys.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),o.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{o.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=ut("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
+ `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),o.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:o.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=Oi.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return o.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee)),n="snowx_fallback_device_id",i=s.string(n);return i?o.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${i}`):(i=Js(),s.set(n,i),o.debug(`[DEVICE REG] Generated NEW fallback UUID: ${i}`)),i}catch(t){o.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee)),n="snowx_fallback_device_id",i=s.string(n);return i?o.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${i}`):(i=Js(),s.set(n,i),o.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${i}`)),i}}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 i=n.devices;if(i.some(a=>a.deviceId===t)){let a=i.map(l=>l.deviceId===t?{...l,lastSeenAt:$e,computerName:s,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:$e,lastSeenAt:$e};i.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:i})}}else{let r={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:$e,lastSeenAt:$e}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}o.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:s})}catch(n){throw o.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:n.message,code:n.code}),n}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let s=await this.api.getDocument(this.devicesCollection,e);if(!s||!s.devices||!Array.isArray(s.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let n=s.devices;if(!n.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=n.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Qs={};Se(Qs,{AuthService:()=>X});import{EventEmitter as $i}from"events";import{signInAnonymously as _i,signInWithEmailAndPassword as Mi,createUserWithEmailAndPassword as Li,signOut as Ui,onAuthStateChanged as Zs,updateProfile as Wi,signInWithCustomToken as Bi}from"firebase/auth";import Me from"axios";import gs from"fs/promises";import en from"path";import Hi from"os";var X,ue=M(()=>{"use strict";ps();W();X=class c extends $i{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=en.join(Hi.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=en.dirname(this.tokenFilePath);await gs.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(ve(),Ee)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let n=await gs.readFile(this.tokenFilePath,"utf-8"),i=JSON.parse(n);i.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",i.userId),e.set("snowx_access_token",i.token),t=i.userId,s=i.token,await gs.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,o.debug("Session restored from UserDefaults");try{let i=await this.getUserProfile();i&&i.tier!==void 0?this.authToken.tier=i.tier:await this.updateUserTierFromToken(n)}catch(i){console.warn("⚠️ Failed to fetch user profile during session restore:",i instanceof Error?i.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(()=>(ve(),Ee));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(()=>(ve(),Ee));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,Zs(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}ge.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(ve(),Ee));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),o.debug(`User tier updated: ${ge.getDisplayName(t)} (${e.tier})`),o.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await _i(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 Mi(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 Li(this.auth,e,t);return this.currentUser=n.user,s&&await Wi(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(()=>(_e(),ms));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ui(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(()=>(_e(),ms));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(ve(),Ee)),s=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of s)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let i=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of i)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Me.post(`${this.snowxAuthEndpoint}/login`,e):t=await Me.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 Me.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(()=>(ve(),Ee));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 i=!1,r,a=Zs(this.auth,async l=>{if(!i)if(i=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);n(u)}catch{n(null)}else n(null)});r=setTimeout(()=>{i||(i=!0,a(),n(null))},2e3)});if(s)return s}let e=await this.getAccessTokenFromStorage();return e?(o.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){o.debug("Using existing authentication token"),o.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?(o.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(o.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 o.error("Failed to authenticate with Firebase during auto-authenticate:",s.message),s.response?.status===401||s.response?.status===403||s.response?.status===404?(o.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):o.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),o.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),o.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),o.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),o.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),o.debug("Signing into Firebase with custom token...");let t=await Bi(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),o.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),o.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let s=4-t;console.log(`📡 [AUTH-API] Attempt ${s}/3: Getting custom token for user: ${e}`),o.debug(`Getting custom token from API for user: ${e} (attempt ${s}/3)`);let n="https://snowx.ai/api-beta/api/fb/custom-token",i={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${n}`);try{let l=await Me.post(n,i,{headers:a,timeout:15e3});if(console.log(`✅ [AUTH-API] Received response with status: ${l.status}`),l.status!==200){let d=l.data?.message||`HTTP ${l.status}`;throw console.error(`❌ [AUTH-API] API returned non-200 status: ${d}`),new Error(`Custom token API failed: ${d}`)}let u=l.data;if(!u?.success||!u?.customToken)throw console.error("❌ [AUTH-API] API response missing success/customToken fields"),console.error("❌ [AUTH-API] Response data:",JSON.stringify(u)),new Error("Invalid custom token response from API");return console.log("✅ [AUTH-API] Custom token successfully received"),o.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${s}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),o.error("Failed to get custom token:",{attempt:s,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let d=Math.pow(2,s)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),o.debug(`Retrying in ${d}ms...`),await new Promise(m=>setTimeout(m,d)),this.getCustomTokenFromAPIInternal(e,t-1)}throw console.error("❌ [AUTH-API] All retry attempts exhausted or non-retryable error"),l}}isFirebaseIdToken(e){try{let t=e.split(".");return t.length!==3?!1:JSON.parse(Buffer.from(t[1],"base64url").toString()).iss?.includes("securetoken.google.com")}catch{return!1}}parseFirebaseIdToken(e){try{let t=e.split(".");if(t.length!==3)return null;let s=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:s.user_id||s.sub,email:s.email,name:s.name,exp:s.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let s={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(s);try{let n=await this.getUserProfileWithIdToken(e,t.userId);n&&(this.authToken.tier=n.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let s=await Me.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,i=n.subscription?.tier??0;return{id:t,email:n.email,tier:i}}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 Me.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 i={token:e,userId:n,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(i),this.userProfile=s,await this.updateUserTierFromToken(i);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(o.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):o.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",i),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 Me.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 ge.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 Me.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 tn={};Se(tn,{MessageQueueManager:()=>Ce});import{EventEmitter as qi}from"events";var Ce,Xe=M(()=>{"use strict";W();Ce=class c extends qi{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),o.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),o.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});import{encode as sn,decode as nn,isWithinTokenLimit as on,countTokens as zi}from"gpt-tokenizer/encoding/cl100k_base";var Ve,Gi,ji,be,Ke=M(()=>{"use strict";Ve=25e3,Gi=1400,ji=17e3,be=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??Ve,this.previewTokens=e?.previewTokens??Gi,this.maxContentTokens=e?.maxContentTokens??ji}count(e){return e?zi(e):0}encode(e){return e?sn(e):[]}decode(e){return!e||e.length===0?"":nn(e)}isWithinLimit(e,t){return e?on(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=on(e,s);if(n!==!1)return{text:e,tokens:n,truncated:!1};let r=sn(e).slice(0,s);return{text:nn(r),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:i,tokens:r}=this.truncate(e,s);return{preview:i,totalTokens:n,previewTokens:r,remainingTokens:n-r}}truncateContent(e,t){let s=t??this.maxContentTokens,n=this.truncate(e,s);return n.truncated?n.text+`
4
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
6
  [Output truncated at ${n.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,s){let{preview:n,totalTokens:i,previewTokens:r,remainingTokens:a}=this.generatePreview(e,s?.previewTokens??this.previewTokens),l=`Response too large (${i.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
@@ -24,9 +24,9 @@ To read full content: use tools like 'read_file' with path above`,l}formatLargeF
24
24
  `,l+=`${"─".repeat(50)}
25
25
  `,l+=n,a>0&&(l+=`
26
26
  ${"─".repeat(50)}`,l+=`
27
- ... (${a.toLocaleString()} more tokens)`),l}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as Xi}from"events";var an,cn,Vi,Ki,Qi,dt,ln,fs=M(()=>{"use strict";W();an=10,cn=2e3,Vi=5e3,Ki=200,Qi=3e3,dt=class c extends Xi{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),o.debug("[SubAgentManager] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.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:o.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:s}=e;if(!t||!s){o.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 i=1;i<=s;i++)n.agents.set(i,{agentNumber:i,task:"",status:"pending"});this.operations.set(t,n),o.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 i=this.operations.get(t);if(!i){o.debug(`[SubAgentManager] Operation not found: ${t}`);return}i.status==="starting"&&(i.status="running");let r=this.truncateString(n||"",Ki);i.agents.set(s,{agentNumber:s,task:r,status:"running",startTime:new Date}),o.debug(`[SubAgentManager] Agent ${s} started: ${r.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:s,task:r}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:s,content:n}=e;if(!t||!s||!n)return;let i=this.operations.get(t);if(!i)return;let r=i.agents.get(s);if(!r)return;let l=(r.streamingContent||"")+n;l.length>cn?r.streamingContent=l.slice(-cn):r.streamingContent=l,this.emit("agent_streaming",{operationId:t,agentNumber:s,content:r.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:s,result:n,error:i}=e;if(!t||!s)return;let r=this.operations.get(t);if(!r)return;let a=r.agents.get(s);if(!a)return;let l=i?"failed":"completed";a.status=l,a.endTime=new Date,a.result=this.truncateString(n||"",Vi),a.error=i;let u=a.startTime?(a.endTime.getTime()-a.startTime.getTime())/1e3:0;o.debug(`[SubAgentManager] Agent ${s} ${l} (${u.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:s,status:l,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()),i=n.some(d=>d.status==="failed"),r=n.every(d=>d.status==="completed"||d.status==="failed");s.status=i?"failed":"completed",s.endTime=new Date;let a=(s.endTime.getTime()-s.startTime.getTime())/1e3,l=n.filter(d=>d.status==="completed").length,u=n.filter(d=>d.status==="failed").length;o.debug(`[SubAgentManager] Spawn completed: ${l} success, ${u} failed (${a.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:s.status,duration:a,successCount:l,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(l=>l.status==="pending").length,i=s.filter(l=>l.status==="running").length,r=s.filter(l=>l.status==="completed").length,a=s.filter(l=>l.status==="failed").length;this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:n,running:i,completed:r,failed:a,agents:s.map(l=>({agentNumber:l.agentNumber,task:l.task,status:l.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,i=s.filter(d=>d.status==="running").length,r=s.filter(d=>d.status==="completed").length,a=s.filter(d=>d.status==="failed").length,u=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${r}/${t.totalAgents} complete`;return i>0&&(u+=` (${i} 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((i,r)=>i.agentNumber-r.agentNumber);for(let i of n){let r={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[i.status]||"❓",a=i.task?`: ${i.task.substring(0,60)}${i.task.length>60?"...":""}`:"";s.push(` ${r} Agent ${i.agentNumber}${a}`),i.error&&s.push(` └─ Error: ${i.error.substring(0,80)}${i.error.length>80?"...":""}`)}return s.join(`
28
- `)}cleanupOldOperations(){if(this.operations.size<an)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-an+1));for(let{id:s}of t){this.operations.delete(s);let n=this.cleanupTimers.get(s);n&&(clearTimeout(n),this.cleanupTimers.delete(s)),o.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),o.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},Qi);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(),o.debug("[SubAgentManager] Cleared all operations")}},ln=dt.getInstance()});var kt,un=M(()=>{"use strict";W();kt=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),o.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let s=e.toLowerCase();for(let[n,i]of this.tools.entries())if(n.toLowerCase()===s)return i}async executeTool(e,t,s,n){let i=this.getTool(e);if(!i)return o.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{o.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await i.execute(t,e,s,n),l=Date.now()-r;o.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(d=>d.text||"").join(`
29
- `);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(r){return o.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),s=[];for(let n of this.tools.keys())n.toLowerCase()===t&&s.push(n);for(let n of s)this.tools.delete(n);o.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),o.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var dn={};Se(dn,{ToolDisplay:()=>U});import K from"chalk";var U,ke=M(()=>{"use strict";U=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,s){if(c.customUIMode)return;let n=this.getToolPrefix(e);if(console.log(K.cyan(`
27
+ ... (${a.toLocaleString()} more tokens)`),l}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as Xi}from"events";var rn,an,Vi,Ki,Qi,dt,cn,hs=M(()=>{"use strict";W();rn=10,an=2e3,Vi=5e3,Ki=200,Qi=3e3,dt=class c extends Xi{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),o.debug("[SubAgentManager] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.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:o.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:s}=e;if(!t||!s){o.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 i=1;i<=s;i++)n.agents.set(i,{agentNumber:i,task:"",status:"pending"});this.operations.set(t,n),o.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 i=this.operations.get(t);if(!i){o.debug(`[SubAgentManager] Operation not found: ${t}`);return}i.status==="starting"&&(i.status="running");let r=this.truncateString(n||"",Ki);i.agents.set(s,{agentNumber:s,task:r,status:"running",startTime:new Date}),o.debug(`[SubAgentManager] Agent ${s} started: ${r.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:s,task:r}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:s,content:n}=e;if(!t||!s||!n)return;let i=this.operations.get(t);if(!i)return;let r=i.agents.get(s);if(!r)return;let l=(r.streamingContent||"")+n;l.length>an?r.streamingContent=l.slice(-an):r.streamingContent=l,this.emit("agent_streaming",{operationId:t,agentNumber:s,content:r.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:s,result:n,error:i}=e;if(!t||!s)return;let r=this.operations.get(t);if(!r)return;let a=r.agents.get(s);if(!a)return;let l=i?"failed":"completed";a.status=l,a.endTime=new Date,a.result=this.truncateString(n||"",Vi),a.error=i;let u=a.startTime?(a.endTime.getTime()-a.startTime.getTime())/1e3:0;o.debug(`[SubAgentManager] Agent ${s} ${l} (${u.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:s,status:l,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()),i=n.some(d=>d.status==="failed"),r=n.every(d=>d.status==="completed"||d.status==="failed");s.status=i?"failed":"completed",s.endTime=new Date;let a=(s.endTime.getTime()-s.startTime.getTime())/1e3,l=n.filter(d=>d.status==="completed").length,u=n.filter(d=>d.status==="failed").length;o.debug(`[SubAgentManager] Spawn completed: ${l} success, ${u} failed (${a.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:s.status,duration:a,successCount:l,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(l=>l.status==="pending").length,i=s.filter(l=>l.status==="running").length,r=s.filter(l=>l.status==="completed").length,a=s.filter(l=>l.status==="failed").length;this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:n,running:i,completed:r,failed:a,agents:s.map(l=>({agentNumber:l.agentNumber,task:l.task,status:l.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,i=s.filter(d=>d.status==="running").length,r=s.filter(d=>d.status==="completed").length,a=s.filter(d=>d.status==="failed").length,u=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${r}/${t.totalAgents} complete`;return i>0&&(u+=` (${i} 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((i,r)=>i.agentNumber-r.agentNumber);for(let i of n){let r={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[i.status]||"❓",a=i.task?`: ${i.task.substring(0,60)}${i.task.length>60?"...":""}`:"";s.push(` ${r} Agent ${i.agentNumber}${a}`),i.error&&s.push(` └─ Error: ${i.error.substring(0,80)}${i.error.length>80?"...":""}`)}return s.join(`
28
+ `)}cleanupOldOperations(){if(this.operations.size<rn)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-rn+1));for(let{id:s}of t){this.operations.delete(s);let n=this.cleanupTimers.get(s);n&&(clearTimeout(n),this.cleanupTimers.delete(s)),o.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),o.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},Qi);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(),o.debug("[SubAgentManager] Cleared all operations")}},cn=dt.getInstance()});var kt,ln=M(()=>{"use strict";W();kt=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),o.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let s=e.toLowerCase();for(let[n,i]of this.tools.entries())if(n.toLowerCase()===s)return i}async executeTool(e,t,s,n){let i=this.getTool(e);if(!i)return o.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{o.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await i.execute(t,e,s,n),l=Date.now()-r;o.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(d=>d.text||"").join(`
29
+ `);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(r){return o.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),s=[];for(let n of this.tools.keys())n.toLowerCase()===t&&s.push(n);for(let n of s)this.tools.delete(n);o.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),o.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var un={};Se(un,{ToolDisplay:()=>U});import K from"chalk";var U,ke=M(()=>{"use strict";U=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,s){if(c.customUIMode)return;let n=this.getToolPrefix(e);if(console.log(K.cyan(`
30
30
  ${n} ${K.bold(e)}`)),t&&console.log(K.gray(` ${t}`)),s){let i=s.length>120?s.substring(0,120)+K.gray("..."):s;console.log(K.white(` ${i}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(c.customUIMode)return;let{toolName:t,output:s,success:n,executionTime:i,truncateLines:r=50}=e,a=s||"";s&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(s,r):t.toLowerCase().includes("write")?a=this.formatWriteOutput(s,r):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(s,r):a=this.formatGenericOutput(s,r)),a&&a.trim()&&console.log(a);let l=n?K.green("✓"):K.red("✗"),u=n?K.green("SUCCESS"):K.red("FAILED"),d=i?K.gray(` (${i}ms)`):"";console.log(`${l} ${u}${d}
31
31
  `)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
32
32
  `),u=a.slice(0,20).map(d=>K.gray(" ")+d).join(`
@@ -40,12 +40,12 @@ ${n} ${K.bold(e)}`)),t&&console.log(K.gray(` ${t}`)),s){let i=s.length>120?s.s
40
40
  `);let i=s.slice(0,t).map(r=>K.gray(" ")+K.dim(r)).join(`
41
41
  `);return i+=`
42
42
  `+K.gray(` ... (${s.length-t} more lines)`),i}static error(e,t){c.customUIMode||(console.log(`
43
- ${K.red("✗")} ${K.red.bold(e)} ${K.red("ERROR")}`),console.log(K.gray(" ")+K.white(t)),console.log(""))}}});import pn from"os";import vs from"path";function xt(){return process.platform==="win32"}function Be(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,pn.homedir())),xt()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,pn.homedir())),!xt()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),xt()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Qe(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=Be(c);if(xt()){let s=vs.basename(e).split(".")[0].toUpperCase();if(Ji.includes(s))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${s}`}}return vs.isAbsolute(e)?vs.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
43
+ ${K.red("✗")} ${K.red.bold(e)} ${K.red("ERROR")}`),console.log(K.gray(" ")+K.white(t)),console.log(""))}}});import dn from"os";import fs from"path";function xt(){return process.platform==="win32"}function Be(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,dn.homedir())),xt()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,dn.homedir())),!xt()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),xt()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function Qe(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=Be(c);if(xt()){let s=fs.basename(e).split(".")[0].toUpperCase();if(Ji.includes(s))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${s}`}}return fs.isAbsolute(e)?fs.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
44
44
 
45
45
  Path must be absolute (start with / on Unix or C:\\ on Windows)
46
46
 
47
47
  Wrong: Downloads/file.pdf
48
- Correct: /Users/username/Downloads/file.pdf`}}var Ji,Et=M(()=>{"use strict";Ji=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import mn from"path";var Yi,Zi,It,gn=M(()=>{"use strict";W();ke();Et();Ke();Yi=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],Zi={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"},It=class{toolNames=["read","Read"];async execute(e,t,s,n){let i=s.file_path||s.path,r=s.offset,a=s.limit;if(!i)throw new Error("Missing file_path or path argument");let l=Be(i),u=Qe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];o.debug(`[ReadFileTool] Reading file: ${l}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();U.start("Read",s.description,l);try{let m=await import("fs/promises");try{await m.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let S=await m.stat(l);if(S.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let w=mn.extname(l).substring(1).toLowerCase();if(Yi.includes(w)){o.debug(`[ReadFileTool] Image file detected: ${l}`);let h=(await m.readFile(l)).toString("base64"),v=Zi[w]||"application/octet-stream",C=mn.basename(l);o.debug(`[ReadFileTool] Image converted to base64: ${C} (${h.length} chars)`);let b=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:`Image loaded: ${C}`,success:!0,executionTime:b}),[{type:"image_url",image_url:{url:`data:${v};base64,${h}`}}]}let I=await m.readFile(l,"utf-8"),D=I.length,y=I.split(`
48
+ Correct: /Users/username/Downloads/file.pdf`}}var Ji,Et=M(()=>{"use strict";Ji=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import pn from"path";var Yi,Zi,It,mn=M(()=>{"use strict";W();ke();Et();Ke();Yi=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],Zi={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"},It=class{toolNames=["read","Read"];async execute(e,t,s,n){let i=s.file_path||s.path,r=s.offset,a=s.limit;if(!i)throw new Error("Missing file_path or path argument");let l=Be(i),u=Qe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];o.debug(`[ReadFileTool] Reading file: ${l}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();U.start("Read",s.description,l);try{let m=await import("fs/promises");try{await m.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let S=await m.stat(l);if(S.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let w=pn.extname(l).substring(1).toLowerCase();if(Yi.includes(w)){o.debug(`[ReadFileTool] Image file detected: ${l}`);let h=(await m.readFile(l)).toString("base64"),v=Zi[w]||"application/octet-stream",C=pn.basename(l);o.debug(`[ReadFileTool] Image converted to base64: ${C} (${h.length} chars)`);let b=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:`Image loaded: ${C}`,success:!0,executionTime:b}),[{type:"image_url",image_url:{url:`data:${v};base64,${h}`}}]}let I=await m.readFile(l,"utf-8"),D=I.length,y=I.split(`
49
49
  `),A=y.length,_=Math.max(r??0,0),P=new be;if(r===void 0&&a===void 0&&P.exceedsResponseLimit(I)){let E=P.count(I),h=S.size/1024,v=h/1024,C=v>=1?`${v.toFixed(2)} MB`:`${h.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
50
50
 
51
51
  File Information:
@@ -69,9 +69,9 @@ Suggested Solutions:
69
69
  The file has ${A.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(A===0||I.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(_>=A)return[{type:"text",text:`Error: Offset ${_} is beyond file length. File has ${A} total lines. Try a smaller offset (0 to ${A-1}).`}];let F=a!==void 0?Math.min(_+a,A):A,H=y.slice(_,F),g=H.map((E,h)=>`${(_+h+1).toString().padStart(6," ")} ${E}`).join(`
70
70
  `),N=g;if(r!==void 0||a!==void 0){let E=`
71
71
 
72
- [Read ${H.length} lines (${_+1}-${F}) of ${A} total lines]`;N=g+E}let x=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:N,success:!0,executionTime:x}),[{type:"text",text:N}]}catch(m){o.debug(`[ReadFileTool] Failed to read file: ${m.message}`);let S;m.code==="ENOENT"?S=`Error: File does not exist at path: ${l}`:m.code==="EACCES"?S=`Error: Permission denied. Cannot read file: ${l}`:m.code==="EISDIR"?S=`Error: Path is a directory, not a file: ${l}`:S=`Error reading file: ${m.message}`;let w=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:S,success:!1,executionTime:w}),[{type:"text",text:S}]}}}});import Pt from"fs/promises";import eo from"form-data";import bs from"axios";import Ts from"path";var Dt,hn=M(()=>{"use strict";W();ke();ue();Dt=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,s,n){let i=s.path;if(!i)throw new Error("Missing path argument");o.debug(`[ReadSpecialFileTool] Converting file: ${i}`);let r=Date.now();U.start("ReadSpecialFile",s.description,i);try{try{await Pt.access(i)}catch{return[{type:"text",text:`Error: File does not exist at path: ${i}`}]}let a=Ts.extname(i).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let _=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
+ [Read ${H.length} lines (${_+1}-${F}) of ${A} total lines]`;N=g+E}let x=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:N,success:!0,executionTime:x}),[{type:"text",text:N}]}catch(m){o.debug(`[ReadFileTool] Failed to read file: ${m.message}`);let S;m.code==="ENOENT"?S=`Error: File does not exist at path: ${l}`:m.code==="EACCES"?S=`Error: Permission denied. Cannot read file: ${l}`:m.code==="EISDIR"?S=`Error: Path is a directory, not a file: ${l}`:S=`Error reading file: ${m.message}`;let w=Date.now()-d;return U.result({toolName:"Read",filePath:l,output:S,success:!1,executionTime:w}),[{type:"text",text:S}]}}}});import Pt from"fs/promises";import eo from"form-data";import vs from"axios";import bs from"path";var Dt,gn=M(()=>{"use strict";W();ke();ue();Dt=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,s,n){let i=s.path;if(!i)throw new Error("Missing path argument");o.debug(`[ReadSpecialFileTool] Converting file: ${i}`);let r=Date.now();U.start("ReadSpecialFile",s.description,i);try{try{await Pt.access(i)}catch{return[{type:"text",text:`Error: File does not exist at path: ${i}`}]}let a=bs.extname(i).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let _=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.
73
73
 
74
- Supported file types: ${_}`}]}let l=await Pt.stat(i),u=Ts.basename(i);if(o.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){o.debug(`[ReadSpecialFileTool] Image file detected: ${i}`);let P=(await Pt.readFile(i)).toString("base64"),F=this.imageMimeTypes[a]||"application/octet-stream";o.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${P.length} chars)`);let H=Date.now()-r;return U.result({toolName:"ReadSpecialFile",filePath:i,output:`Image loaded: ${u}`,success:!0,executionTime:H}),[{type:"image_url",image_url:{url:`data:${F};base64,${P}`}}]}let d=await this.uploadToBatchAPI(i,u);o.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let m=await this.pollBatchStatus(d);o.debug("[ReadSpecialFileTool] Conversion completed");let S=m.files[0];if(!S||S.status==="failed"){let _=S?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${_}`}]}let w=await this.fetchFileContent(S.file_id);if(!w.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let T=l.size/1024,I=T/1024,D=I>=1?`${I.toFixed(2)} MB`:`${T.toFixed(2)} KB`,y=`# File: ${u}
74
+ Supported file types: ${_}`}]}let l=await Pt.stat(i),u=bs.basename(i);if(o.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){o.debug(`[ReadSpecialFileTool] Image file detected: ${i}`);let P=(await Pt.readFile(i)).toString("base64"),F=this.imageMimeTypes[a]||"application/octet-stream";o.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${P.length} chars)`);let H=Date.now()-r;return U.result({toolName:"ReadSpecialFile",filePath:i,output:`Image loaded: ${u}`,success:!0,executionTime:H}),[{type:"image_url",image_url:{url:`data:${F};base64,${P}`}}]}let d=await this.uploadToBatchAPI(i,u);o.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let m=await this.pollBatchStatus(d);o.debug("[ReadSpecialFileTool] Conversion completed");let S=m.files[0];if(!S||S.status==="failed"){let _=S?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${_}`}]}let w=await this.fetchFileContent(S.file_id);if(!w.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let T=l.size/1024,I=T/1024,D=I>=1?`${I.toFixed(2)} MB`:`${T.toFixed(2)} KB`,y=`# File: ${u}
75
75
  **Type:** ${a.toUpperCase()}
76
76
  **Size:** ${D}
77
77
  **Conversion:** ✅ Successful
@@ -86,7 +86,7 @@ This could be due to:
86
86
  • Unsupported document structure
87
87
  • File is password-protected or encrypted
88
88
 
89
- For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-r;return U.result({toolName:"ReadSpecialFile",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let s=await Pt.readFile(e),n=Ts.extname(t).substring(1).toLowerCase(),r=await X.getInstance().getFirebaseIdToken(),a=new eo;a.append("files",s,{filename:t,contentType:this.getMimeType(n)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await bs.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let s=await X.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);for(let i=1;i<=this.maxPollAttempts;i++)try{let a=(await bs.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:n})).data;if(o.debug(`[ReadSpecialFileTool] Poll ${i} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(r){throw r.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${r.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let s=await X.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);try{let i=await bs.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:n});if(i.data.status==="failed")throw new Error(i.data.error||"Unknown conversion error");return i.data}catch(i){throw i.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${i.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 At,fn=M(()=>{"use strict";W();ke();Et();At=class{toolNames=["write","Write","write_file"];async execute(e,t,s,n){let i=s.file_path,r=s.content,a=s.edits;if(!i)throw new Error("Missing file_path argument");let l=Be(i),u=Qe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let d=Date.now();return U.start("Write",s.description,l),r!=null?await this.executeSimpleWrite(l,r,d):await this.executeEditsMode(l,a,d)}async executeSimpleWrite(e,t,s){o.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let n=await import("fs/promises"),r=(await import("path")).dirname(e);await n.mkdir(r,{recursive:!0}),await n.writeFile(e,t,"utf-8");let a=t.split(`
89
+ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-r;return U.result({toolName:"ReadSpecialFile",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let s=await Pt.readFile(e),n=bs.extname(t).substring(1).toLowerCase(),r=await X.getInstance().getFirebaseIdToken(),a=new eo;a.append("files",s,{filename:t,contentType:this.getMimeType(n)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await vs.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let s=await X.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);for(let i=1;i<=this.maxPollAttempts;i++)try{let a=(await vs.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:n})).data;if(o.debug(`[ReadSpecialFileTool] Poll ${i} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(r){throw r.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${r.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let s=await X.getInstance().getFirebaseIdToken(),n={};s&&(n.Authorization=`Bearer ${s}`);try{let i=await vs.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:n});if(i.data.status==="failed")throw new Error(i.data.error||"Unknown conversion error");return i.data}catch(i){throw i.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${i.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 At,hn=M(()=>{"use strict";W();ke();Et();At=class{toolNames=["write","Write","write_file"];async execute(e,t,s,n){let i=s.file_path,r=s.content,a=s.edits;if(!i)throw new Error("Missing file_path argument");let l=Be(i),u=Qe(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let d=Date.now();return U.start("Write",s.description,l),r!=null?await this.executeSimpleWrite(l,r,d):await this.executeEditsMode(l,a,d)}async executeSimpleWrite(e,t,s){o.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let n=await import("fs/promises"),r=(await import("path")).dirname(e);await n.mkdir(r,{recursive:!0}),await n.writeFile(e,t,"utf-8");let a=t.split(`
90
90
  `),l="";for(let m=0;m<Math.min(a.length,8);m++)l+=`+ ${a[m]}
91
91
  `;a.length>8&&(l+=`+ ...
92
92
 
@@ -98,14 +98,14 @@ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'ca
98
98
  `),S="";for(let w=0;w<Math.min(m.length,8);w++)S+=`+ ${m[w]}
99
99
  `;return m.length>8&&(S+=`+ ...
100
100
 
101
- (${m.length-8} more lines)`),[{type:"text",text:S.trim()}]}catch(n){return o.debug(`[WriteFileTool] Failed to write file: ${n.message}`),[{type:"text",text:`Error writing file: ${n.message}`}]}}}});var Nt,vn=M(()=>{"use strict";W();ke();Et();Nt=class{toolNames=["edit","Edit"];async execute(e,t,s,n){let i=s.file_path,r=s.old_string,a=s.new_string,l=s.replace_all===!0;if(!i)throw new Error("Missing file_path argument");if(r==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let u=Be(i),d=Qe(u);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];o.debug(`[EditFileTool] Editing file: ${u}`);let m=Date.now();U.start("Edit",s.description,u);try{let S=await import("fs/promises"),w=await S.readFile(u,"utf-8"),T,I=0;if(l)for(T=w;T.includes(r);)T=T.replace(r,a),I++;else w.includes(r)?(T=w.replace(r,a),I=1):T=w;if(I===0){let P=`No matches found for the specified old_string in file: ${u}`,F=Date.now()-m;return U.result({toolName:"Edit",filePath:u,output:P,success:!1,executionTime:F}),[{type:"text",text:P}]}await S.writeFile(u,T,"utf-8");let D=`Successfully edited file: Replaced ${I} occurrence(s)`;o.debug(`[EditFileTool] ${D}`);let y=Date.now()-m,A=(await import("chalk")).default,_=`${A.red("- "+r.split(`
101
+ (${m.length-8} more lines)`),[{type:"text",text:S.trim()}]}catch(n){return o.debug(`[WriteFileTool] Failed to write file: ${n.message}`),[{type:"text",text:`Error writing file: ${n.message}`}]}}}});var Nt,fn=M(()=>{"use strict";W();ke();Et();Nt=class{toolNames=["edit","Edit"];async execute(e,t,s,n){let i=s.file_path,r=s.old_string,a=s.new_string,l=s.replace_all===!0;if(!i)throw new Error("Missing file_path argument");if(r==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let u=Be(i),d=Qe(u);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];o.debug(`[EditFileTool] Editing file: ${u}`);let m=Date.now();U.start("Edit",s.description,u);try{let S=await import("fs/promises"),w=await S.readFile(u,"utf-8"),T,I=0;if(l)for(T=w;T.includes(r);)T=T.replace(r,a),I++;else w.includes(r)?(T=w.replace(r,a),I=1):T=w;if(I===0){let P=`No matches found for the specified old_string in file: ${u}`,F=Date.now()-m;return U.result({toolName:"Edit",filePath:u,output:P,success:!1,executionTime:F}),[{type:"text",text:P}]}await S.writeFile(u,T,"utf-8");let D=`Successfully edited file: Replaced ${I} occurrence(s)`;o.debug(`[EditFileTool] ${D}`);let y=Date.now()-m,A=(await import("chalk")).default,_=`${A.red("- "+r.split(`
102
102
  `).slice(0,5).join(`
103
103
  - `))}
104
104
  ${A.green("+ "+a.split(`
105
105
  `).slice(0,5).join(`
106
106
  + `))}
107
107
 
108
- Replaced ${I} occurrence(s)`;return U.result({toolName:"Edit",filePath:u,output:_,success:!0,executionTime:y}),[{type:"text",text:D}]}catch(S){o.debug(`[EditFileTool] Failed to edit file: ${S.message}`);let w=`Error editing file: ${S.message}`,T=Date.now()-m;return U.result({toolName:"Edit",filePath:u,output:w,success:!1,executionTime:T}),[{type:"text",text:w}]}}}});var Rt,bn=M(()=>{"use strict";W();Rt=class{toolNames=["upload_file"];async execute(e,t,s,n){let i=s.file_path;if(!i)throw new Error("Missing file_path argument");return o.debug(`[UploadFileTool] Upload file not implemented for CLI: ${i}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${i}`}]}}});import ys from"fs/promises";import to from"path";import so from"form-data";import no from"axios";var Ft,Tn=M(()=>{"use strict";W();ke();ue();Ft=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let i=s.zip_file_path;if(!i)throw new Error("Missing zip_file_path argument");let r=Date.now();U.start("DeployZipHTML",s.description,i);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let g=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 ${g} seconds.`)}o.debug(`[DeployZipHTML] Deploying HTML project: ${i}`);try{await ys.access(i)}catch{throw new Error(`ZIP file not found at path: ${i}`)}if(!i.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${i}`);let l=await ys.stat(i),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await ys.readFile(i),m=to.basename(i).replace(/[\r\n\t"']/g,"_");o.debug(`[DeployZipHTML] File: ${m}, Size: ${l.size} bytes`);let w=await X.getInstance().getFirebaseIdToken();if(!w)throw new Error("User must be authenticated to deploy projects");let T=new so;T.append("zipFile",d,{filename:m,contentType:"application/zip"});let I="https://snowx.ai/api/v2/deploy-zip";o.debug(`[DeployZipHTML] Uploading to ${I}`);let D=await no.post(I,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${w}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(D.status!==200&&D.status!==201)throw new Error(`Deployment failed with status ${D.status}: ${JSON.stringify(D.data)}`);let y=D.data;o.debug("[DeployZipHTML] Deployed successfully"),o.debug(`[DeployZipHTML] Response: ${JSON.stringify(y,null,2)}`);let A=y.data?.deployUrl||y.deployUrl||y.url||y.deploymentUrl||y.site_url||y.siteUrl||y.website_url,_=y.data?.deployId||y.deployId||y.projectId||y.deploymentId,P=y.data?.siteId||y.siteId;this.deployCount++;let F=`# HTML Project Deployed Successfully!
108
+ Replaced ${I} occurrence(s)`;return U.result({toolName:"Edit",filePath:u,output:_,success:!0,executionTime:y}),[{type:"text",text:D}]}catch(S){o.debug(`[EditFileTool] Failed to edit file: ${S.message}`);let w=`Error editing file: ${S.message}`,T=Date.now()-m;return U.result({toolName:"Edit",filePath:u,output:w,success:!1,executionTime:T}),[{type:"text",text:w}]}}}});var Rt,vn=M(()=>{"use strict";W();Rt=class{toolNames=["upload_file"];async execute(e,t,s,n){let i=s.file_path;if(!i)throw new Error("Missing file_path argument");return o.debug(`[UploadFileTool] Upload file not implemented for CLI: ${i}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${i}`}]}}});import Ts from"fs/promises";import to from"path";import so from"form-data";import no from"axios";var Ft,bn=M(()=>{"use strict";W();ke();ue();Ft=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let i=s.zip_file_path;if(!i)throw new Error("Missing zip_file_path argument");let r=Date.now();U.start("DeployZipHTML",s.description,i);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let g=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 ${g} seconds.`)}o.debug(`[DeployZipHTML] Deploying HTML project: ${i}`);try{await Ts.access(i)}catch{throw new Error(`ZIP file not found at path: ${i}`)}if(!i.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${i}`);let l=await Ts.stat(i),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await Ts.readFile(i),m=to.basename(i).replace(/[\r\n\t"']/g,"_");o.debug(`[DeployZipHTML] File: ${m}, Size: ${l.size} bytes`);let w=await X.getInstance().getFirebaseIdToken();if(!w)throw new Error("User must be authenticated to deploy projects");let T=new so;T.append("zipFile",d,{filename:m,contentType:"application/zip"});let I="https://snowx.ai/api/v2/deploy-zip";o.debug(`[DeployZipHTML] Uploading to ${I}`);let D=await no.post(I,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${w}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(D.status!==200&&D.status!==201)throw new Error(`Deployment failed with status ${D.status}: ${JSON.stringify(D.data)}`);let y=D.data;o.debug("[DeployZipHTML] Deployed successfully"),o.debug(`[DeployZipHTML] Response: ${JSON.stringify(y,null,2)}`);let A=y.data?.deployUrl||y.deployUrl||y.url||y.deploymentUrl||y.site_url||y.siteUrl||y.website_url,_=y.data?.deployId||y.deployId||y.projectId||y.deploymentId,P=y.data?.siteId||y.siteId;this.deployCount++;let F=`# HTML Project Deployed Successfully!
109
109
 
110
110
  **Deployment URL**: ${A}
111
111
 
@@ -127,7 +127,7 @@ Troubleshooting:
127
127
  4. Check network connectivity
128
128
  5. Ensure ZIP file is under 100MB
129
129
 
130
- If the issue persists, contact support.`,u=Date.now()-r;return U.result({toolName:"DeployZipHTML",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import ws from"fs/promises";import io from"path";import oo from"form-data";import ro from"axios";var Ot,yn=M(()=>{"use strict";W();ke();ue();Ot=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let i=s.zip_file_path;if(!i)throw new Error("Missing zip_file_path argument");let r=Date.now();U.start("DeployZipReact",s.description,i);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let g=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 ${g} seconds.`)}o.debug(`[DeployZipReact] Deploying React project: ${i}`);try{await ws.access(i)}catch{throw new Error(`ZIP file not found at path: ${i}`)}if(!i.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${i}`);let l=await ws.stat(i),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await ws.readFile(i),m=io.basename(i).replace(/[\r\n\t"']/g,"_");o.debug(`[DeployZipReact] File: ${m}, Size: ${l.size} bytes`);let w=await X.getInstance().getFirebaseIdToken();if(!w)throw new Error("User must be authenticated to deploy projects");let T=new oo;T.append("zipFile",d,{filename:m,contentType:"application/zip"});let I="https://snowx.ai/api/v2/deploy-zip-react";o.debug(`[DeployZipReact] Uploading to ${I}`);let D=await ro.post(I,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${w}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(D.status!==200&&D.status!==201)throw new Error(`Deployment failed with status ${D.status}: ${JSON.stringify(D.data)}`);let y=D.data;o.debug("[DeployZipReact] Deployed successfully"),o.debug(`[DeployZipReact] Response: ${JSON.stringify(y,null,2)}`);let A=y.data?.deployUrl||y.deployUrl||y.url||y.deploymentUrl||y.site_url||y.siteUrl||y.website_url,_=y.data?.deployId||y.deployId||y.projectId||y.deploymentId,P=y.data?.siteId||y.siteId;this.deployCount++;let F=`# React Project Deployed Successfully!
130
+ If the issue persists, contact support.`,u=Date.now()-r;return U.result({toolName:"DeployZipHTML",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import ys from"fs/promises";import io from"path";import oo from"form-data";import ro from"axios";var Ot,Tn=M(()=>{"use strict";W();ke();ue();Ot=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,s,n){let i=s.zip_file_path;if(!i)throw new Error("Missing zip_file_path argument");let r=Date.now();U.start("DeployZipReact",s.description,i);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let g=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 ${g} seconds.`)}o.debug(`[DeployZipReact] Deploying React project: ${i}`);try{await ys.access(i)}catch{throw new Error(`ZIP file not found at path: ${i}`)}if(!i.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${i}`);let l=await ys.stat(i),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await ys.readFile(i),m=io.basename(i).replace(/[\r\n\t"']/g,"_");o.debug(`[DeployZipReact] File: ${m}, Size: ${l.size} bytes`);let w=await X.getInstance().getFirebaseIdToken();if(!w)throw new Error("User must be authenticated to deploy projects");let T=new oo;T.append("zipFile",d,{filename:m,contentType:"application/zip"});let I="https://snowx.ai/api/v2/deploy-zip-react";o.debug(`[DeployZipReact] Uploading to ${I}`);let D=await ro.post(I,T,{headers:{...T.getHeaders(),Authorization:`Bearer ${w}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(D.status!==200&&D.status!==201)throw new Error(`Deployment failed with status ${D.status}: ${JSON.stringify(D.data)}`);let y=D.data;o.debug("[DeployZipReact] Deployed successfully"),o.debug(`[DeployZipReact] Response: ${JSON.stringify(y,null,2)}`);let A=y.data?.deployUrl||y.deployUrl||y.url||y.deploymentUrl||y.site_url||y.siteUrl||y.website_url,_=y.data?.deployId||y.deployId||y.projectId||y.deploymentId,P=y.data?.siteId||y.siteId;this.deployCount++;let F=`# React Project Deployed Successfully!
131
131
 
132
132
  **Deployment URL**: ${A}
133
133
 
@@ -149,8 +149,8 @@ Troubleshooting:
149
149
  4. Check network connectivity
150
150
  5. Ensure ZIP file is under 100MB
151
151
 
152
- If the issue persists, contact support.`,u=Date.now()-r;return U.result({toolName:"DeployZipReact",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var wn=M(()=>{"use strict"});function ao(c){let e=c.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),n=t[t.length-1].trim().split(/\s+/)[0]||"";return new Set(["head","tail","sed","awk","cut","wc","uniq","sort","grep","fgrep","egrep","rg","ag","tee","cat","tr","fold","fmt","nl","pr"]).has(n)}function pt(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(ao(c))return Te.pipedWithTerminator;if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("DOC")))return Te.extended;let s=["python","python3","python2","node ",`node
153
- `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let u of s)if(e.includes(u))return Te.extended;let n=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let u of n)if(e.includes(u))return Te.extended;return(c.match(/\n/g)||[]).length>5?Te.extended:new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","printf","env","printenv","basename","dirname","realpath","readlink","write-host","write-output","get-date","get-location","hostname.exe"]).has(t)?Te.instant:new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","stat","file","du","df","free","uptime","ps","touch","mkdir","rmdir","mv","cp","chmod","chown","ln","test","[","expr","dir","get-childitem","get-content","select-object","where-object","measure-object","sort-object","get-process","get-service"]).has(t)?c.length<100?Te.fast:Te.default:new Set(["make","cmake","npm","yarn","pnpm","pip","pip3","pipx","cargo","mvn","gradle","ant","docker","docker-compose","podman","git","rsync","scp","sftp","ssh","curl","wget","aria2c","find","locate","updatedb","mlocate","tar","zip","unzip","gzip","bzip2","xz","7z","brew","apt","apt-get","yum","dnf","pacman","apk","convert","ffmpeg","imagemagick","install-module","update-module","invoke-webrequest","start-job","invoke-command","enter-pssession","new-pssession","msiexec"]).has(t)?Te.extended:c.includes("|")?Te.default:c.length<30?Te.fast:Te.default}var Te,Ss=M(()=>{"use strict";wn();Te={instant:{activityTimeout:1e3,maxTimeout:3e3,initialTimeout:500,useActivityTimeout:!1},fast:{activityTimeout:2e3,maxTimeout:1e4,initialTimeout:2e3,useActivityTimeout:!1},default:{activityTimeout:15e3,maxTimeout:12e4,initialTimeout:1e4,useActivityTimeout:!0},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:3e4,useActivityTimeout:!0},pipedWithTerminator:{activityTimeout:5e3,maxTimeout:6e4,initialTimeout:1e4,useActivityTimeout:!0}}});import{spawn as co,exec as lo,execSync as uo}from"child_process";import{promisify as po}from"util";function ks(){return process.platform}function Ne(){return process.platform==="win32"}function ho(){return process.platform==="darwin"}function Je(c,e="SIGTERM"){if(c)try{if(Ne())try{uo(`taskkill /PID ${c} /T /F`,{timeout:5e3,stdio:"ignore"})}catch{}else try{process.kill(-c,e)}catch{try{process.kill(c,e)}catch{}}}catch(t){o.debug(`[killProcessTree] Failed for PID ${c}: ${t}`)}}function fo(c){let e=c.trim().toLowerCase();if(e.startsWith("sudo "))return{isPrivileged:!0,reason:"Direct sudo usage"};if(/(\||&&|;)\s*sudo\s+/.test(e))return{isPrivileged:!0,reason:"Sudo in command chain"};if(Ne()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let n=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(n)return{isPrivileged:!0,reason:`Privileged command: ${n.trim()}`};let r=[{pattern:/>\s*\/etc\//,desc:"Writing to /etc/"},{pattern:/>\s*\/usr\//,desc:"Writing to /usr/"},{pattern:/>\s*\/var\//,desc:"Writing to /var/"},{pattern:/>\s*\/opt\//,desc:"Writing to /opt/"},{pattern:/>\s*\/System\//,desc:"Writing to /System/ (macOS)"},{pattern:/tee\s+\/etc\//,desc:"Tee to /etc/"},{pattern:/tee\s+\/usr\//,desc:"Tee to /usr/"},{pattern:/tee\s+\/var\//,desc:"Tee to /var/"}].find(({pattern:a})=>a.test(e));return r?{isPrivileged:!0,reason:r.desc}:{isPrivileged:!1}}function Sn(){return Ne()?"PowerShell or Command Prompt":(ho(),"Terminal")}function vo(c,e){let t=Sn();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
152
+ If the issue persists, contact support.`,u=Date.now()-r;return U.result({toolName:"DeployZipReact",filePath:i,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var yn=M(()=>{"use strict"});function ao(c){let e=c.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),n=t[t.length-1].trim().split(/\s+/)[0]||"";return new Set(["head","tail","sed","awk","cut","wc","uniq","sort","grep","fgrep","egrep","rg","ag","tee","cat","tr","fold","fmt","nl","pr"]).has(n)}function pt(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(ao(c))return Te.pipedWithTerminator;if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("DOC")))return Te.extended;let s=["python","python3","python2","node ",`node
153
+ `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let u of s)if(e.includes(u))return Te.extended;let n=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let u of n)if(e.includes(u))return Te.extended;return(c.match(/\n/g)||[]).length>5?Te.extended:new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","printf","env","printenv","basename","dirname","realpath","readlink","write-host","write-output","get-date","get-location","hostname.exe"]).has(t)?Te.instant:new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","stat","file","du","df","free","uptime","ps","touch","mkdir","rmdir","mv","cp","chmod","chown","ln","test","[","expr","dir","get-childitem","get-content","select-object","where-object","measure-object","sort-object","get-process","get-service"]).has(t)?c.length<100?Te.fast:Te.default:new Set(["make","cmake","npm","yarn","pnpm","pip","pip3","pipx","cargo","mvn","gradle","ant","docker","docker-compose","podman","git","rsync","scp","sftp","ssh","curl","wget","aria2c","find","locate","updatedb","mlocate","tar","zip","unzip","gzip","bzip2","xz","7z","brew","apt","apt-get","yum","dnf","pacman","apk","convert","ffmpeg","imagemagick","install-module","update-module","invoke-webrequest","start-job","invoke-command","enter-pssession","new-pssession","msiexec"]).has(t)?Te.extended:c.includes("|")?Te.default:c.length<30?Te.fast:Te.default}var Te,ws=M(()=>{"use strict";yn();Te={instant:{activityTimeout:1e3,maxTimeout:3e3,initialTimeout:500,useActivityTimeout:!1},fast:{activityTimeout:2e3,maxTimeout:1e4,initialTimeout:2e3,useActivityTimeout:!1},default:{activityTimeout:15e3,maxTimeout:12e4,initialTimeout:1e4,useActivityTimeout:!0},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:3e4,useActivityTimeout:!0},pipedWithTerminator:{activityTimeout:5e3,maxTimeout:6e4,initialTimeout:1e4,useActivityTimeout:!0}}});import{spawn as co,exec as lo,execSync as uo}from"child_process";import{promisify as po}from"util";function Cs(){return process.platform}function Ne(){return process.platform==="win32"}function ho(){return process.platform==="darwin"}function Je(c,e="SIGTERM"){if(c)try{if(Ne())try{uo(`taskkill /PID ${c} /T /F`,{timeout:5e3,stdio:"ignore"})}catch{}else try{process.kill(-c,e)}catch{try{process.kill(c,e)}catch{}}}catch(t){o.debug(`[killProcessTree] Failed for PID ${c}: ${t}`)}}function fo(c){let e=c.trim().toLowerCase();if(e.startsWith("sudo "))return{isPrivileged:!0,reason:"Direct sudo usage"};if(/(\||&&|;)\s*sudo\s+/.test(e))return{isPrivileged:!0,reason:"Sudo in command chain"};if(Ne()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let n=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(n)return{isPrivileged:!0,reason:`Privileged command: ${n.trim()}`};let r=[{pattern:/>\s*\/etc\//,desc:"Writing to /etc/"},{pattern:/>\s*\/usr\//,desc:"Writing to /usr/"},{pattern:/>\s*\/var\//,desc:"Writing to /var/"},{pattern:/>\s*\/opt\//,desc:"Writing to /opt/"},{pattern:/>\s*\/System\//,desc:"Writing to /System/ (macOS)"},{pattern:/tee\s+\/etc\//,desc:"Tee to /etc/"},{pattern:/tee\s+\/usr\//,desc:"Tee to /usr/"},{pattern:/tee\s+\/var\//,desc:"Tee to /var/"}].find(({pattern:a})=>a.test(e));return r?{isPrivileged:!0,reason:r.desc}:{isPrivileged:!1}}function wn(){return Ne()?"PowerShell or Command Prompt":(ho(),"Terminal")}function vo(c,e){let t=wn();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
154
154
 
155
155
  Reason: ${e}
156
156
 
@@ -164,7 +164,7 @@ To run this command:
164
164
  2. Run the command manually: ${c}
165
165
  3. Enter your password when prompted
166
166
 
167
- Alternative: Break down the task into non-privileged commands if possible.`}function bo(c){let e=c.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:m}of n)if(e.startsWith(u)&&!d?.some(w=>e.startsWith(w)))return{isInteractive:!0,reason:m};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let u of a)if(e.startsWith(u))return{isInteractive:!0,reason:`${u} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let l=["git push","git pull","git fetch","git clone"];for(let u of l)e.startsWith(u);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function To(c,e){let t=Sn();return`This command requires interactive input and cannot run in the Bash tool.
167
+ Alternative: Break down the task into non-privileged commands if possible.`}function bo(c){let e=c.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:m}of n)if(e.startsWith(u)&&!d?.some(w=>e.startsWith(w)))return{isInteractive:!0,reason:m};if(["vim","vi","nano","emacs","pico","ed","less","more","most"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive editor/pager that requires a TTY`};if(["top","htop","btop","atop","iotop","nmon","glances"].includes(t))return{isInteractive:!0,reason:`${t} is an interactive monitor that requires a TTY`};if((t==="python"||t==="python3"||t==="node")&&e.includes(" -i"))return{isInteractive:!0,reason:`${t} -i starts an interactive REPL`};let a=["irb","pry","iex","erl","ghci","scala","sbt console"];for(let u of a)if(e.startsWith(u))return{isInteractive:!0,reason:`${u} is an interactive REPL`};if(t==="ssh"&&!e.includes("-o batchmode")&&!e.includes("-o passwordauthentication=no")&&!e.includes("-i ")&&!e.includes("-o identityfile"))return{isInteractive:!0,reason:"ssh may require interactive password input (use -o BatchMode=yes for non-interactive)"};if(t==="read"||e.includes("| read")||e.includes("; read"))return{isInteractive:!0,reason:"read command waits for user input"};if(t==="passwd")return{isInteractive:!0,reason:"passwd requires interactive password input"};let l=["git push","git pull","git fetch","git clone"];for(let u of l)e.startsWith(u);return t==="mysql"&&!e.includes("-p")&&!e.includes("--password")?{isInteractive:!0,reason:"mysql without -p flag may prompt for password"}:(t==="psql"&&!e.includes("PGPASSWORD")&&e.includes("--no-password"),{isInteractive:!1})}function To(c,e){let t=wn();return`This command requires interactive input and cannot run in the Bash tool.
168
168
 
169
169
  Reason: ${e}
170
170
 
@@ -194,7 +194,7 @@ The Bash tool will NEVER execute commands that could destroy your system.
194
194
  If you believe this is a false positive, please:
195
195
  1. Review the command carefully
196
196
  2. Run it manually in your terminal if you're certain it's safe
197
- 3. Consider breaking down the operation into safer steps`}function Cn(c){let e=wo(c);if(e.isCatastrophic)return So(c,e);let t=fo(c);if(t.isPrivileged)return vo(c,t.reason||"Privileged command detected");let s=bo(c);return s.isInteractive?To(c,s.reason||"Interactive command detected"):null}function kn(c){let e=c.trim();for(let t of Co)if(t.test(e))return{isDelete:!0,paths:ko(e),category:xo(e)};return{isDelete:!1,paths:[]}}function ko(c){let e=[],t=c.split(/\s+/),s=!1;for(let n=1;n<t.length;n++){let i=t[n];if(s){s=!1;continue}if(i.startsWith("-")){["-f","-o","-t","--target","--output"].includes(i)&&(s=!0);continue}i.length>0&&!i.startsWith("-")&&e.push(i)}return e}function xo(c){let e=c.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 mo,go,mt,Cs,re,gt,yo,Co,Ye=M(()=>{"use strict";Ss();Ke();W();mo=po(lo),go=8500,mt=new be({maxResponseTokens:go});Cs=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),o.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),o.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),o.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${s.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],s=Array.from(this.processes.entries());for(let r=0;r<s.length;r++){let[a,l]=s[r];l.status!=="running"&&l.endTime&&t.push({id:a,endTime:l.endTime.getTime()})}let n=0;for(let r=0;r<t.length;r++){let{id:a,endTime:l}=t[r];e-l>this.COMPLETED_PROCESS_TTL&&(this.processes.delete(a),n++)}n>0&&o.debug(`[BackgroundProcessManager] Cleaned up ${n} old processes by TTL`);let i=t.filter(r=>e-r.endTime<=this.COMPLETED_PROCESS_TTL);if(i.length>this.MAX_COMPLETED_PROCESSES){i.sort((a,l)=>a.endTime-l.endTime);let r=i.slice(0,i.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<r.length;a++){let{id:l}=r[a];this.processes.delete(l)}o.debug(`[BackgroundProcessManager] Cleaned up ${r.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let s=0;s<t.length;s++){let[n,i]=t[s];i.status!=="running"&&(this.processes.delete(n),e++)}return o.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(),o.debug("[BackgroundProcessManager] Cleared all processes")}},re=new Cs;gt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,s,n,i="new",r){let a=r||pt(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Ne())await mo(`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(),i=ks(),r,a;Ne()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=co(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Ne()}),u="",d="",m=!1,S="",w=!1,T=!1,I=Date.now(),D=null,y=null,A=null,_=null,P=null,F=null,H=()=>{D&&(clearTimeout(D),D=null),y&&(clearTimeout(y),y=null),A&&(clearTimeout(A),A=null),_&&(clearTimeout(_),_=null),P&&(clearTimeout(P),P=null),F&&(clearTimeout(F),F=null)},g=E=>{w||(w=!0,H(),s(E))},N=async E=>{w||(m=!0,S=E,y&&(clearTimeout(y),y=null),A&&(clearTimeout(A),A=null),l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),this.cleanupStreams(l),_=setTimeout(async()=>{w||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),P=setTimeout(()=>{if(w)return;let h=Date.now()-n;g({output:u+d+`
197
+ 3. Consider breaking down the operation into safer steps`}function Sn(c){let e=wo(c);if(e.isCatastrophic)return So(c,e);let t=fo(c);if(t.isPrivileged)return vo(c,t.reason||"Privileged command detected");let s=bo(c);return s.isInteractive?To(c,s.reason||"Interactive command detected"):null}function Cn(c){let e=c.trim();for(let t of Co)if(t.test(e))return{isDelete:!0,paths:ko(e),category:xo(e)};return{isDelete:!1,paths:[]}}function ko(c){let e=[],t=c.split(/\s+/),s=!1;for(let n=1;n<t.length;n++){let i=t[n];if(s){s=!1;continue}if(i.startsWith("-")){["-f","-o","-t","--target","--output"].includes(i)&&(s=!0);continue}i.length>0&&!i.startsWith("-")&&e.push(i)}return e}function xo(c){let e=c.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 mo,go,mt,Ss,re,gt,yo,Co,Ye=M(()=>{"use strict";ws();Ke();W();mo=po(lo),go=8500,mt=new be({maxResponseTokens:go});Ss=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),o.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),o.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),o.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${s.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],s=Array.from(this.processes.entries());for(let r=0;r<s.length;r++){let[a,l]=s[r];l.status!=="running"&&l.endTime&&t.push({id:a,endTime:l.endTime.getTime()})}let n=0;for(let r=0;r<t.length;r++){let{id:a,endTime:l}=t[r];e-l>this.COMPLETED_PROCESS_TTL&&(this.processes.delete(a),n++)}n>0&&o.debug(`[BackgroundProcessManager] Cleaned up ${n} old processes by TTL`);let i=t.filter(r=>e-r.endTime<=this.COMPLETED_PROCESS_TTL);if(i.length>this.MAX_COMPLETED_PROCESSES){i.sort((a,l)=>a.endTime-l.endTime);let r=i.slice(0,i.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<r.length;a++){let{id:l}=r[a];this.processes.delete(l)}o.debug(`[BackgroundProcessManager] Cleaned up ${r.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let s=0;s<t.length;s++){let[n,i]=t[s];i.status!=="running"&&(this.processes.delete(n),e++)}return o.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(),o.debug("[BackgroundProcessManager] Cleared all processes")}},re=new Ss;gt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,s,n,i="new",r){let a=r||pt(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(Ne())await mo(`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(),i=Cs(),r,a;Ne()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=co(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!Ne()}),u="",d="",m=!1,S="",w=!1,T=!1,I=Date.now(),D=null,y=null,A=null,_=null,P=null,F=null,H=()=>{D&&(clearTimeout(D),D=null),y&&(clearTimeout(y),y=null),A&&(clearTimeout(A),A=null),_&&(clearTimeout(_),_=null),P&&(clearTimeout(P),P=null),F&&(clearTimeout(F),F=null)},g=E=>{w||(w=!0,H(),s(E))},N=async E=>{w||(m=!0,S=E,y&&(clearTimeout(y),y=null),A&&(clearTimeout(A),A=null),l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),this.cleanupStreams(l),_=setTimeout(async()=>{w||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),P=setTimeout(()=>{if(w)return;let h=Date.now()-n;g({output:u+d+`
198
198
 
199
199
  ❌ Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:h,platform:i})},500))},1e3))};D=setTimeout(()=>{N(`Max timeout reached (${t.maxTimeout}ms)`)},t.maxTimeout),t.initialTimeout>0&&(A=setTimeout(()=>{!T&&!w&&N(`No output received within initial timeout (${t.initialTimeout}ms)`)},t.initialTimeout));let x=()=>{I=Date.now(),t.useActivityTimeout&&(y&&clearTimeout(y),y=setTimeout(()=>{if(!w){let E=Date.now()-I;N(`No output for ${E}ms (activity timeout: ${t.activityTimeout}ms)`)}},t.activityTimeout))};t.useActivityTimeout&&x(),l.stdout?.on("data",E=>{T=!0,x(),A&&(clearTimeout(A),A=null),u+=E.toString()}),l.stderr?.on("data",E=>{T=!0,x(),A&&(clearTimeout(A),A=null),d+=E.toString()}),l.on("exit",(E,h)=>{h&&!m&&(d+=`
200
200
  [Process terminated by signal: ${h}]`),F=setTimeout(()=>{if(w)return;H(),this.cleanupStreams(l);let v=Date.now()-n,C=(u+d).trim();if(mt.exceedsResponseLimit(C)){let b=mt.truncate(C),f=b.text.split(`
@@ -210,7 +210,7 @@ If you believe this is a false positive, please:
210
210
  [Showing first `+$+` lines of output]
211
211
  [Total output was `+C.toLocaleString()+" tokens]"}g(m?{output:v+`
212
212
 
213
- ❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:h,platform:i}:{output:v,exitCode:E||0,isSuccess:(E||0)===0,duration:h,platform:i})}),l.on("error",E=>{if(w)return;H();let h=Date.now()-n;g({output:"Process execution failed: "+E.message,exitCode:-1,isSuccess:!1,duration:h,platform:i})})})}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`)}};yo=[{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"}];Co=[/^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 xs={};Se(xs,{ToolCallingService:()=>ht});import{EventEmitter as Eo}from"events";import xn from"axios";import{exec as Io,spawn as En}from"child_process";import{promisify as Po}from"util";import oe from"fs/promises";import Ie from"fs";import Ze from"path";import Do from"os";var ll,ht,$t=M(()=>{"use strict";Ye();Ss();Ke();ll=Po(Io),ht=class _ToolCallingService extends Eo{static instance;tools=new Map;executionHistory=[];tokenCounter=new be;shellSessionManager=gt.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.
213
+ ❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:h,platform:i}:{output:v,exitCode:E||0,isSuccess:(E||0)===0,duration:h,platform:i})}),l.on("error",E=>{if(w)return;H();let h=Date.now()-n;g({output:"Process execution failed: "+E.message,exitCode:-1,isSuccess:!1,duration:h,platform:i})})})}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`)}};yo=[{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"}];Co=[/^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 ks={};Se(ks,{ToolCallingService:()=>ht});import{EventEmitter as Eo}from"events";import kn from"axios";import{exec as Io,spawn as xn}from"child_process";import{promisify as Po}from"util";import oe from"fs/promises";import Ie from"fs";import Ze from"path";import Do from"os";var cl,ht,$t=M(()=>{"use strict";Ye();ws();Ke();cl=Po(Io),ht=class _ToolCallingService extends Eo{static instance;tools=new Map;executionHistory=[];tokenCounter=new be;shellSessionManager=gt.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.
214
214
 
215
215
  🔧 SESSION MODE SELECTION (REQUIRED):
216
216
  • Use session: "existing" for workflows that need persistent state:
@@ -244,13 +244,13 @@ If you believe this is a false positive, please:
244
244
  4. LLM receives prompt details and makes decision
245
245
  5. LLM uses provide_input to send appropriate response
246
246
  6. Command execution continues with provided input
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(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let s={};try{s=JSON.parse(c.function.arguments)}catch(i){throw new Error(`Invalid arguments for tool '${t}': ${i}`)}let{ToolDisplay:n}=await Promise.resolve().then(()=>(ke(),dn));n.start(t,s.description,s.command||s.file_path);try{let i=this.tools.get(t);if(!i)throw new Error(`Tool '${t}' not found`);if(!i.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await i.handler(s),a=Date.now()-e,l=this.handleLargeResponse(r,t);return this.executionHistory.push({toolName:t,args:s,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),n.result({toolName:t,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(i){let r=Date.now()-e,a={success:!1,error:i.message};return this.emit("tool_execution_error",{toolName:t,error:i,executionTime:r}),n.error(t,i.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(()=>(Pe(),et)),s=t.getInstance(),n=this.extractOutputForDisplay(e);s.captureFrontendToolResult(c,n,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,s=(await xn.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 i of s.RelatedTopics.slice(0,c.num_results||5))i.Text&&n.push({title:i.Text.split(" - ")[0]||"Related Topic",content:i.Text,url:i.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:n,total_results:n.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await oe.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:s="write"}=c;if(e.endsWith(".ipynb")&&Ie.existsSync(e)){let i=await oe.readFile(e,"utf-8"),r=JSON.parse(i);if(r.cells.length>0&&r.cells[0].id){let a=r.cells.findIndex(l=>l.id===r.cells[0].id);if(a!==-1)return r.cells[a].source=t,await oe.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}Ie.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let n=Ze.dirname(e);return await oe.mkdir(n,{recursive:!0}),s==="append"?await oe.appendFile(e,t):await oe.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:s}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await oe.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let n=await oe.stat(Ze.join(c.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:n.size,modified:n.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=gt.parseSessionMode(c.session),t=pt(c.command),s={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},n=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,s);return{success:n.isSuccess,result:{command:c.command,stdout:n.output,stderr:"",exit_code:n.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await xn({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:s=!1}=c;if(s){this.backgroundProcessCounter++;let r=`bg-${this.backgroundProcessCounter}`,a=En("/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",d=>{let m=d.toString();if(m){let S=this.backgroundProcesses.get(r);S&&(S.stdout+=m,this.backgroundProcesses.set(r,S))}}),a.stderr.on("data",d=>{let m=d.toString();if(m){let S=this.backgroundProcesses.get(r);S&&(S.stderr+=m,this.backgroundProcesses.set(r,S))}}),a.on("close",d=>{let m=this.backgroundProcesses.get(r);m&&(m.exitCode=d||0,this.backgroundProcesses.set(r,m))}),this.backgroundProcesses.set(r,l);let u=`Command started in background with ID: ${r}
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(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let s={};try{s=JSON.parse(c.function.arguments)}catch(i){throw new Error(`Invalid arguments for tool '${t}': ${i}`)}let{ToolDisplay:n}=await Promise.resolve().then(()=>(ke(),un));n.start(t,s.description,s.command||s.file_path);try{let i=this.tools.get(t);if(!i)throw new Error(`Tool '${t}' not found`);if(!i.enabled)throw new Error(`Tool '${t}' is disabled`);let r=await i.handler(s),a=Date.now()-e,l=this.handleLargeResponse(r,t);return this.executionHistory.push({toolName:t,args:s,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),n.result({toolName:t,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(i){let r=Date.now()-e,a={success:!1,error:i.message};return this.emit("tool_execution_error",{toolName:t,error:i,executionTime:r}),n.error(t,i.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(()=>(Pe(),et)),s=t.getInstance(),n=this.extractOutputForDisplay(e);s.captureFrontendToolResult(c,n,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,s=(await kn.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 i of s.RelatedTopics.slice(0,c.num_results||5))i.Text&&n.push({title:i.Text.split(" - ")[0]||"Related Topic",content:i.Text,url:i.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:n,total_results:n.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await oe.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:s="write"}=c;if(e.endsWith(".ipynb")&&Ie.existsSync(e)){let i=await oe.readFile(e,"utf-8"),r=JSON.parse(i);if(r.cells.length>0&&r.cells[0].id){let a=r.cells.findIndex(l=>l.id===r.cells[0].id);if(a!==-1)return r.cells[a].source=t,await oe.writeFile(e,JSON.stringify(r,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}Ie.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let n=Ze.dirname(e);return await oe.mkdir(n,{recursive:!0}),s==="append"?await oe.appendFile(e,t):await oe.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:s}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await oe.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let n=await oe.stat(Ze.join(c.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:n.size,modified:n.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=gt.parseSessionMode(c.session),t=pt(c.command),s={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},n=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,s);return{success:n.isSuccess,result:{command:c.command,stdout:n.output,stderr:"",exit_code:n.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await kn({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:s=!1}=c;if(s){this.backgroundProcessCounter++;let r=`bg-${this.backgroundProcessCounter}`,a=xn("/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",d=>{let m=d.toString();if(m){let S=this.backgroundProcesses.get(r);S&&(S.stdout+=m,this.backgroundProcesses.set(r,S))}}),a.stderr.on("data",d=>{let m=d.toString();if(m){let S=this.backgroundProcesses.get(r);S&&(S.stderr+=m,this.backgroundProcesses.set(r,S))}}),a.on("close",d=>{let m=this.backgroundProcesses.get(r);m&&(m.exitCode=d||0,this.backgroundProcesses.set(r,m))}),this.backgroundProcesses.set(r,l);let u=`Command started in background with ID: ${r}
248
248
  PID: ${a.pid}
249
249
  Command: ${e}
250
250
 
251
251
  Note: The process will continue running in the background.
252
- Output will be collected automatically.`;return{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let n=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:pt(e),i=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",n);return{success:i.isSuccess,result:{command:e,stdout:i.output,stderr:"",exit_code:i.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(c){try{let{file_path:e,old_string:t,new_string:s,replace_all:n=!1}=c;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&Ie.existsSync(e)){let a=await oe.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let d=l.cells[u],m=Array.isArray(d.source)?d.source.join(""):d.source;if(m.includes(t)){let S=n?m.replaceAll(t,s):m.replace(t,s);return l.cells[u].source=S,await oe.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:n?m.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 i=await oe.readFile(e,"utf-8");if(!i.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let r=n?i.replaceAll(t,s):i.replace(t,s);if(r===i)throw new Error("Edit failed: File content unchanged after replacement");return await oe.writeFile(e,r,"utf-8"),this.cacheFileState(e,r),{success:!0,result:{file_path:e,replacements:n?i.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(c){try{let{pattern:e,path:t=process.cwd(),glob:s,output_mode:n="files_with_matches",case_insensitive:i=!1}=c,r=[];return i&&r.push("-i"),n==="files_with_matches"?r.push("-l"):n==="count"&&r.push("-c"),s&&r.push("--glob",s),r.push(e,t),new Promise(a=>{let l=En("rg",r,{stdio:["ignore","pipe","pipe"]}),u="",d="";l.stdout.on("data",m=>{u+=m.toString()}),l.stderr.on("data",m=>{d+=m.toString()}),l.on("close",m=>{if(m!==0&&m!==1){a({success:!1,error:`ripgrep failed: ${d||"Unknown error"}`});return}let S=u.trim().split(`
253
- `).filter(T=>T),w=S.length;a({success:!0,result:{pattern:e,num_files:w,files:S,output:u.trim()}})}),l.on("error",m=>{a({success:!1,error:`Failed to execute ripgrep: ${m.message}. Make sure ripgrep is installed.`})})})}catch(e){return{success:!1,error:`Grep failed: ${e.message}`}}}async globFiles(c){try{let{pattern:e,path:t=process.cwd()}=c,n=(a=>{let l=a;return l=l.replace(/[.+^${}()|[\]\\]/g,"\\$&"),l=l.replace(/\*\*/g,"<DOUBLESTAR>"),l=l.replace(/\*/g,"[^/]*"),l=l.replace(/<DOUBLESTAR>/g,".*"),l=l.replace(/\?/g,"."),new RegExp(`^${l}$`)})(e),i=[],r=async a=>{try{let l=await oe.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let d=Ze.join(a,u.name),m=Ze.relative(t,d);u.isDirectory()?await r(d):(n.test(m)||n.test(u.name))&&i.push(d)}}catch{}};return await r(t),{success:!0,result:{pattern:e,num_files:i.length,files:i}}}catch(e){return{success:!1,error:`Glob failed: ${e.message}`}}}async editNotebook(c){try{let{notebook_path:e,cell_id:t,new_source:s,cell_type:n="code",edit_mode:i="replace"}=c;if(!Ie.existsSync(e))throw new Error(`Notebook file does not exist: ${e}`);if(!e.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let r=await oe.readFile(e,"utf-8"),a=JSON.parse(r);switch(i){case"replace":{if(!t)throw new Error("cell_id is required for replace mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells[l].source=s;break}case"insert":{if(!n)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:n,source:s,metadata:{},execution_count:n==="code"?null:void 0,outputs:n==="code"?[]:void 0};if(t){let u=a.cells.findIndex(d=>d.id===t);a.cells.splice(u+1,0,l)}else a.cells.unshift(l);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${i}`)}return await oe.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:i,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=Ie.statSync(c);this.fileStateCache.set(c,{content:e,modificationDate:t.mtime,filePath:c})}catch{}}async validateFileNotModified(c){let e=this.fileStateCache.get(c);if(!e){if(Ie.existsSync(c)){let s=await oe.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(Ie.statSync(c).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let c=[];for(let[e,t]of this.tools.entries())t.enabled&&c.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return c}getToolsByCategory(c){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===c)}enableTool(c){let e=this.tools.get(c);return e?(e.enabled=!0,!0):!1}disableTool(c){let e=this.tools.get(c);return e?(e.enabled=!1,!0):!1}getExecutionHistory(c=10){return this.executionHistory.slice(-c)}getExecutionStats(){let c=this.executionHistory.length,e=this.executionHistory.filter(r=>r.result.success).length,t=c-e,s=c>0?this.executionHistory.reduce((r,a)=>r+a.executionTime,0)/c:0,n=new Map;this.executionHistory.forEach(r=>{n.set(r.toolName,(n.get(r.toolName)||0)+1)});let i=n.size>0?Array.from(n.entries()).reduce((r,a)=>a[1]>r[1]?a:r)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(s),mostUsed:i}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){}handleLargeResponse(c,e){if(!c.success||!c.result)return c;let t=typeof c.result=="string"?c.result:JSON.stringify(c.result);if(this.tokenCounter.exceedsResponseLimit(t)){let s=this.createTempFile(t,e);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(t,s)}:{success:!0,result:this.tokenCounter.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=Do.tmpdir(),s=Ze.join(t,"orion_tool_responses");Ie.existsSync(s)||Ie.mkdirSync(s,{recursive:!0});let n=Math.floor(Date.now()/1e3),i=Math.random().toString(36).substring(2,10),r=`${e}_${n}_${i}.txt`,a=Ze.join(s,r);return Ie.writeFileSync(a,c,"utf8"),a}catch{return null}}stopAllRunningTools(){}}});import{spawn as Ao}from"child_process";var _t,In=M(()=>{"use strict";W();Ye();_t=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,n){let i=s.command;if(i==null)throw new Error("Missing command argument");if(typeof i!="string")throw new Error(`Command must be a string. Received: ${typeof i}`);if(i.trim().length===0)throw new Error("Command cannot be empty");let r=s.session;if(r==null)r="new";else{if(typeof r!="string")throw new Error(`Session must be a string. Received: ${typeof r}`);r=r.toLowerCase()}if(r!=="new"&&r!=="existing")throw new Error(`Invalid session mode '${r}' - must be 'new' or 'existing'`);let a;if(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 l=s.description;l!=null&&typeof l!="string"&&o.debug(`[RunCommandTool] Invalid description type: ${typeof l}, 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=Cn(i);if(d)return o.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let m=kn(i);if(m.isDelete){o.debug("[RunCommandTool] Delete command detected, requesting confirmation"),o.debug(`[RunCommandTool] Affected targets: ${m.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(tt(),Es)),D=await T.getInstance().requestDeleteConfirmation(i,l);if(D==="declined")return o.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${i}
252
+ Output will be collected automatically.`;return{success:!0,result:{process_id:r,pid:a.pid,message:u}}}let n=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:pt(e),i=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",n);return{success:i.isSuccess,result:{command:e,stdout:i.output,stderr:"",exit_code:i.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(c){try{let{file_path:e,old_string:t,new_string:s,replace_all:n=!1}=c;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&Ie.existsSync(e)){let a=await oe.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let d=l.cells[u],m=Array.isArray(d.source)?d.source.join(""):d.source;if(m.includes(t)){let S=n?m.replaceAll(t,s):m.replace(t,s);return l.cells[u].source=S,await oe.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:n?m.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 i=await oe.readFile(e,"utf-8");if(!i.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let r=n?i.replaceAll(t,s):i.replace(t,s);if(r===i)throw new Error("Edit failed: File content unchanged after replacement");return await oe.writeFile(e,r,"utf-8"),this.cacheFileState(e,r),{success:!0,result:{file_path:e,replacements:n?i.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(c){try{let{pattern:e,path:t=process.cwd(),glob:s,output_mode:n="files_with_matches",case_insensitive:i=!1}=c,r=[];return i&&r.push("-i"),n==="files_with_matches"?r.push("-l"):n==="count"&&r.push("-c"),s&&r.push("--glob",s),r.push(e,t),new Promise(a=>{let l=xn("rg",r,{stdio:["ignore","pipe","pipe"]}),u="",d="";l.stdout.on("data",m=>{u+=m.toString()}),l.stderr.on("data",m=>{d+=m.toString()}),l.on("close",m=>{if(m!==0&&m!==1){a({success:!1,error:`ripgrep failed: ${d||"Unknown error"}`});return}let S=u.trim().split(`
253
+ `).filter(T=>T),w=S.length;a({success:!0,result:{pattern:e,num_files:w,files:S,output:u.trim()}})}),l.on("error",m=>{a({success:!1,error:`Failed to execute ripgrep: ${m.message}. Make sure ripgrep is installed.`})})})}catch(e){return{success:!1,error:`Grep failed: ${e.message}`}}}async globFiles(c){try{let{pattern:e,path:t=process.cwd()}=c,n=(a=>{let l=a;return l=l.replace(/[.+^${}()|[\]\\]/g,"\\$&"),l=l.replace(/\*\*/g,"<DOUBLESTAR>"),l=l.replace(/\*/g,"[^/]*"),l=l.replace(/<DOUBLESTAR>/g,".*"),l=l.replace(/\?/g,"."),new RegExp(`^${l}$`)})(e),i=[],r=async a=>{try{let l=await oe.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let d=Ze.join(a,u.name),m=Ze.relative(t,d);u.isDirectory()?await r(d):(n.test(m)||n.test(u.name))&&i.push(d)}}catch{}};return await r(t),{success:!0,result:{pattern:e,num_files:i.length,files:i}}}catch(e){return{success:!1,error:`Glob failed: ${e.message}`}}}async editNotebook(c){try{let{notebook_path:e,cell_id:t,new_source:s,cell_type:n="code",edit_mode:i="replace"}=c;if(!Ie.existsSync(e))throw new Error(`Notebook file does not exist: ${e}`);if(!e.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let r=await oe.readFile(e,"utf-8"),a=JSON.parse(r);switch(i){case"replace":{if(!t)throw new Error("cell_id is required for replace mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells[l].source=s;break}case"insert":{if(!n)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:n,source:s,metadata:{},execution_count:n==="code"?null:void 0,outputs:n==="code"?[]:void 0};if(t){let u=a.cells.findIndex(d=>d.id===t);a.cells.splice(u+1,0,l)}else a.cells.unshift(l);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${i}`)}return await oe.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:i,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=Ie.statSync(c);this.fileStateCache.set(c,{content:e,modificationDate:t.mtime,filePath:c})}catch{}}async validateFileNotModified(c){let e=this.fileStateCache.get(c);if(!e){if(Ie.existsSync(c)){let s=await oe.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(Ie.statSync(c).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let c=[];for(let[e,t]of this.tools.entries())t.enabled&&c.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return c}getToolsByCategory(c){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===c)}enableTool(c){let e=this.tools.get(c);return e?(e.enabled=!0,!0):!1}disableTool(c){let e=this.tools.get(c);return e?(e.enabled=!1,!0):!1}getExecutionHistory(c=10){return this.executionHistory.slice(-c)}getExecutionStats(){let c=this.executionHistory.length,e=this.executionHistory.filter(r=>r.result.success).length,t=c-e,s=c>0?this.executionHistory.reduce((r,a)=>r+a.executionTime,0)/c:0,n=new Map;this.executionHistory.forEach(r=>{n.set(r.toolName,(n.get(r.toolName)||0)+1)});let i=n.size>0?Array.from(n.entries()).reduce((r,a)=>a[1]>r[1]?a:r)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(s),mostUsed:i}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){}handleLargeResponse(c,e){if(!c.success||!c.result)return c;let t=typeof c.result=="string"?c.result:JSON.stringify(c.result);if(this.tokenCounter.exceedsResponseLimit(t)){let s=this.createTempFile(t,e);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(t,s)}:{success:!0,result:this.tokenCounter.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=Do.tmpdir(),s=Ze.join(t,"orion_tool_responses");Ie.existsSync(s)||Ie.mkdirSync(s,{recursive:!0});let n=Math.floor(Date.now()/1e3),i=Math.random().toString(36).substring(2,10),r=`${e}_${n}_${i}.txt`,a=Ze.join(s,r);return Ie.writeFileSync(a,c,"utf8"),a}catch{return null}}stopAllRunningTools(){}}});import{spawn as Ao}from"child_process";var _t,En=M(()=>{"use strict";W();Ye();_t=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,n){let i=s.command;if(i==null)throw new Error("Missing command argument");if(typeof i!="string")throw new Error(`Command must be a string. Received: ${typeof i}`);if(i.trim().length===0)throw new Error("Command cannot be empty");let r=s.session;if(r==null)r="new";else{if(typeof r!="string")throw new Error(`Session must be a string. Received: ${typeof r}`);r=r.toLowerCase()}if(r!=="new"&&r!=="existing")throw new Error(`Invalid session mode '${r}' - must be 'new' or 'existing'`);let a;if(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 l=s.description;l!=null&&typeof l!="string"&&o.debug(`[RunCommandTool] Invalid description type: ${typeof l}, 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=Sn(i);if(d)return o.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let m=Cn(i);if(m.isDelete){o.debug("[RunCommandTool] Delete command detected, requesting confirmation"),o.debug(`[RunCommandTool] Affected targets: ${m.paths.join(", ")}`);let{FrontendWebSocketService:T}=await Promise.resolve().then(()=>(tt(),xs)),D=await T.getInstance().requestDeleteConfirmation(i,l);if(D==="declined")return o.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${i}
254
254
 
255
255
  ALTERNATIVES (choose one):
256
256
  • Rename instead: mv [file] [file].old or mv [file] [file].legacy
@@ -271,7 +271,7 @@ IF CRITICAL (user explicitly asked to delete):
271
271
 
272
272
  DO NOT keep retrying the same delete command.`}];if(D==="error")return o.debug("[RunCommandTool] Delete confirmation failed"),[{type:"text",text:`Failed to show delete confirmation dialog. The command was NOT executed for safety.
273
273
 
274
- Please try again or ask the user to confirm the deletion manually.`}];o.debug("[RunCommandTool] User confirmed delete command, proceeding")}let S=a||12e4,w=ks();if(o.debug(`[RunCommandTool] Executing command on platform: ${w}`),o.debug(`[RunCommandTool] Command: ${i.substring(0,50)}${i.length>50?"...":""}`),l&&o.debug(`[RunCommandTool] Description: ${l}`),o.debug(`[RunCommandTool] Session: ${r}, Timeout: ${S}ms, Background: ${u}`),u)return this.executeBackground(e,i,S,n);try{let T=(await Promise.resolve().then(()=>($t(),xs))).ToolCallingService.getInstance(),I={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:i,session:r,timeout:S})}},D=await T.executeTool(I),y="";if(D.success){let A=(D.result?.stdout||"").trim(),_=D.result?.exitCode??0;if(y=`Command: ${i}
274
+ Please try again or ask the user to confirm the deletion manually.`}];o.debug("[RunCommandTool] User confirmed delete command, proceeding")}let S=a||12e4,w=Cs();if(o.debug(`[RunCommandTool] Executing command on platform: ${w}`),o.debug(`[RunCommandTool] Command: ${i.substring(0,50)}${i.length>50?"...":""}`),l&&o.debug(`[RunCommandTool] Description: ${l}`),o.debug(`[RunCommandTool] Session: ${r}, Timeout: ${S}ms, Background: ${u}`),u)return this.executeBackground(e,i,S,n);try{let T=(await Promise.resolve().then(()=>($t(),ks))).ToolCallingService.getInstance(),I={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:i,session:r,timeout:S})}},D=await T.executeTool(I),y="";if(D.success){let A=(D.result?.stdout||"").trim(),_=D.result?.exitCode??0;if(y=`Command: ${i}
275
275
  `,y+=`Exit Code: ${_}
276
276
 
277
277
  `,A.length>0){let P=A.split(`
@@ -302,7 +302,7 @@ If you expected output, the command may need different parameters or the operati
302
302
  Consider:
303
303
  • Checking the command syntax and parameters
304
304
  • Verifying file permissions and paths
305
- • Running the command with verbose flags for more details`:n}}});var Mt,Pn=M(()=>{"use strict";W();Ye();Mt=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,s,n){try{let i=s.bash_id||s.shell_id||s.task_id;if(!i)throw new Error("bash_id is required");if(typeof i!="string")throw new Error(`bash_id must be a string. Received: ${typeof i}`);o.debug(`[BashOutputTool] Retrieving output for process: ${i}`);let r=re.getProcess(i);if(!r)throw new Error(`Background process not found: ${i}`);let a=[...r.output,...r.error].join(""),l=r.status==="running",u=`Process ID: ${i}
305
+ • Running the command with verbose flags for more details`:n}}});var Mt,In=M(()=>{"use strict";W();Ye();Mt=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,s,n){try{let i=s.bash_id||s.shell_id||s.task_id;if(!i)throw new Error("bash_id is required");if(typeof i!="string")throw new Error(`bash_id must be a string. Received: ${typeof i}`);o.debug(`[BashOutputTool] Retrieving output for process: ${i}`);let r=re.getProcess(i);if(!r)throw new Error(`Background process not found: ${i}`);let a=[...r.output,...r.error].join(""),l=r.status==="running",u=`Process ID: ${i}
306
306
  `;if(u+=`Status: ${r.status}
307
307
  `,u+=`PID: ${r.pid||"N/A"}
308
308
  `,u+=`Command: ${r.command}
@@ -314,7 +314,7 @@ Consider:
314
314
  --- Output ---
315
315
  `,a?u+=a:l?u+="(no output yet - process still running)":r.exitCode===0?u+=`Process completed successfully with no output.
316
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(i){return o.debug(`[BashOutputTool] Error: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});var Lt,Dn=M(()=>{"use strict";W();Ye();Lt=class{toolNames=["kill_shell","KillShell"];async execute(e,t,s,n){try{let i=s.shell_id||s.bash_id||s.task_id;if(!i)throw new Error("shell_id is required");if(typeof i!="string")throw new Error(`shell_id must be a string. Received: ${typeof i}`);o.debug(`[KillShellTool] Killing process: ${i}`);let r=re.getProcess(i);if(!r)throw new Error(`Background process not found: ${i}`);if(r.status!=="running")throw new Error(`Process is not running (status: ${r.status})`);if(r.pid){Je(r.pid,"SIGTERM"),setTimeout(()=>{r.status==="running"&&Je(r.pid,"SIGKILL")},3e3),re.updateProcess(i,{status:"killed",endTime:new Date});let a=`Process ${i} (PID ${r.pid}) and its children killed successfully`;return o.debug(`[KillShellTool] ${a}`),[{type:"text",text:a}]}else throw new Error("Process has no PID")}catch(i){return o.debug(`[KillShellTool] Error: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});var Is,No,Ut,An=M(()=>{"use strict";W();Ye();Is=class c{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){o.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.instance}startMonitoring(e,t,s){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let n=re.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 i=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:i,onComplete:s}),o.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),o.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let s=re.getProcess(e);if(!s){this.stopMonitoring(e);return}s.status!=="running"&&(o.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(()=>(tt(),Es)),i=n.getInstance();if(!i.isConnected()){o.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let r,a=t.output.join(`
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(i){return o.debug(`[BashOutputTool] Error: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});var Lt,Pn=M(()=>{"use strict";W();Ye();Lt=class{toolNames=["kill_shell","KillShell"];async execute(e,t,s,n){try{let i=s.shell_id||s.bash_id||s.task_id;if(!i)throw new Error("shell_id is required");if(typeof i!="string")throw new Error(`shell_id must be a string. Received: ${typeof i}`);o.debug(`[KillShellTool] Killing process: ${i}`);let r=re.getProcess(i);if(!r)throw new Error(`Background process not found: ${i}`);if(r.status!=="running")throw new Error(`Process is not running (status: ${r.status})`);if(r.pid){Je(r.pid,"SIGTERM"),setTimeout(()=>{r.status==="running"&&Je(r.pid,"SIGKILL")},3e3),re.updateProcess(i,{status:"killed",endTime:new Date});let a=`Process ${i} (PID ${r.pid}) and its children killed successfully`;return o.debug(`[KillShellTool] ${a}`),[{type:"text",text:a}]}else throw new Error("Process has no PID")}catch(i){return o.debug(`[KillShellTool] Error: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});var Es,No,Ut,Dn=M(()=>{"use strict";W();Ye();Es=class c{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){o.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.instance}startMonitoring(e,t,s){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let n=re.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 i=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:i,onComplete:s}),o.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),o.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let s=re.getProcess(e);if(!s){this.stopMonitoring(e);return}s.status!=="running"&&(o.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(()=>(tt(),xs)),i=n.getInstance();if(!i.isConnected()){o.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let r,a=t.output.join(`
318
318
  `).substring(0,1e3),l=t.error.join(`
319
319
  `).substring(0,500);t.status==="completed"?r=`Background process completed successfully (ID: ${e}, Exit: ${t.exitCode}).
320
320
 
@@ -336,19 +336,19 @@ Reason for monitoring: ${s}
336
336
 
337
337
  The process was terminated. Please check if this was intentional or if there was a timeout.`:r=`Background process ended with status: ${t.status} (ID: ${e}).
338
338
 
339
- Reason for monitoring: ${s}`,i.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:s,message:r,timestamp:new Date().toISOString()}),o.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(n){o.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(),o.debug("[ProcessMonitoringService] Cleared all monitors")}},No=Is.getInstance(),Ut=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,s,n){let i=s.shell_id,r=s.reason;if(!i||typeof i!="string"||i.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!r||typeof r!="string"||r.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(r.length>500)return[{type:"text",text:`Error: reason is too long (${r.length} characters). Maximum 500 characters allowed.`}];o.debug(`[MonitorRunningCliTool] Starting monitoring for ${i}`),o.debug(`[MonitorRunningCliTool] Reason: ${r}`);let a=No.startMonitoring(i,r);return a.success?(o.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${i}.
339
+ Reason for monitoring: ${s}`,i.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:s,message:r,timestamp:new Date().toISOString()}),o.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(n){o.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(),o.debug("[ProcessMonitoringService] Cleared all monitors")}},No=Es.getInstance(),Ut=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,s,n){let i=s.shell_id,r=s.reason;if(!i||typeof i!="string"||i.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!r||typeof r!="string"||r.trim().length===0)return[{type:"text",text:"Error: reason is required and must be a non-empty string"}];if(r.length>500)return[{type:"text",text:`Error: reason is too long (${r.length} characters). Maximum 500 characters allowed.`}];o.debug(`[MonitorRunningCliTool] Starting monitoring for ${i}`),o.debug(`[MonitorRunningCliTool] Reason: ${r}`);let a=No.startMonitoring(i,r);return a.success?(o.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${i}.
340
340
 
341
341
  Reason: ${r}
342
342
 
343
343
  You will be auto-prompted when the process completes. You can continue with other tasks in the meantime.
344
344
 
345
- To check status manually, use BashOutput tool with shell_id: ${i}`}]):(o.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var Wt,Nn=M(()=>{"use strict";W();Wt=class{toolNames=["grep","Grep"];async execute(e,t,s,n){let i=s.pattern,r=s.output_mode||"files_with_matches",a=s.path||process.cwd(),l=s.glob,u=s.type,d=s["-i"]===!0,m=s["-n"]===!0,S=s["-A"],w=s["-B"],T=s["-C"],I=s.multiline===!0,D=s.head_limit;if(!i)throw new Error("Missing pattern argument");if(i.trim().length===0)throw new Error("Pattern cannot be empty");o.debug(`[GrepTool] Grep search: pattern="${i}", path="${a}", output_mode="${r}"`);try{let{exec:y}=await import("child_process"),{promisify:A}=await import("util"),_=A(y),P="rg",F=!0;try{await _("which rg")}catch{o.debug("[GrepTool] ripgrep not found, falling back to grep"),P="grep -r",F=!1}if(F){switch(d&&(P+=" -i"),m&&(P+=" -n"),r){case"files_with_matches":P+=" -l";break;case"count":P+=" -c";break;case"content":default:break}T!==void 0?P+=` -C ${T}`:(S!==void 0&&(P+=` -A ${S}`),w!==void 0&&(P+=` -B ${w}`)),I&&(P+=" -U --multiline-dotall"),P+=` "${i.replace(/"/g,'\\"')}"`,l&&(P+=` --glob="${l}"`),u&&(P+=` --type=${u}`),P+=` "${a}"`}else{switch(d&&(P+=" -i"),m&&(P+=" -n"),r){case"files_with_matches":P+=" -l";break;case"count":P+=" -c";break}T!==void 0?P+=` -C ${T}`:(S!==void 0&&(P+=` -A ${S}`),w!==void 0&&(P+=` -B ${w}`)),P+=` "${i.replace(/"/g,'\\"')}"`,l&&(P+=` --include="${l}"`),P+=` "${a}"`}D!==void 0&&D>0&&(P+=` | head -n ${D}`),o.debug(`[GrepTool] Executing: ${P}`);let{stdout:H,stderr:g}=await _(P,{maxBuffer:10*1024*1024});if(!H&&!g)return[{type:"text",text:"No matches found"}];let N=H||g;if(r==="content"&&N){let E=`
345
+ To check status manually, use BashOutput tool with shell_id: ${i}`}]):(o.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var Wt,An=M(()=>{"use strict";W();Wt=class{toolNames=["grep","Grep"];async execute(e,t,s,n){let i=s.pattern,r=s.output_mode||"files_with_matches",a=s.path||process.cwd(),l=s.glob,u=s.type,d=s["-i"]===!0,m=s["-n"]===!0,S=s["-A"],w=s["-B"],T=s["-C"],I=s.multiline===!0,D=s.head_limit;if(!i)throw new Error("Missing pattern argument");if(i.trim().length===0)throw new Error("Pattern cannot be empty");o.debug(`[GrepTool] Grep search: pattern="${i}", path="${a}", output_mode="${r}"`);try{let{exec:y}=await import("child_process"),{promisify:A}=await import("util"),_=A(y),P="rg",F=!0;try{await _("which rg")}catch{o.debug("[GrepTool] ripgrep not found, falling back to grep"),P="grep -r",F=!1}if(F){switch(d&&(P+=" -i"),m&&(P+=" -n"),r){case"files_with_matches":P+=" -l";break;case"count":P+=" -c";break;case"content":default:break}T!==void 0?P+=` -C ${T}`:(S!==void 0&&(P+=` -A ${S}`),w!==void 0&&(P+=` -B ${w}`)),I&&(P+=" -U --multiline-dotall"),P+=` "${i.replace(/"/g,'\\"')}"`,l&&(P+=` --glob="${l}"`),u&&(P+=` --type=${u}`),P+=` "${a}"`}else{switch(d&&(P+=" -i"),m&&(P+=" -n"),r){case"files_with_matches":P+=" -l";break;case"count":P+=" -c";break}T!==void 0?P+=` -C ${T}`:(S!==void 0&&(P+=` -A ${S}`),w!==void 0&&(P+=` -B ${w}`)),P+=` "${i.replace(/"/g,'\\"')}"`,l&&(P+=` --include="${l}"`),P+=` "${a}"`}D!==void 0&&D>0&&(P+=` | head -n ${D}`),o.debug(`[GrepTool] Executing: ${P}`);let{stdout:H,stderr:g}=await _(P,{maxBuffer:10*1024*1024});if(!H&&!g)return[{type:"text",text:"No matches found"}];let N=H||g;if(r==="content"&&N){let E=`
346
346
 
347
347
  [Found ${N.trim().split(`
348
- `).length} matching line(s)]`;return[{type:"text",text:N+E}]}return[{type:"text",text:N}]}catch(y){return y.code===1?[{type:"text",text:"No matches found"}]:(o.debug(`[GrepTool] Grep failed: ${y.message}`),y.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 Bt,Rn=M(()=>{"use strict";W();Bt=class{toolNames=["glob","Glob"];async execute(e,t,s,n){let i=s.pattern,r=s.path||process.cwd();if(!i)throw new Error("Missing pattern argument");o.debug(`[GlobTool] Glob search: pattern="${i}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),d=i.replace(/\*\*/g,"*"),m=process.platform==="win32"?`dir /s /b "${r}\\${d}"`:`find "${r}" -name "${d}" 2>/dev/null`,{stdout:S}=await u(m);if(!S||S.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let w=S.trim().split(`
348
+ `).length} matching line(s)]`;return[{type:"text",text:N+E}]}return[{type:"text",text:N}]}catch(y){return y.code===1?[{type:"text",text:"No matches found"}]:(o.debug(`[GrepTool] Grep failed: ${y.message}`),y.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 Bt,Nn=M(()=>{"use strict";W();Bt=class{toolNames=["glob","Glob"];async execute(e,t,s,n){let i=s.pattern,r=s.path||process.cwd();if(!i)throw new Error("Missing pattern argument");o.debug(`[GlobTool] Glob search: pattern="${i}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),d=i.replace(/\*\*/g,"*"),m=process.platform==="win32"?`dir /s /b "${r}\\${d}"`:`find "${r}" -name "${d}" 2>/dev/null`,{stdout:S}=await u(m);if(!S||S.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let w=S.trim().split(`
349
349
  `);return[{type:"text",text:`Found ${w.length} file(s):
350
350
  ${w.join(`
351
- `)}`}]}catch(a){return o.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Ht,Fn=M(()=>{"use strict";W();Ht=class{toolNames=["open_url"];async execute(e,t,s,n){let i=s.url;if(!i)throw new Error("Missing url argument");o.debug(`[OpenUrlTool] Opening URL: ${i}`),n.activeWebViewURLs.includes(i)||(n.activeWebViewURLs.push(i),o.debug(`[OpenUrlTool] Added to active URLs: ${i}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${i}"`,l=>{l?o.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):o.debug(`[OpenUrlTool] URL opened in default browser: ${i}`)}),[{type:"text",text:`✅ URL opened in default browser: ${i}`}]}catch(r){return o.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});import{exec as Ro,execSync as Ll}from"child_process";import{promisify as Fo}from"util";function st(){return process.platform==="win32"}function qt(){return process.platform==="darwin"}function zt(){return process.platform==="linux"}function Ps(){return st()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var Wl,On=M(()=>{"use strict";Wl=Fo(Ro)});import*as B from"fs";import*as ne from"path";import*as z from"os";import{exec as $n}from"child_process";import{promisify as Oo}from"util";var Gt,Ds,pe,_n=M(()=>{"use strict";On();Gt=Oo($n),Ds=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 ne.join(z.homedir(),".orion")}getKnowledgeFilePath(){return ne.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!B.existsSync(this.orionDirectory))try{B.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),st()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{$n(`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 B.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return B.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),B.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let s=(this.readDeviceKnowledge()||"")+`
351
+ `)}`}]}catch(a){return o.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Ht,Rn=M(()=>{"use strict";W();Ht=class{toolNames=["open_url"];async execute(e,t,s,n){let i=s.url;if(!i)throw new Error("Missing url argument");o.debug(`[OpenUrlTool] Opening URL: ${i}`),n.activeWebViewURLs.includes(i)||(n.activeWebViewURLs.push(i),o.debug(`[OpenUrlTool] Added to active URLs: ${i}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${i}"`,l=>{l?o.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):o.debug(`[OpenUrlTool] URL opened in default browser: ${i}`)}),[{type:"text",text:`✅ URL opened in default browser: ${i}`}]}catch(r){return o.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});import{exec as Ro,execSync as Ml}from"child_process";import{promisify as Fo}from"util";function st(){return process.platform==="win32"}function qt(){return process.platform==="darwin"}function zt(){return process.platform==="linux"}function Is(){return st()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var Ul,Fn=M(()=>{"use strict";Ul=Fo(Ro)});import*as B from"fs";import*as ne from"path";import*as z from"os";import{exec as On}from"child_process";import{promisify as Oo}from"util";var Gt,Ps,pe,$n=M(()=>{"use strict";Fn();Gt=Oo(On),Ps=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 ne.join(z.homedir(),".orion")}getKnowledgeFilePath(){return ne.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!B.existsSync(this.orionDirectory))try{B.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),st()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{On(`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 B.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return B.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),B.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let s=(this.readDeviceKnowledge()||"")+`
352
352
 
353
353
  `+e;return this.writeDeviceKnowledge(s)}getKnowledgeFileSize(){try{return B.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
354
354
 
@@ -364,7 +364,7 @@ ${w.join(`
364
364
  `,e+=`- **Username**: ${z.userInfo().username}
365
365
  `,e+=`- **Home Directory**: ${z.homedir()}
366
366
 
367
- `;let t=Ps();e+=`## Shell Environment
367
+ `;let t=Is();e+=`## Shell Environment
368
368
  `,e+=`- **Default Shell**: ${t}
369
369
  `,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
370
370
  `),e+=`
@@ -411,8 +411,8 @@ ${w.join(`
411
411
  ${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${s}`)){let a=r.split(`
412
412
  `),l=[],u=!1,d=!1;for(let S of a)S.startsWith(`## ${s}`)?(u=!0,l.push(S)):S.startsWith("## ")&&u&&!d?(l.push(""),l.push(i),l.push(""),l.push(S),u=!1,d=!0):l.push(S);u&&!d&&(l.push(""),l.push(i));let m=l.join(`
413
413
  `);return this.writeDeviceKnowledge(m)}else return this.updateKnowledgeSection(s,i)}deleteDeviceKnowledge(){try{return B.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return B.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=B.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(zt()){try{let{stdout:s}=await Gt("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),n=s.trim();n&&n!=="none"&&e.push(`- **Virtualization**: ${n}`)}catch{}if(B.existsSync("/proc/cpuinfo"))try{B.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(B.existsSync(s))try{let n=B.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(B.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),B.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),B.existsSync("/proc/version"))try{let s=B.readFileSync("/proc/version","utf8");(s.toLowerCase().includes("microsoft")||s.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(B.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),B.existsSync("/etc/os-release"))try{let n=B.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);n&&e.push(`- **Distribution**: ${n[1]}`)}catch{}}else if(qt())try{let{stdout:t}=await Gt('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(st())try{let{stdout:t}=await Gt('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=Ps(),{stdout:s,stderr:n}=await Gt(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]}},pe=Ds.shared()});var jt,Mn=M(()=>{"use strict";W();ke();_n();jt=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,n){let i=s.action,r=Date.now();o.debug(`[ManageDeviceKnowledgeTool] Executing action: ${i}`),U.start("ManageDeviceKnowledge",i);try{let a,l=!0;switch(i){case"read":{let d=pe.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await pe.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${pe.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let d=s.content;d?pe.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",l=!1):(a='Error: Missing "content" argument for write action.',l=!1);break}case"append":{let d=s.content;d?pe.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",l=!1):(a='Error: Missing "content" argument for append action.',l=!1);break}case"update_section":{let d=s.section,m=s.content;!d||!m?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):pe.updateKnowledgeSection(d,m)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,l=!1);break}case"add_note":{let d=s.title,m=s.content,S=s.category||"Notes";!d||!m?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):pe.addNote(d,m,S)?a=`Note "${d}" added to ${S} successfully.`:(a=`Failed to add note "${d}".`,l=!1);break}case"delete":{pe.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=pe.getKnowledgeFilePath();break}case"exists":{a=pe.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${pe.getKnowledgeFileSize()} bytes`;break}case"export":{let d=s.destination;d?pe.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,l=!1):(a='Error: Missing "destination" argument for export action.',l=!1);break}case"import":{let d=s.source;d?pe.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,l=!1):(a='Error: Missing "source" argument for import action.',l=!1);break}default:a=`Unknown action: ${i}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-r;return U.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){o.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-r;return U.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Xt,Ln=M(()=>{"use strict";W();Xt=class{toolNames=["operator_status"];async execute(e,t,s,n){let i=s.taskId,r=s.status,a=s.message;return o.debug(`[OperatorStatusTool] Operator status - Task ${i}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Vt,Un=M(()=>{"use strict";W();Vt=class{toolNames=["provide_input"];async execute(e,t,s,n){let i=s.input;if(!i)throw new Error("Missing input argument");o.debug(`[ProvideInputTool] Delegating provide_input to backend: ${i.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>($t(),xs))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:i})}},l=await r.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(r){return o.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});import{exec as $o}from"child_process";import{promisify as _o}from"util";import*as Kt from"fs/promises";import*as Wn from"path";import*as Bn from"os";var Mo,nt,As=M(()=>{"use strict";W();Mo=_o($o),nt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=Wn.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;
414
+ `):null}async getCommandVersion(e){try{let t=Is(),{stdout:s,stderr:n}=await Gt(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]}},pe=Ps.shared()});var jt,_n=M(()=>{"use strict";W();ke();$n();jt=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,n){let i=s.action,r=Date.now();o.debug(`[ManageDeviceKnowledgeTool] Executing action: ${i}`),U.start("ManageDeviceKnowledge",i);try{let a,l=!0;switch(i){case"read":{let d=pe.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await pe.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${pe.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let d=s.content;d?pe.writeDeviceKnowledge(d)?a="Device knowledge updated successfully.":(a="Failed to write device knowledge.",l=!1):(a='Error: Missing "content" argument for write action.',l=!1);break}case"append":{let d=s.content;d?pe.appendDeviceKnowledge(d)?a="Content appended to device knowledge successfully.":(a="Failed to append to device knowledge.",l=!1):(a='Error: Missing "content" argument for append action.',l=!1);break}case"update_section":{let d=s.section,m=s.content;!d||!m?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):pe.updateKnowledgeSection(d,m)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,l=!1);break}case"add_note":{let d=s.title,m=s.content,S=s.category||"Notes";!d||!m?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):pe.addNote(d,m,S)?a=`Note "${d}" added to ${S} successfully.`:(a=`Failed to add note "${d}".`,l=!1);break}case"delete":{pe.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=pe.getKnowledgeFilePath();break}case"exists":{a=pe.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${pe.getKnowledgeFileSize()} bytes`;break}case"export":{let d=s.destination;d?pe.exportDeviceKnowledge(d)?a=`Device knowledge exported to: ${d}`:(a=`Failed to export device knowledge to: ${d}`,l=!1):(a='Error: Missing "destination" argument for export action.',l=!1);break}case"import":{let d=s.source;d?pe.importDeviceKnowledge(d)?a=`Device knowledge imported from: ${d}`:(a=`Failed to import device knowledge from: ${d}`,l=!1):(a='Error: Missing "source" argument for import action.',l=!1);break}default:a=`Unknown action: ${i}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-r;return U.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){o.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-r;return U.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Xt,Mn=M(()=>{"use strict";W();Xt=class{toolNames=["operator_status"];async execute(e,t,s,n){let i=s.taskId,r=s.status,a=s.message;return o.debug(`[OperatorStatusTool] Operator status - Task ${i}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Vt,Ln=M(()=>{"use strict";W();Vt=class{toolNames=["provide_input"];async execute(e,t,s,n){let i=s.input;if(!i)throw new Error("Missing input argument");o.debug(`[ProvideInputTool] Delegating provide_input to backend: ${i.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>($t(),ks))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:i})}},l=await r.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(r){return o.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});import{exec as $o}from"child_process";import{promisify as _o}from"util";import*as Kt from"fs/promises";import*as Un from"path";import*as Wn from"os";var Mo,nt,Ds=M(()=>{"use strict";W();Mo=_o($o),nt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=Un.join(Wn.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;
416
416
  [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
417
417
  Start-Sleep -Milliseconds 100;
418
418
  $img = [System.Windows.Forms.Clipboard]::GetImage();
@@ -420,20 +420,20 @@ ${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${s}`)){let a=r.split(`
420
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
421
421
  `)):process.platform==="darwin"&&(console.log(`
422
422
  ⚠️ Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
423
- `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var Qt,Hn=M(()=>{"use strict";W();As();Qt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,s,n){o.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await nt.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return o.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(i){return o.error(`[TakeScreenshotTool] Failed to capture screenshot: ${i.message}`),[{type:"text",text:`Failed to capture screenshot: ${i.message}`}]}}}});function qn(c){c.register(new It),c.register(new Dt),c.register(new At),c.register(new Nt),c.register(new Rt),c.register(new Ft),c.register(new Ot),c.register(new _t),c.register(new Mt),c.register(new Lt),c.register(new Ut),c.register(new Wt),c.register(new Bt),c.register(new Ht),c.register(new jt),c.register(new Xt),c.register(new Vt),c.register(new Qt)}var zn=M(()=>{"use strict";gn();hn();fn();vn();bn();Tn();yn();In();Pn();Dn();An();Nn();Rn();Fn();Mn();Ln();Un();Hn()});var Jt,Gn=M(()=>{"use strict";Jt=class{constructor(e,t,s,n,i){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=n;this.activeWebViewURLs=i}}});var Es={};Se(Es,{FrontendWebSocketService:()=>ee});import{EventEmitter as Lo}from"events";import{io as Uo}from"socket.io-client";import jn from"os";import Wo from"path";var ee,tt=M(()=>{"use strict";W();_e();ue();Xe();Ke();fs();un();zn();Gn();ee=class c extends Lo{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 be;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=de.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new kt,qn(this.toolRegistry),o.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?o.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):o.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{o.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return o.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return o.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(o.debug("[FRONTEND WS] connectForConversation called"),o.debug(`[FRONTEND WS] New sessionId: ${t}`),o.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),o.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?(o.debug("[FRONTEND WS] Session ID changing but active work exists"),o.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),o.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),o.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(s)):(o.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)o.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${s}`),this.deviceId=s;else if(!s)return o.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(o.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){o.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],o.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){o.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(o.debug("[FRONTEND WS] connect() called"),this.socket?.connected){o.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(o.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),o.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}`;o.debug(`[FRONTEND WS] Connecting to ${t}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),o.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),o.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Uo(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){o.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){o.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,o.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&&(o.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),o.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:i=>{clearTimeout(n),this.connectionPromise=null,t(i)},reject:i=>{clearTimeout(n),this.connectionPromise=null,s(i)},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",()=>{o.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{o.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{o.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,o.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{o.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{o.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{o.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=>{o.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{o.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{o.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{o.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{o.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=>{o.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{o.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=>{o.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{o.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("get_image_for_annotation",e=>{o.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(){o.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.activeToolExecutions.size>0&&(o.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();o.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else o.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){o.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||o.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){o.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,s=t?.type||t?.stop_type||"all";switch(o.debug(`[FRONTEND WS] Stop type: ${s}`),s){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:o.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.session_id,s=e.reason||"backend_stop";if(o.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${s}`),t&&this.sessionId&&t!==this.sessionId){o.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(s)}stopAllActiveTools(e){o.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),o.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),o.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),o.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(o.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(o.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(o.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),o.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}handleCheckpointRequest(e){o.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,s=t.checkpoint_id,n=t.session_id,i=t.iteration;if(!s||!n||i===void 0){o.warn("[FRONTEND WS] Invalid checkpoint request format");return}o.debug(`[FRONTEND WS] Checkpoint request - ID: ${s}, Session: ${n}, Iteration: ${i}`);let r=Ce.getInstance(),a=r.getQueuedMessages(),l=a.map(d=>({content:d.content,timestamp:Math.floor(d.timestamp.getTime())})),u=l.length>0;o.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:s,session_id:n,has_feedback:u,feedback:l}),u&&(o.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,s=e.isNew;if(!t||s===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:s})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){o.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){o.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}o.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),o.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(o.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),o.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(s/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){o.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){o.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){o.debug("[FRONTEND WS] Initiating forced reconnection...");let n=this.sessionId,i=this.userId,r=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(i,n)?(o.debug("[FRONTEND WS] Reconnection successful!"),o.debug(`[FRONTEND WS] Composite key: ${r}_${n}`)):o.error("[FRONTEND WS] Reconnection failed")}catch(a){o.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else o.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:s}=e;o.debug(`[FRONTEND WS] Sub-agent event: ${t}`,s);try{ln.handleEvent({type:t,...s}),o.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(n){o.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;o.debug(`[FRONTEND WS] Processing image for annotation: ${s}`);try{let i=await import("fs/promises"),r=await import("path");try{await i.access(s)}catch{o.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 l=(await i.readFile(s)).toString("base64"),u=r.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,${l}`,mime_type:d,file_path:s}),o.debug(`[FRONTEND WS] Image sent for annotation: ${s}`)}catch(i){o.error(`[FRONTEND WS] Failed to read image for annotation: ${i.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${i.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&&(o.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){o.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();o.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(),o.debug("[FRONTEND WS] === EXECUTING TOOL ==="),o.debug(`[FRONTEND WS] Tool name: ${e.name}`),o.debug(`[FRONTEND WS] Tool ID: ${e.id}`),o.debug(`[FRONTEND WS] Tool call ID: ${t}`);let i=new Jt(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,i);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success}),await this.handleLargeResponse(e.id,t,e.name,r,r.success,s)}catch(r){o.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-n)/1e3).toFixed(2);o.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(o.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),o.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}o.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(s){o.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;o.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),o.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(s){o.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,i){this.updateKeepalive();let r;if(n&&typeof n=="object"&&"content"in n&&Array.isArray(n.content))r=n.content;else{let a;typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),r=this.createContentBlocks(a,i,s)}if(i){let a=this.createDeviceKnowledgeReminderBlock();r.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:r,success:!0,error:null})}sendToolError(e,t,s,n){let i=this.createContentBlocks(n.message,!1,s);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:i,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 Qt,Bn=M(()=>{"use strict";W();Ds();Qt=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,s,n){o.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await nt.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return o.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(i){return o.error(`[TakeScreenshotTool] Failed to capture screenshot: ${i.message}`),[{type:"text",text:`Failed to capture screenshot: ${i.message}`}]}}}});function Hn(c){c.register(new It),c.register(new Dt),c.register(new At),c.register(new Nt),c.register(new Rt),c.register(new Ft),c.register(new Ot),c.register(new _t),c.register(new Mt),c.register(new Lt),c.register(new Ut),c.register(new Wt),c.register(new Bt),c.register(new Ht),c.register(new jt),c.register(new Xt),c.register(new Vt),c.register(new Qt)}var qn=M(()=>{"use strict";mn();gn();hn();fn();vn();bn();Tn();En();In();Pn();Dn();An();Nn();Rn();_n();Mn();Ln();Bn()});var Jt,zn=M(()=>{"use strict";Jt=class{constructor(e,t,s,n,i){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=n;this.activeWebViewURLs=i}}});var xs={};Se(xs,{FrontendWebSocketService:()=>ee});import{EventEmitter as Lo}from"events";import{io as Uo}from"socket.io-client";import Gn from"os";import Wo from"path";var ee,tt=M(()=>{"use strict";W();_e();ue();Xe();Ke();hs();ln();qn();zn();ee=class c extends Lo{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 be;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=de.getInstance(),this.authService=X.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new kt,Hn(this.toolRegistry),o.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?o.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):o.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{o.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return o.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return o.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(o.debug("[FRONTEND WS] connectForConversation called"),o.debug(`[FRONTEND WS] New sessionId: ${t}`),o.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),o.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?(o.debug("[FRONTEND WS] Session ID changing but active work exists"),o.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),o.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),o.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(s)):(o.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)o.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${s}`),this.deviceId=s;else if(!s)return o.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(o.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){o.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],o.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){o.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(o.debug("[FRONTEND WS] connect() called"),this.socket?.connected){o.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(o.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),o.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}`;o.debug(`[FRONTEND WS] Connecting to ${t}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),o.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),o.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Uo(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){o.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){o.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,o.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&&(o.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),o.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:i=>{clearTimeout(n),this.connectionPromise=null,t(i)},reject:i=>{clearTimeout(n),this.connectionPromise=null,s(i)},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",()=>{o.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{o.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{o.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,o.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{o.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{o.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{o.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=>{o.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{o.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{o.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{o.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{o.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=>{o.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{o.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=>{o.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{o.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("get_image_for_annotation",e=>{o.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(){o.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.activeToolExecutions.size>0&&(o.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();o.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else o.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){o.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||o.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){o.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,s=t?.type||t?.stop_type||"all";switch(o.debug(`[FRONTEND WS] Stop type: ${s}`),s){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:o.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.session_id,s=e.reason||"backend_stop";if(o.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${s}`),t&&this.sessionId&&t!==this.sessionId){o.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(s)}stopAllActiveTools(e){o.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),o.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),o.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),o.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(o.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(o.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(o.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),o.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}handleCheckpointRequest(e){o.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,s=t.checkpoint_id,n=t.session_id,i=t.iteration;if(!s||!n||i===void 0){o.warn("[FRONTEND WS] Invalid checkpoint request format");return}o.debug(`[FRONTEND WS] Checkpoint request - ID: ${s}, Session: ${n}, Iteration: ${i}`);let r=Ce.getInstance(),a=r.getQueuedMessages(),l=a.map(d=>({content:d.content,timestamp:Math.floor(d.timestamp.getTime())})),u=l.length>0;o.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:s,session_id:n,has_feedback:u,feedback:l}),u&&(o.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,s=e.isNew;if(!t||s===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:s})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){o.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){o.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}o.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),o.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(o.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),o.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(s/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){o.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){o.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){o.debug("[FRONTEND WS] Initiating forced reconnection...");let n=this.sessionId,i=this.userId,r=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(i,n)?(o.debug("[FRONTEND WS] Reconnection successful!"),o.debug(`[FRONTEND WS] Composite key: ${r}_${n}`)):o.error("[FRONTEND WS] Reconnection failed")}catch(a){o.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else o.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:s}=e;o.debug(`[FRONTEND WS] Sub-agent event: ${t}`,s);try{cn.handleEvent({type:t,...s}),o.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(n){o.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;o.debug(`[FRONTEND WS] Processing image for annotation: ${s}`);try{let i=await import("fs/promises"),r=await import("path");try{await i.access(s)}catch{o.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 l=(await i.readFile(s)).toString("base64"),u=r.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,${l}`,mime_type:d,file_path:s}),o.debug(`[FRONTEND WS] Image sent for annotation: ${s}`)}catch(i){o.error(`[FRONTEND WS] Failed to read image for annotation: ${i.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${i.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&&(o.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){o.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();o.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(),o.debug("[FRONTEND WS] === EXECUTING TOOL ==="),o.debug(`[FRONTEND WS] Tool name: ${e.name}`),o.debug(`[FRONTEND WS] Tool ID: ${e.id}`),o.debug(`[FRONTEND WS] Tool call ID: ${t}`);let i=new Jt(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let r=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,i);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.output,success:r.success}),await this.handleLargeResponse(e.id,t,e.name,r,r.success,s)}catch(r){o.error(`[FRONTEND WS] Tool execution failed: ${r.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:r.message,success:!1,error:r.message}),this.sendToolError(e.id,t,e.name,r)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let r=((Date.now()-n)/1e3).toFixed(2);o.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${r}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(o.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),o.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}o.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(s){o.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;o.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),o.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(s){o.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,i){this.updateKeepalive();let r;if(n&&typeof n=="object"&&"content"in n&&Array.isArray(n.content))r=n.content;else{let a;typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),r=this.createContentBlocks(a,i,s)}if(i){let a=this.createDeviceKnowledgeReminderBlock();r.push(a)}this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:r,success:!0,error:null})}sendToolError(e,t,s,n){let i=this.createContentBlocks(n.message,!1,s);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:s,content:i,success:!0,error:null})}createDeviceKnowledgeReminderBlock(){return{type:"text",text:`
424
424
 
425
- UPDATE DEVICE KNOWLEDGE: ${Wo.join(jn.homedir(),".orion","device-knowledge.md")}
425
+ UPDATE DEVICE KNOWLEDGE: ${Wo.join(Gn.homedir(),".orion","device-knowledge.md")}
426
426
  Skip only if trivial. Update if you: discovered paths/configs/tools, completed significant tasks, or learned device-specific details.
427
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.
428
428
 
429
- No output was produced, which may be expected for this operation.`:n=`Command '${s}' failed but no error message was provided.`);try{let i=JSON.parse(n);if(Array.isArray(i)){let r=[];for(let a of i)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?r.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&r.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(r.length>0)return r}}catch{}return[{type:"text",text:n}]}async handleLargeResponse(e,t,s,n,i,r){let a;if(typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),s==="take_screenshot"||s==="take_current_screenshot"){await this.sendToolResult(e,t,s,n,i);return}if(["read","read_special_file","read_file","readspecialfile"].includes(s.toLowerCase())&&n?.metadata?.isImage===!0){o.debug(`[FRONTEND WS] Image file detected from ${s} tool, bypassing token limit`),await this.sendToolResult(e,t,s,n,i);return}if(this.tokenCounter.exceedsResponseLimit(a)){let u=this.tokenCounter.count(a);if(o.debug(`[FRONTEND WS] Response too large (${u} tokens), creating temp file`),s.toLowerCase()==="read"&&r?.file_path){let w=r.file_path,T=this.tokenCounter.formatLargeFileMessage(a,w);await this.sendToolResult(e,t,s,T,i);return}let m=await this.createTempFile(a,s);if(!m){o.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,s,this.tokenCounter.truncateOutput(a),i);return}let S=this.tokenCounter.formatLargeResponsePreview(a,m);await this.sendToolResult(e,t,s,S,i)}else await this.sendToolResult(e,t,s,a,i)}async createTempFile(e,t){try{let s=await import("fs/promises"),n=await import("path"),i=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${i}_${r}.txt`,l=jn.homedir(),u=n.join(l,".orion","tool_outputs");await s.mkdir(u,{recursive:!0});let d=n.join(u,a);return await s.writeFile(d,e,"utf-8"),o.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(s){return o.error(`[FRONTEND WS] Failed to create temp file: ${s}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),o.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),o.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),o.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}),o.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),o.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),o.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()});o.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();o.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(o.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),o.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){o.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(o.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}terminateAllRunningProcesses(){o.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),o.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(s){o.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){o.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()}),o.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){o.debug("[FRONTEND WS] Not connected, cannot register session");return}o.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),o.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw o.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};o.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return o.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let s=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return o.debug(`[FRONTEND WS] Requesting delete confirmation: ${s}`),o.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(n=>{let i=setTimeout(()=>{this.pendingDeleteConfirmations.get(s)&&(o.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:i}),this.socket?.emit("delete_confirmation_request",{confirmationId:s,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),o.debug(`[FRONTEND WS] Delete confirmation request sent: ${s}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:s}=e;o.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${s}`);let n=this.pendingDeleteConfirmations.get(t);if(!n){o.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(n.timeoutId),this.pendingDeleteConfirmations.delete(t);let i=s;n.resolve(["confirmed","declined","timeout","error"].includes(s)?i:"error")}async captureFrontendToolResultForHistory(e,t,s,n){let i=t.map(r=>r.text||"").join(`
430
- `);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(Pe(),et)),a=r.getInstance(),l=n?`Error: ${n}`:i;a.captureFrontendToolResult(e,l,s),o.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){o.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}scheduleOldSessionCleanup(e){let n=Date.now(),i=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){o.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-n>6e4){o.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(o.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(i,2e3)};o.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(i,2e3)}forceCleanup(){if(o.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}o.debug("[FRONTEND WS] Force cleanup complete")}destroy(){o.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Le,Xn=M(()=>{"use strict";Le=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 i=e;if(e.includes("<context>")&&(i=i.replace(this.contextRegex,"")),e.includes("<agent_system_reminder>")&&(i=i.replace(this.agentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(i=i.replace(this.systemReminderRegex,"")),i=i.replace(this.multipleNewlinesRegex,`
429
+ No output was produced, which may be expected for this operation.`:n=`Command '${s}' failed but no error message was provided.`);try{let i=JSON.parse(n);if(Array.isArray(i)){let r=[];for(let a of i)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?r.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&r.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(r.length>0)return r}}catch{}return[{type:"text",text:n}]}async handleLargeResponse(e,t,s,n,i,r){let a;if(typeof n=="string"?a=n:n&&typeof n=="object"&&"output"in n?a=n.output||n.error||"":a=JSON.stringify(n),s==="take_screenshot"||s==="take_current_screenshot"){await this.sendToolResult(e,t,s,n,i);return}if(["read","read_special_file","read_file","readspecialfile"].includes(s.toLowerCase())&&n?.metadata?.isImage===!0){o.debug(`[FRONTEND WS] Image file detected from ${s} tool, bypassing token limit`),await this.sendToolResult(e,t,s,n,i);return}if(this.tokenCounter.exceedsResponseLimit(a)){let u=this.tokenCounter.count(a);if(o.debug(`[FRONTEND WS] Response too large (${u} tokens), creating temp file`),s.toLowerCase()==="read"&&r?.file_path){let w=r.file_path,T=this.tokenCounter.formatLargeFileMessage(a,w);await this.sendToolResult(e,t,s,T,i);return}let m=await this.createTempFile(a,s);if(!m){o.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,s,this.tokenCounter.truncateOutput(a),i);return}let S=this.tokenCounter.formatLargeResponsePreview(a,m);await this.sendToolResult(e,t,s,S,i)}else await this.sendToolResult(e,t,s,a,i)}async createTempFile(e,t){try{let s=await import("fs/promises"),n=await import("path"),i=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${i}_${r}.txt`,l=Gn.homedir(),u=n.join(l,".orion","tool_outputs");await s.mkdir(u,{recursive:!0});let d=n.join(u,a);return await s.writeFile(d,e,"utf-8"),o.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(s){return o.error(`[FRONTEND WS] Failed to create temp file: ${s}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),o.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),o.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),o.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}),o.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),o.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),o.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()});o.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();o.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(o.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),o.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){o.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(o.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}terminateAllRunningProcesses(){o.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),o.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(s){o.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){o.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()}),o.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){o.debug("[FRONTEND WS] Not connected, cannot register session");return}o.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),o.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw o.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};o.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return o.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let s=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return o.debug(`[FRONTEND WS] Requesting delete confirmation: ${s}`),o.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(n=>{let i=setTimeout(()=>{this.pendingDeleteConfirmations.get(s)&&(o.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:i}),this.socket?.emit("delete_confirmation_request",{confirmationId:s,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),o.debug(`[FRONTEND WS] Delete confirmation request sent: ${s}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:s}=e;o.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${s}`);let n=this.pendingDeleteConfirmations.get(t);if(!n){o.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(n.timeoutId),this.pendingDeleteConfirmations.delete(t);let i=s;n.resolve(["confirmed","declined","timeout","error"].includes(s)?i:"error")}async captureFrontendToolResultForHistory(e,t,s,n){let i=t.map(r=>r.text||"").join(`
430
+ `);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(Pe(),et)),a=r.getInstance(),l=n?`Error: ${n}`:i;a.captureFrontendToolResult(e,l,s),o.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){o.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}scheduleOldSessionCleanup(e){let n=Date.now(),i=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){o.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-n>6e4){o.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(o.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(i,2e3)};o.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(i,2e3)}forceCleanup(){if(o.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}o.debug("[FRONTEND WS] Force cleanup complete")}destroy(){o.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Le,jn=M(()=>{"use strict";Le=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 i=e;if(e.includes("<context>")&&(i=i.replace(this.contextRegex,"")),e.includes("<agent_system_reminder>")&&(i=i.replace(this.agentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(i=i.replace(this.systemReminderRegex,"")),i=i.replace(this.multipleNewlinesRegex,`
431
431
 
432
- `),i=i.trim(),this.cache.size>=this.MAX_CACHE_SIZE){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}return this.cache.set(s,i),this.lastInput=e,this.lastOutput=i,i}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Bo}from"events";import{promises as Yt}from"fs";import{join as Vn}from"path";import{homedir as Ho}from"os";var Ns,Zt,Rs=M(()=>{"use strict";Ns=class c extends Bo{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=Vn(Ho(),".orion-cli"),this.configPath=Vn(this.configDir,"settings.json"),this.settings={isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},this.loadSettings()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async loadSettings(){try{await Yt.mkdir(this.configDir,{recursive:!0});try{let e=await Yt.readFile(this.configPath,"utf-8"),t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified))}catch{await this.saveSettings()}}catch(e){console.warn("⚠️ Failed to load settings:",e)}this.emit("settingsLoaded",this.settings)}async saveSettings(){try{await Yt.mkdir(this.configDir,{recursive:!0}),await Yt.writeFile(this.configPath,JSON.stringify(this.settings,null,2)),this.emit("settingsSaved",this.settings)}catch(e){throw console.error("❌ Failed to save settings:",e),e}}async setWorkingDirectory(e){this.settings.currentWorkingDirectory=e,await this.saveSettings(),this.emit("workingDirectoryChanged",e)}getWorkingDirectory(){return this.settings.currentWorkingDirectory}async setPrivacyMode(e){this.settings.isPrivacyModeEnabled=e,await this.saveSettings(),this.emit("privacyModeChanged",e)}isPrivacyModeEnabled(){return this.settings.isPrivacyModeEnabled}async setDefaultModel(e){this.settings.defaultModel=e,await this.saveSettings(),this.emit("defaultModelChanged",e)}getDefaultModel(){return this.settings.defaultModel}async setTemperature(e){this.settings.temperature=Math.max(0,Math.min(2,e)),await this.saveSettings(),this.emit("temperatureChanged",this.settings.temperature)}getTemperature(){return this.settings.temperature}async setMarkdownFormatting(e){this.settings.enableMarkdownFormatting=e,await this.saveSettings(),this.emit("markdownFormattingChanged",e)}async setShowThinkingBlocks(e){this.settings.showThinkingBlocks=e,await this.saveSettings(),this.emit("thinkingBlocksChanged",e)}async setCompactMode(e){this.settings.compactMode=e,await this.saveSettings(),this.emit("compactModeChanged",e)}async setEnableColors(e){this.settings.enableColors=e,await this.saveSettings(),this.emit("colorsChanged",e)}async setEnableToolCalling(e){this.settings.enableToolCalling=e,await this.saveSettings(),this.emit("toolCallingChanged",e)}async setEnableCrossDevice(e){this.settings.enableCrossDevice=e,await this.saveSettings(),this.emit("crossDeviceChanged",e)}async setEnableWebSocket(e){this.settings.enableWebSocket=e,await this.saveSettings(),this.emit("webSocketChanged",e)}async setEnableFirebase(e){this.settings.enableFirebase=e,await this.saveSettings(),this.emit("firebaseChanged",e)}async updateCustomUserPreferences(e){this.settings.customUserPreferences={...this.settings.customUserPreferences,...e,lastModified:new Date},await this.saveSettings(),this.emit("customPreferencesChanged",this.settings.customUserPreferences)}getFormattedCustomPreferences(){let e=this.settings.customUserPreferences;return!e.isEnabled||!e.instructions.trim()?"":`
432
+ `),i=i.trim(),this.cache.size>=this.MAX_CACHE_SIZE){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}return this.cache.set(s,i),this.lastInput=e,this.lastOutput=i,i}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Bo}from"events";import{promises as Yt}from"fs";import{join as Xn}from"path";import{homedir as Ho}from"os";var As,Zt,Ns=M(()=>{"use strict";As=class c extends Bo{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=Xn(Ho(),".orion-cli"),this.configPath=Xn(this.configDir,"settings.json"),this.settings={isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},this.loadSettings()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async loadSettings(){try{await Yt.mkdir(this.configDir,{recursive:!0});try{let e=await Yt.readFile(this.configPath,"utf-8"),t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified))}catch{await this.saveSettings()}}catch(e){console.warn("⚠️ Failed to load settings:",e)}this.emit("settingsLoaded",this.settings)}async saveSettings(){try{await Yt.mkdir(this.configDir,{recursive:!0}),await Yt.writeFile(this.configPath,JSON.stringify(this.settings,null,2)),this.emit("settingsSaved",this.settings)}catch(e){throw console.error("❌ Failed to save settings:",e),e}}async setWorkingDirectory(e){this.settings.currentWorkingDirectory=e,await this.saveSettings(),this.emit("workingDirectoryChanged",e)}getWorkingDirectory(){return this.settings.currentWorkingDirectory}async setPrivacyMode(e){this.settings.isPrivacyModeEnabled=e,await this.saveSettings(),this.emit("privacyModeChanged",e)}isPrivacyModeEnabled(){return this.settings.isPrivacyModeEnabled}async setDefaultModel(e){this.settings.defaultModel=e,await this.saveSettings(),this.emit("defaultModelChanged",e)}getDefaultModel(){return this.settings.defaultModel}async setTemperature(e){this.settings.temperature=Math.max(0,Math.min(2,e)),await this.saveSettings(),this.emit("temperatureChanged",this.settings.temperature)}getTemperature(){return this.settings.temperature}async setMarkdownFormatting(e){this.settings.enableMarkdownFormatting=e,await this.saveSettings(),this.emit("markdownFormattingChanged",e)}async setShowThinkingBlocks(e){this.settings.showThinkingBlocks=e,await this.saveSettings(),this.emit("thinkingBlocksChanged",e)}async setCompactMode(e){this.settings.compactMode=e,await this.saveSettings(),this.emit("compactModeChanged",e)}async setEnableColors(e){this.settings.enableColors=e,await this.saveSettings(),this.emit("colorsChanged",e)}async setEnableToolCalling(e){this.settings.enableToolCalling=e,await this.saveSettings(),this.emit("toolCallingChanged",e)}async setEnableCrossDevice(e){this.settings.enableCrossDevice=e,await this.saveSettings(),this.emit("crossDeviceChanged",e)}async setEnableWebSocket(e){this.settings.enableWebSocket=e,await this.saveSettings(),this.emit("webSocketChanged",e)}async setEnableFirebase(e){this.settings.enableFirebase=e,await this.saveSettings(),this.emit("firebaseChanged",e)}async updateCustomUserPreferences(e){this.settings.customUserPreferences={...this.settings.customUserPreferences,...e,lastModified:new Date},await this.saveSettings(),this.emit("customPreferencesChanged",this.settings.customUserPreferences)}getFormattedCustomPreferences(){let e=this.settings.customUserPreferences;return!e.isEnabled||!e.instructions.trim()?"":`
433
433
  --- User Instructions ---
434
434
  ${e.instructions}
435
435
  --- End Instructions ---
436
- `}getCustomPreferencesSummary(){let e=this.settings.customUserPreferences;if(!e.instructions.trim())return"No instructions set";let t=e.instructions.trim().split(/\s+/).length;return t<=10?e.instructions.trim():`${t} words of custom instructions`}async setLogLevel(e){this.settings.logLevel=e,await this.saveSettings(),this.emit("logLevelChanged",e)}getLogLevel(){return this.settings.logLevel}getAllSettings(){return{...this.settings}}getDisplayPreferences(){return{enableMarkdownFormatting:this.settings.enableMarkdownFormatting,showThinkingBlocks:this.settings.showThinkingBlocks,compactMode:this.settings.compactMode,enableColors:this.settings.enableColors}}getFeatureToggles(){return{enableToolCalling:this.settings.enableToolCalling,enableCrossDevice:this.settings.enableCrossDevice,enableWebSocket:this.settings.enableWebSocket,enableFirebase:this.settings.enableFirebase}}async resetToDefaults(){let e=this.settings.currentWorkingDirectory;this.settings={currentWorkingDirectory:e,isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},await this.saveSettings(),this.emit("settingsReset")}exportSettings(){return JSON.stringify(this.settings,null,2)}async importSettings(e){try{let t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified)),await this.saveSettings(),this.emit("settingsImported")}catch{throw new Error("Invalid settings format")}}},Zt=Ns});var et={};Se(et,{PersonalAgentService:()=>ae});import{EventEmitter as qo}from"events";import Fs from"axios";import zo from"http";import Go from"https";import{v4 as Ue}from"uuid";import xe from"fs";import ft from"path";import it from"os";var vt,ae,Pe=M(()=>{"use strict";je();ue();tt();Xe();_e();W();Xn();Rs();vt=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code,n=e?.status||e?.statusCode||e?.response?.status,i=String(s||""),r=Number(n);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(i)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||r===401||r===403||i==="401"||i==="403"?"critical":"parsing"}},ae=class c extends qo{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=X.getInstance(),this.httpAgent=new zo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Go.Agent({keepAlive:!0,timeout:36e5}),o.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),ee.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(o.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=Ei("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 xe.existsSync(e)?t=xe.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
436
+ `}getCustomPreferencesSummary(){let e=this.settings.customUserPreferences;if(!e.instructions.trim())return"No instructions set";let t=e.instructions.trim().split(/\s+/).length;return t<=10?e.instructions.trim():`${t} words of custom instructions`}async setLogLevel(e){this.settings.logLevel=e,await this.saveSettings(),this.emit("logLevelChanged",e)}getLogLevel(){return this.settings.logLevel}getAllSettings(){return{...this.settings}}getDisplayPreferences(){return{enableMarkdownFormatting:this.settings.enableMarkdownFormatting,showThinkingBlocks:this.settings.showThinkingBlocks,compactMode:this.settings.compactMode,enableColors:this.settings.enableColors}}getFeatureToggles(){return{enableToolCalling:this.settings.enableToolCalling,enableCrossDevice:this.settings.enableCrossDevice,enableWebSocket:this.settings.enableWebSocket,enableFirebase:this.settings.enableFirebase}}async resetToDefaults(){let e=this.settings.currentWorkingDirectory;this.settings={currentWorkingDirectory:e,isPrivacyModeEnabled:!0,defaultModel:"snowx-c5",temperature:.7,maxTokens:4096,enableMarkdownFormatting:!0,showThinkingBlocks:!0,compactMode:!1,enableColors:!0,enableToolCalling:!0,enableCrossDevice:!0,enableWebSocket:!0,enableFirebase:!0,customUserPreferences:{instructions:"",lastModified:new Date,isEnabled:!0},logLevel:"info",autoSaveHistory:!0,maxHistoryEntries:1e3},await this.saveSettings(),this.emit("settingsReset")}exportSettings(){return JSON.stringify(this.settings,null,2)}async importSettings(e){try{let t=JSON.parse(e);this.settings={...this.settings,...t},this.settings.customUserPreferences.lastModified&&(this.settings.customUserPreferences.lastModified=new Date(this.settings.customUserPreferences.lastModified)),await this.saveSettings(),this.emit("settingsImported")}catch{throw new Error("Invalid settings format")}}},Zt=As});var et={};Se(et,{PersonalAgentService:()=>ae});import{EventEmitter as qo}from"events";import Rs from"axios";import zo from"http";import Go from"https";import{v4 as Ue}from"uuid";import xe from"fs";import ft from"path";import it from"os";var vt,ae,Pe=M(()=>{"use strict";je();ue();tt();Xe();_e();W();jn();Ns();vt=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code,n=e?.status||e?.statusCode||e?.response?.status,i=String(s||""),r=Number(n);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(i)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||r===401||r===403||i==="401"||i==="403"?"critical":"parsing"}},ae=class c extends qo{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=X.getInstance(),this.httpAgent=new zo.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Go.Agent({keepAlive:!0,timeout:36e5}),o.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout"),ee.getInstance().on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(o.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=Ei("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 xe.existsSync(e)?t=xe.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
437
437
 
438
438
  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.
439
439
 
@@ -461,7 +461,7 @@ Current project path in this session: ${Zt.getInstance().getWorkingDirectory()||
461
461
  *Last updated: ${new Date().toISOString()}*
462
462
  `;return xe.writeFileSync(e,a,"utf8"),a}catch{return"Basic device knowledge initialization failed."}}static getInstance(){return c.instance||(c.instance=new c),c.instance}generateRequestHash(e,t){let s=`${e}:${t}:${Date.now()}`,n=0;for(let i=0;i<s.length;i++){let r=s.charCodeAt(i);n=(n<<5)-n+r,n=n&n}return n.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,s,n=.7,i=!0,r,a,l){let u=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(u))return o.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(u),this.lastRequestHash=u,this.lastRequestTime=Date.now(),this.currentPromptId=Ue(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=s;let d=l?.crossDeviceTaskId;d&&o.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),l?.mode==="new"&&(t=[],o.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let m=r||this.authService.getUserId();o.debug("🔌 WebSocket will connect after receiving sessionId from API...");let S=de.getInstance().getCurrentDeviceId();if(!S)throw o.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let T=`${this.getProjectPathContext()}
463
463
 
464
- My main prompt: ${e}`,I={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:T},...a.map(D=>({type:"image_url",image_url:{url:D}}))]:[{type:"text",text:T}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:S,model:s.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(l?.conversationId)I.conversationId=l.conversationId,o.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),o.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let D=t.map(y=>{let A,_=y;_.metadata?.toolResults?A=_.metadata.toolResults:_.originalContent?A=_.originalContent:A=typeof y.content=="string"?y.content:JSON.stringify(y.content);let P=[{type:"text",text:A}];return _.imageUrls&&_.imageUrls.length>0&&P.push(..._.imageUrls.map(F=>({type:"image_url",image_url:{url:F}}))),{role:y.role,content:P}});for(let y=0;y<D.length;y++)D[y].role;I.messages=D,o.debug(`[PERSONAL AGENT] Sending request with ${D.length} messages (new conversation)`)}else o.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return i?this.performStreamingToolCall(I,u):this.performNonStreamingToolCall(I,u)}async performStreamingToolCall(e,t){let s=await this.getFirebaseIdToken();return s||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((n,i)=>{this.currentAbortController=new AbortController;let r="",a=Buffer.alloc(0),l="",u="",d=[],m=null,S=!1,w="";this.currentOutput="",this.completeOutputWithToolResults="";let T=new Map,I=new Set,D=this.authService.getUserId();Fs.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 y=>{let A=y.data,_=y.headers["x-session-id"]||y.headers["session-id"];if(_){m=_,this.currentSessionId=_,o.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${_}`);let P=ee.getInstance();o.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await P.connectForConversation(D||void 0,_)?o.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):o.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else o.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");A.on("data",P=>{try{a=Buffer.concat([a,P]);let N="",x=0;for(let E=0;E<a.length;E++)try{N=a.slice(0,E+1).toString("utf8"),x=E+1}catch{break}if(x>0){let E=a.slice(0,x);a=a.slice(x),r+=E.toString("utf8")}}catch{r+=P.toString()}let F=[/\r?\n/,/\r/],H=[],g=r;H=g.split(/\r?\n/),g=H.pop()||"",r=g;for(let N of H){let x=N.trim();if(!(!x||x.startsWith(":"))){if(x.startsWith("event: keepalive")){o.debug("[PERSONAL AGENT] Received keepalive event"),this.emit("keepalive");continue}if(x.startsWith("data: ")){let E=x.slice(6).trim();if(E==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",l),n(l);return}try{let h=JSON.parse(E);if(h.type==="session_start"&&h.conversationId){let v=h.conversationId,C=h.isNewConversation||!1,b=h.title;o.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),o.debug(`[PERSONAL AGENT] conversationId: ${v}`),o.debug(`[PERSONAL AGENT] isNewConversation: ${C}`),b&&o.debug(`[PERSONAL AGENT] title: "${b}"`),this.emit("conversation_id_received",{conversationId:v,isNew:C,title:b||void 0});continue}if(h.type==="title_generated"&&h.title&&h.conversationId){let v=h.title,C=h.conversationId;o.debug("[PERSONAL AGENT] Received title_generated event!"),o.debug(`[PERSONAL AGENT] conversationId: ${C}`),o.debug(`[PERSONAL AGENT] title: "${v}"`),this.emit("conversation_title_updated",{conversationId:C,title:v});continue}if(h.type==="error"||h.error){let v=h.error||h,C=v.message||"Unknown error occurred",b=v.status||500,f=v.provider||"unknown";o.debug(`[PERSONAL AGENT] API Error - Status: ${b}, Provider: ${f}`),o.debug(`[PERSONAL AGENT] Error Message: ${C}`);let $=C;try{let V=JSON.parse(C);V.error?.message&&($=V.error.message)}catch{}let L;b===503?L=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
464
+ My main prompt: ${e}`,I={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:T},...a.map(D=>({type:"image_url",image_url:{url:D}}))]:[{type:"text",text:T}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:S,model:s.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(l?.conversationId)I.conversationId=l.conversationId,o.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),o.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let D=t.map(y=>{let A,_=y;_.metadata?.toolResults?A=_.metadata.toolResults:_.originalContent?A=_.originalContent:A=typeof y.content=="string"?y.content:JSON.stringify(y.content);let P=[{type:"text",text:A}];return _.imageUrls&&_.imageUrls.length>0&&P.push(..._.imageUrls.map(F=>({type:"image_url",image_url:{url:F}}))),{role:y.role,content:P}});for(let y=0;y<D.length;y++)D[y].role;I.messages=D,o.debug(`[PERSONAL AGENT] Sending request with ${D.length} messages (new conversation)`)}else o.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return i?this.performStreamingToolCall(I,u):this.performNonStreamingToolCall(I,u)}async performStreamingToolCall(e,t){let s=await this.getFirebaseIdToken();return s||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((n,i)=>{this.currentAbortController=new AbortController;let r="",a=Buffer.alloc(0),l="",u="",d=[],m=null,S=!1,w="";this.currentOutput="",this.completeOutputWithToolResults="";let T=new Map,I=new Set,D=this.authService.getUserId();Rs.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 y=>{let A=y.data,_=y.headers["x-session-id"]||y.headers["session-id"];if(_){m=_,this.currentSessionId=_,o.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${_}`);let P=ee.getInstance();o.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await P.connectForConversation(D||void 0,_)?o.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):o.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else o.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");A.on("data",P=>{try{a=Buffer.concat([a,P]);let N="",x=0;for(let E=0;E<a.length;E++)try{N=a.slice(0,E+1).toString("utf8"),x=E+1}catch{break}if(x>0){let E=a.slice(0,x);a=a.slice(x),r+=E.toString("utf8")}}catch{r+=P.toString()}let F=[/\r?\n/,/\r/],H=[],g=r;H=g.split(/\r?\n/),g=H.pop()||"",r=g;for(let N of H){let x=N.trim();if(!(!x||x.startsWith(":"))){if(x.startsWith("event: keepalive")){o.debug("[PERSONAL AGENT] Received keepalive event"),this.emit("keepalive");continue}if(x.startsWith("data: ")){let E=x.slice(6).trim();if(E==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",l),n(l);return}try{let h=JSON.parse(E);if(h.type==="session_start"&&h.conversationId){let v=h.conversationId,C=h.isNewConversation||!1,b=h.title;o.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),o.debug(`[PERSONAL AGENT] conversationId: ${v}`),o.debug(`[PERSONAL AGENT] isNewConversation: ${C}`),b&&o.debug(`[PERSONAL AGENT] title: "${b}"`),this.emit("conversation_id_received",{conversationId:v,isNew:C,title:b||void 0});continue}if(h.type==="title_generated"&&h.title&&h.conversationId){let v=h.title,C=h.conversationId;o.debug("[PERSONAL AGENT] Received title_generated event!"),o.debug(`[PERSONAL AGENT] conversationId: ${C}`),o.debug(`[PERSONAL AGENT] title: "${v}"`),this.emit("conversation_title_updated",{conversationId:C,title:v});continue}if(h.type==="error"||h.error){let v=h.error||h,C=v.message||"Unknown error occurred",b=v.status||500,f=v.provider||"unknown";o.debug(`[PERSONAL AGENT] API Error - Status: ${b}, Provider: ${f}`),o.debug(`[PERSONAL AGENT] Error Message: ${C}`);let $=C;try{let V=JSON.parse(C);V.error?.message&&($=V.error.message)}catch{}let L;b===503?L=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
465
465
 
466
466
  Details: ${$}`:b>=500?L=`Server Error (${b}): The AI service encountered an internal error. Please try again.
467
467
 
@@ -482,7 +482,7 @@ ${V}
482
482
  </context>`;if(d.push(Z),l+=Z+`
483
483
  `,this.completeOutputWithToolResults+=Z+`
484
484
  `,this.currentOutput+=Z+`
485
- `,!b){let me=v.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(me){let j=v.replace(me[0],"").trim();if(j.length>0){l+=j,u+=j,this.currentOutput+=j,this.completeOutputWithToolResults+=j;let O=Le.remove(j);this.emit("data",O)}}}continue}}catch{}if(v.includes("<think>")){S=!0;let C=v.split("<think>")[0];if(C){l+=C,u+=C,this.currentOutput+=C,this.completeOutputWithToolResults+=C;let b=Le.remove(C);this.emit("data",b)}}else if(v.includes("</think>")){S=!1,w+=v.split("</think>")[0],this.emit("thinking",w),w="";let C=v.split("</think>")[1]||"";if(C){l+=C,u+=C,this.currentOutput+=C,this.completeOutputWithToolResults+=C;let b=Le.remove(C);this.emit("data",b)}}else if(S)w+=v,this.emit("thinking",w);else{l+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let C=Le.remove(v);this.emit("data",C)}}else if(h.type==="checkpoint_reached"||h.event==="checkpoint_reached")o.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(h.type==="todo_update")this.handleTodoUpdate(h.data);else if(h.type==="webview_update")this.handleWebViewUpdate(h.data);else if(h.type==="operator_progress")this.handleOperatorProgress(h.data);else if(h.type==="stop"){this.handleStop(h.data),n(l);return}}catch{o.debug("Treating as plain text"),l+=E,u+=E,this.currentOutput+=E,this.completeOutputWithToolResults+=E;let v=Le.remove(E);this.emit("data",v)}}}}}),A.on("end",()=>{this.inflightRequests.delete(t),this.activeToolNames.clear(),this.emit("done"),n(l)}),A.on("error",P=>{switch(o.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),vt.classify(P)){case"parsing":let H={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Streaming parsing error occurred: ${P.message}. Please check response format and retry.`};o.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(H)),ee.getInstance().handleConversationComplete(),n(l);return;case"critical":ee.getInstance().handleConversationComplete(),this.emit("error",P),i(P);break}})}).catch(y=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),y.code==="ERR_CANCELED")o.debug("Task was cancelled, disconnecting WebSocket"),ee.getInstance().handleConversationComplete(),this.emit("canceled"),n(l);else switch(vt.classify(y)){case"parsing":let _={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Request parsing error: ${y.message}. Please check request format and retry.`};o.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(_)),ee.getInstance().handleConversationComplete(),n(l);break;case"critical":o.debug("Request failed, disconnecting WebSocket"),ee.getInstance().handleConversationComplete(),i(y);break}})})}async performNonStreamingToolCall(e,t){try{let s=await this.getFirebaseIdToken();s||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let n=await Fs.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 i of n.data.toolResults)this.handleToolResult(i.tool,i.result);return n.data.content}throw new Error("No response content received")}catch(s){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),vt.classify(s)){case"parsing":let i={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Non-streaming API parsing error: ${s.message}. Please check request format and retry.`};return o.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(i)),"";case"critical":throw this.emit("error",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{o.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=ee.getInstance(),i={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await n.sendToolRequest(i)}catch(n){o.debug(`Failed to execute tool via WebSocket: ${n.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),o.debug(`Tool Result: ${e.name}`),t&&o.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:s,success:n,error:i}=e;if(o.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",n),n&&s){let a=`<context>
485
+ `,!b){let me=v.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(me){let j=v.replace(me[0],"").trim();if(j.length>0){l+=j,u+=j,this.currentOutput+=j,this.completeOutputWithToolResults+=j;let O=Le.remove(j);this.emit("data",O)}}}continue}}catch{}if(v.includes("<think>")){S=!0;let C=v.split("<think>")[0];if(C){l+=C,u+=C,this.currentOutput+=C,this.completeOutputWithToolResults+=C;let b=Le.remove(C);this.emit("data",b)}}else if(v.includes("</think>")){S=!1,w+=v.split("</think>")[0],this.emit("thinking",w),w="";let C=v.split("</think>")[1]||"";if(C){l+=C,u+=C,this.currentOutput+=C,this.completeOutputWithToolResults+=C;let b=Le.remove(C);this.emit("data",b)}}else if(S)w+=v,this.emit("thinking",w);else{l+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let C=Le.remove(v);this.emit("data",C)}}else if(h.type==="checkpoint_reached"||h.event==="checkpoint_reached")o.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(h.type==="todo_update")this.handleTodoUpdate(h.data);else if(h.type==="webview_update")this.handleWebViewUpdate(h.data);else if(h.type==="operator_progress")this.handleOperatorProgress(h.data);else if(h.type==="stop"){this.handleStop(h.data),n(l);return}}catch{o.debug("Treating as plain text"),l+=E,u+=E,this.currentOutput+=E,this.completeOutputWithToolResults+=E;let v=Le.remove(E);this.emit("data",v)}}}}}),A.on("end",()=>{this.inflightRequests.delete(t),this.activeToolNames.clear(),this.emit("done"),n(l)}),A.on("error",P=>{switch(o.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),vt.classify(P)){case"parsing":let H={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Streaming parsing error occurred: ${P.message}. Please check response format and retry.`};o.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(H)),ee.getInstance().handleConversationComplete(),n(l);return;case"critical":ee.getInstance().handleConversationComplete(),this.emit("error",P),i(P);break}})}).catch(y=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),y.code==="ERR_CANCELED")o.debug("Task was cancelled, disconnecting WebSocket"),ee.getInstance().handleConversationComplete(),this.emit("canceled"),n(l);else switch(vt.classify(y)){case"parsing":let _={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Request parsing error: ${y.message}. Please check request format and retry.`};o.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(_)),ee.getInstance().handleConversationComplete(),n(l);break;case"critical":o.debug("Request failed, disconnecting WebSocket"),ee.getInstance().handleConversationComplete(),i(y);break}})})}async performNonStreamingToolCall(e,t){try{let s=await this.getFirebaseIdToken();s||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let n=await Rs.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 i of n.data.toolResults)this.handleToolResult(i.tool,i.result);return n.data.content}throw new Error("No response content received")}catch(s){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),vt.classify(s)){case"parsing":let i={type:"tool_result",tool_call_id:`error_${Ue()}`,error:!0,content:`Non-streaming API parsing error: ${s.message}. Please check request format and retry.`};return o.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(i)),"";case"critical":throw this.emit("error",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{o.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=ee.getInstance(),i={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await n.sendToolRequest(i)}catch(n){o.debug(`Failed to execute tool via WebSocket: ${n.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),o.debug(`Tool Result: ${e.name}`),t&&o.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:s,success:n,error:i}=e;if(o.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",n),n&&s){let a=`<context>
486
486
  ${s.map(l=>l.text||"").join("")}
487
487
  </context>`;this.completeOutputWithToolResults+=a+`
488
488
  `,this.currentOutput+=a+`
@@ -498,41 +498,41 @@ ${t}
498
498
  `,this.currentOutput+=i+`
499
499
  `,o.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),o.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:n,wrappedContent:i})}handleCheckpointReached(){let e=Ce.getInstance(),t=e.getQueuedMessages();if(t.length===0){o.debug("[CHECKPOINT] No queued messages to convert");return}let s=t.filter(i=>!i.isCrossDeviceTask),n=t.filter(i=>i.isCrossDeviceTask);if(o.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),o.debug(` - ${s.length} user messages -> convert to feedback`),o.debug(` - ${n.length} cross-device tasks -> keep in queue`),s.length>0){let i=s.map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",i),o.info(`[CHECKPOINT] Converted ${s.length} user messages to feedback`),s.forEach(r=>{e.removeFromQueueById(r.id)})}n.length>0&&o.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||Ue(),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||Ue(),taskId:e.taskId||e.id||Ue(),sessionId:e.sessionId||Ue(),status:e.status||"pending",task:e.task||e.description||"",llm:e.llm,currentStep:e.currentStep,totalSteps:e.totalSteps||0,steps:e.steps||[],result:e.result,error:e.error,startTime:e.startTime||new Date},this.emit("operator_progress",this.operatorTaskState)}handleStop(e){e.reason==="CONVERSATION_COMPLETE"&&this.handleConversationComplete(),this.emit("BotResponseStopped",{reason:e.reason||"user_manual_stop"}),this.emit("stop",e)}async handleConversationComplete(){if(o.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),ee.getInstance().handleConversationComplete(),o.debug("[PERSONAL AGENT] WebSocket disconnected after conversation completion"),this.currentOutput.trim().length>0){let t={conversationId:null,content:this.currentOutput,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};o.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),o.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),o.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,s)=>typeof s.content=="string"?t+Math.ceil(s.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let s=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",n=Q.find(r=>r.name===s)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},i=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,i,n,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){o.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),ee.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
500
500
 
501
- [STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{o.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(n){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",n)}await this.completeConversation(s,"STOP"),o.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),o.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.session_id=this.currentSessionId,o.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):o.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let n=de.getInstance().getCurrentDeviceId();n?(s.device_id=n,o.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):o.debug("[PERSONAL AGENT] No device_id available for stop request"),o.debug("[PERSONAL AGENT] Sending backend stop request");let i=await this.getFirebaseIdToken();i||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let r=await Fs.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i||this.getAuthToken()}`}});r.status===200&&(o.debug("[PERSONAL AGENT] Backend stop successful:",r.data),r.data.stopped_sessions&&o.debug("[PERSONAL AGENT] Stopped sessions:",r.data.stopped_sessions),r.data.stopped_tools&&o.debug("[PERSONAL AGENT] Stopped tools:",r.data.stopped_tools))}catch(e){o.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){o.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),ee.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(),o.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),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 Kn={};Se(Kn,{FirebaseNativeService:()=>bt,TaskMode:()=>_s,TaskStatus:()=>Ms});import{getDatabase as Vo,ref as $s,onChildAdded as Ko,update as Qo,set as Jo,serverTimestamp as Yo}from"firebase/database";import{EventEmitter as Zo}from"events";var _s,Ms,bt,Ls=M(()=>{"use strict";W();Ct();_s=(t=>(t.NEW="new",t.EXISTING="existing",t))(_s||{}),Ms=(n=>(n.PENDING="pending",n.PROCESSING="processing",n.COMPLETED="completed",n.QUEUE_FULL="queue_full",n))(Ms||{}),bt=class c extends Zo{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(),o.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Oe.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=Vo(e),o.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(o.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(o.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){o.error("[Firebase Native] Firebase not initialized properly");return}o.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;o.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let n=$s(this.database,s),i=this.auth?.currentUser;o.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!i,uid:i?.uid||"none",email:i?.email||"none"}),this.listenerHandle=Ko(n,r=>{let a=r.key,l=r.val();if(o.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){o.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){o.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){o.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(m=>this.processedTaskIds.delete(m))}o.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{o.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),o.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){o.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,o.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),o.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),o.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){o.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){o.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),o.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),o.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(Pe(),et))).PersonalAgentService.getInstance()){o.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}o.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?o.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):o.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),o.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),o.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(n){o.error("[FIREBASE-NATIVE] Task execution failed:",n.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Pe(),et)),s=t.getInstance();await this.cleanupObservers(),this.completedObserver=n=>{this.currentTaskId===e&&(o.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 i=n?.message||n||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${i}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=n=>{if(this.currentTaskId!==e)return;let i=n?.reason;o.debug(`[RESULT MONITOR] Task ${e} stopped: ${i}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),o.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(Pe(),et)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),o.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){o.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,i={status:t,updatedAt:"firebase_timestamp"};s&&(i.result=s),o.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:n,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(n,i),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:n,error:r.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=$s(this.database,n),l={status:t,updatedAt:Yo()};s&&(l.result=s),await Qo(a,l),o.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else o.error("[Firebase Native] Database not available for fallback")}catch(a){o.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,n){let i=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;o.debug("[Firebase Native] Sending task to device",{taskId:i,targetDeviceId:t,mode:n});try{let r=$s(this.database,`users/${e}/devices/${t}/tasks/${i}`),a={taskId:i,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:n,timestamp:Date.now(),status:"pending"};return await Jo(r,a),o.debug("[Firebase Native] Task sent successfully",{taskId:i,targetDeviceId:t}),i}catch(r){throw r}}stopListening(){if(o.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,o.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){o.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),o.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as er}from"events";var ot,Us=M(()=>{"use strict";_e();ue();Ct();Ls();Pe();W();ot=class c extends er{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=de.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=Oe.getInstance(),this.firebaseNative=bt.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=ae.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){o.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(o.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(o.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){o.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){o.debug("✅ [CrossDevice] No pending tasks in queue");return}let s=this.pendingTasksQueue.shift();o.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){o.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,o.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let n=this.authService.getFirebaseAuth();if(!n?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(n.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",n.currentUser.uid,"Requested:",e),o.error("Refusing to start listener for different user");return}o.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(n){throw o.error("Failed to start listener:",n.message),n}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),o.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){o.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){o.error("No stored user ID found - cannot authenticate Firebase for listeners");return}o.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let n=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",n.user.uid)}}catch(s){o.warn("Firebase authentication failed:",s.message),o.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){o.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e.taskId),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,o.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),o.debug("Cross-device task UI flow triggered successfully")}catch(t){o.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){o.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(s){o.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),o.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let n=s[1],i=s[2];return n.length!==13||!Number.isInteger(Number(n))||i.length!==9?!1:/^[a-z0-9]+$/.test(i)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,n=t.prompt,i=t.status;if(!s||!n){o.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(i!=="pending"){o.debug("⏭️ [CrossDevice] Skipping non-pending task:",s,"Status:",i);return}this.incomingTaskQueue.push({taskId:s,prompt:n,snapshot:e}),o.debug(`📨 [CrossDevice] Task queued for processing: ${s}`),o.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){o.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,o.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:s}=this.incomingTaskQueue.shift();o.debug(`🔵 [CrossDevice] Processing task: ${e}`),o.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let n=s.val();if(o.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(o.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){o.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}o.debug("✅ [CrossDevice] Task accepted:",e),o.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,o.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=(Xe(),Pi(sn)).MessageQueueManager.getInstance(),i=n.getQueueCount(),r=n.canAddToQueue();if(o.debug(`🔍 [CrossDevice] Queue capacity check: ${i}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,s){if(o.debug(`Executing task: ${e} with mode: ${s}`),o.debug(`Prompt to execute: ${t}`),ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),o.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}o.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{o.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(n){o.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=i=>{this.currentTaskId===e&&this.cleanupObservers()},n=i=>{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)}`,i={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:$e,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${n}`;try{await this.firebaseAPI.writeRealtimeData(r,i),o.debug("Task submitted to device:",e)}catch(a){throw o.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([s,n])=>({id:s,...n})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return o.error("Failed to get available devices:",e.message),[]}}enable(){o.debug("[CROSS DEVICE] Service enabled")}disable(){o.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){o.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var ui={};Se(ui,{SnowXStreamHandlerService:()=>Gs});import{EventEmitter as kr}from"events";var Gs,di=M(()=>{"use strict";Gs=class extends kr{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,i){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let d=this.byteBuffer.toString("utf8");this.buffer+=d,this.rawDataReceived+=d,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,n,i)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,n,i),this.printFinalStatistics(),!this.fullResponse&&!i){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let n,i=this.buffer.indexOf(`\r
501
+ [STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{o.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(n){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",n)}await this.completeConversation(s,"STOP"),o.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),o.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.session_id=this.currentSessionId,o.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):o.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let n=de.getInstance().getCurrentDeviceId();n?(s.device_id=n,o.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):o.debug("[PERSONAL AGENT] No device_id available for stop request"),o.debug("[PERSONAL AGENT] Sending backend stop request");let i=await this.getFirebaseIdToken();i||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let r=await Rs.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i||this.getAuthToken()}`}});r.status===200&&(o.debug("[PERSONAL AGENT] Backend stop successful:",r.data),r.data.stopped_sessions&&o.debug("[PERSONAL AGENT] Stopped sessions:",r.data.stopped_sessions),r.data.stopped_tools&&o.debug("[PERSONAL AGENT] Stopped tools:",r.data.stopped_tools))}catch(e){o.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){o.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),ee.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(),o.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),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 Vn={};Se(Vn,{FirebaseNativeService:()=>bt,TaskMode:()=>$s,TaskStatus:()=>_s});import{getDatabase as Vo,ref as Os,onChildAdded as Ko,update as Qo,set as Jo,serverTimestamp as Yo}from"firebase/database";import{EventEmitter as Zo}from"events";var $s,_s,bt,Ms=M(()=>{"use strict";W();Ct();$s=(t=>(t.NEW="new",t.EXISTING="existing",t))($s||{}),_s=(n=>(n.PENDING="pending",n.PROCESSING="processing",n.COMPLETED="completed",n.QUEUE_FULL="queue_full",n))(_s||{}),bt=class c extends Zo{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(),o.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Oe.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=Vo(e),o.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(o.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(o.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){o.error("[Firebase Native] Firebase not initialized properly");return}o.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;o.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let n=Os(this.database,s),i=this.auth?.currentUser;o.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!i,uid:i?.uid||"none",email:i?.email||"none"}),this.listenerHandle=Ko(n,r=>{let a=r.key,l=r.val();if(o.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){o.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){o.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){o.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(m=>this.processedTaskIds.delete(m))}o.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{o.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),o.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){o.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,o.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),o.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),o.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){o.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){o.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),o.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),o.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(Pe(),et))).PersonalAgentService.getInstance()){o.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}o.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?o.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):o.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),o.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),o.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(n){o.error("[FIREBASE-NATIVE] Task execution failed:",n.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Pe(),et)),s=t.getInstance();await this.cleanupObservers(),this.completedObserver=n=>{this.currentTaskId===e&&(o.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 i=n?.message||n||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${i}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=n=>{if(this.currentTaskId!==e)return;let i=n?.reason;o.debug(`[RESULT MONITOR] Task ${e} stopped: ${i}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),o.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(Pe(),et)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),o.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){o.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,i={status:t,updatedAt:"firebase_timestamp"};s&&(i.result=s),o.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:n,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(n,i),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:n,error:r.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Os(this.database,n),l={status:t,updatedAt:Yo()};s&&(l.result=s),await Qo(a,l),o.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else o.error("[Firebase Native] Database not available for fallback")}catch(a){o.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,n){let i=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;o.debug("[Firebase Native] Sending task to device",{taskId:i,targetDeviceId:t,mode:n});try{let r=Os(this.database,`users/${e}/devices/${t}/tasks/${i}`),a={taskId:i,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:n,timestamp:Date.now(),status:"pending"};return await Jo(r,a),o.debug("[Firebase Native] Task sent successfully",{taskId:i,targetDeviceId:t}),i}catch(r){throw r}}stopListening(){if(o.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,o.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){o.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),o.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as er}from"events";var ot,Ls=M(()=>{"use strict";_e();ue();Ct();Ms();Pe();W();ot=class c extends er{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];incomingTaskQueue=[];isProcessingIncoming=!1;currentlyExecutingTaskId=null;overlayManager=null;constructor(){super(),this.deviceRegistrationService=de.getInstance(),this.authService=X.getInstance(),this.firebaseAPI=Oe.getInstance(),this.firebaseNative=bt.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=ae.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){o.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(o.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(o.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){o.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){o.debug("✅ [CrossDevice] No pending tasks in queue");return}let s=this.pendingTasksQueue.shift();o.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){o.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,o.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let n=this.authService.getFirebaseAuth();if(!n?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(n.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",n.currentUser.uid,"Requested:",e),o.error("Refusing to start listener for different user");return}o.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(n){throw o.error("Failed to start listener:",n.message),n}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),o.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){o.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){o.error("No stored user ID found - cannot authenticate Firebase for listeners");return}o.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let n=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",n.user.uid)}}catch(s){o.warn("Firebase authentication failed:",s.message),o.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){o.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e.taskId),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,o.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),o.debug("Cross-device task UI flow triggered successfully")}catch(t){o.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){o.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(s){o.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),o.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let n=s[1],i=s[2];return n.length!==13||!Number.isInteger(Number(n))||i.length!==9?!1:/^[a-z0-9]+$/.test(i)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,n=t.prompt,i=t.status;if(!s||!n){o.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(i!=="pending"){o.debug("⏭️ [CrossDevice] Skipping non-pending task:",s,"Status:",i);return}this.incomingTaskQueue.push({taskId:s,prompt:n,snapshot:e}),o.debug(`📨 [CrossDevice] Task queued for processing: ${s}`),o.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){o.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,o.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:s}=this.incomingTaskQueue.shift();o.debug(`🔵 [CrossDevice] Processing task: ${e}`),o.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let n=s.val();if(o.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(o.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){o.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}o.debug("✅ [CrossDevice] Task accepted:",e),o.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,o.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let n=(Xe(),Pi(tn)).MessageQueueManager.getInstance(),i=n.getQueueCount(),r=n.canAddToQueue();if(o.debug(`🔍 [CrossDevice] Queue capacity check: ${i}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,s){if(o.debug(`Executing task: ${e} with mode: ${s}`),o.debug(`Prompt to execute: ${t}`),ae.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),o.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}o.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{o.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(n){o.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=i=>{this.currentTaskId===e&&this.cleanupObservers()},n=i=>{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)}`,i={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:$e,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${n}`;try{await this.firebaseAPI.writeRealtimeData(r,i),o.debug("Task submitted to device:",e)}catch(a){throw o.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([s,n])=>({id:s,...n})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return o.error("Failed to get available devices:",e.message),[]}}enable(){o.debug("[CROSS DEVICE] Service enabled")}disable(){o.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){o.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var ui={};Se(ui,{SnowXStreamHandlerService:()=>zs});import{EventEmitter as Cr}from"events";var zs,di=M(()=>{"use strict";zs=class extends Cr{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,i){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let d=this.byteBuffer.toString("utf8");this.buffer+=d,this.rawDataReceived+=d,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,n,i)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,n,i),this.printFinalStatistics(),!this.fullResponse&&!i){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let n,i=this.buffer.indexOf(`\r
502
502
  `);if(i!==-1)n=i;else{let r=this.buffer.indexOf(`
503
503
  `);if(r!==-1)n=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)n=a;else return}}for(;n!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,n);this.linesProcessed++,this.buffer.substring(n,n+2)===`\r
504
504
  `?this.buffer=this.buffer.substring(n+2):this.buffer=this.buffer.substring(n+1);let a=r.trim();if(!a){n=this.findNextLineEnd();continue}if(a.startsWith(":")){n=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),n=this.findNextLineEnd()}}processDataLine(e,t,s,n){if(this.isCancelled)return;this.dataLinesFound++;let i=e.substring(6).trim();if(i==="[DONE]"){this.emit("streamEnd");return}if(i)try{let r=JSON.parse(i);if(r.choices&&r.choices.length>0){let a=r.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)n?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,s))}}catch{}}processThinkingContent(e,t,s){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let n=this.thinkingBuffer.indexOf("</think>");if(n!==-1){let i=this.thinkingBuffer.substring(0,n);i&&(this.thinkingContent+=i,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 i=this.thinkingBuffer.substring(0,n);i&&(this.regularContent+=i,this.fullResponse+=i,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 i=JSON.parse(n);i.choices&&i.choices.length>0&&i.choices[0].delta.content&&this.processThinkingContent(i.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
505
505
  `);if(e!==-1)return e;let t=this.buffer.indexOf(`
506
- `);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 xr from"axios";import{EventEmitter as Er}from"events";import Ir from"http";import Pr from"https";var is,pi=M(()=>{"use strict";ue();is=class extends Er{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Ir.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Pr.Agent({keepAlive:!0,timeout:36e5}),this.client=xr.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.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 i=Math.pow(2,s);await new Promise(r=>setTimeout(r,i*1e3))}else throw n}throw new Error("Max retries exceeded")}buildRequest(e,t,s,n=.7,i=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:n,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:i,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,n=.9,i,r){let a=this.buildRequest(e,t,!1,s,n,i,r);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(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,s=.7,n=.9,i,r,a,l,u){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(di(),ui)),m=this.buildRequest(e,t,!0,s,n,i,r);return new Promise((S,w)=>{this.currentAbortController=new AbortController;let T=[],I=new Map,D=new d;this.client.post("/chat/completions",m,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async y=>{let A=y.data,_=y.headers["content-type"]||"",P=F=>{if(F?.index!==void 0){let H=F.index;I.has(H)||I.set(H,{});let g=I.get(H);F.id&&(g.id=F.id,g.type="function"),F.function&&(g.function||(g.function={name:"",arguments:""}),F.function.name&&(g.function.name=F.function.name),F.function.arguments&&(g.function.arguments+=F.function.arguments))}u?.(F),this.emit("tool_call_delta",F)};D.on("streamEnd",()=>{I.forEach((F,H)=>{F.id&&F.function?.name&&T.push(F)}),this.emit("done"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})}),D.on("cancelled",()=>{this.emit("canceled"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})});try{await D.processStreamingResponse(A,_,a||(()=>{}),l,P),I.forEach((F,H)=>{F.id&&F.function?.name&&T.push(F)}),this.emit("done"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})}catch(F){this.emit("error",F),w(F)}}).catch(y=>{y.code==="ERR_CANCELED"?(this.emit("canceled"),S({content:"",toolCalls:T.length>0?T:void 0})):w(y)})})}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 Dr}from"socket.io-client";import{EventEmitter as Ar}from"events";var os,mi=M(()=>{"use strict";_e();os=class c extends Ar{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=de.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let s={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=Dr(t,s),this.setupEventHandlers(),new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),n(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),i(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 gi,hi=M(()=>{"use strict";gi={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 vi={};Se(vi,{ServiceManager:()=>yt});import{EventEmitter as Nr}from"events";import{initializeApp as Rr,getApps as fi}from"firebase/app";import{getAuth as Fr}from"firebase/auth";var yt,js=M(()=>{"use strict";Pe();pi();ue();_e();mi();tt();Us();$t();je();W();hi();yt=class c extends Nr{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=ae.getInstance(),this.networkClient=new is,this.authService=X.getInstance(),this.deviceRegistration=de.getInstance(),this.webSocketService=os.getInstance(),this.frontendWebSocketService=ee.getInstance(),this.crossDeviceService=ot.getInstance(),this.toolCalling=ht.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||gi;if(fi().length===0?(this.firebaseApp=Rr(e),o.debug("Firebase app initialized")):(this.firebaseApp=fi()[0],o.debug("Using existing Firebase app")),this.firebaseAuth=Fr(this.firebaseApp),o.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),o.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Ls(),Kn));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),o.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{o.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){o.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){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=Q[0],s={}){let{usePersonalAgent:n=!0,enableToolCalling:i=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=s;try{let l=[];if(n)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=i?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,m)=>{let S="";this.networkClient.on("data",w=>{S+=w}),this.networkClient.on("done",()=>{d(S)}),this.networkClient.on("error",m),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:s}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return Q.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 i=setTimeout(()=>{n(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(i),this.deviceRegistration.off("DeviceRegistrationComplete",r),s()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(i),this.deviceRegistration.off("DeviceRegistrationComplete",r),s())})}}});import*as Qs from"@sentry/node";Qs.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as Hr}from"commander";import _r from"react";import{withFullScreen as Mr}from"fullscreen-ink";ue();import p,{useState as ti,useEffect as qe,useCallback as Bs,useRef as ss,useMemo as ns,memo as cr}from"react";import{Box as R,Text as k,useInput as lr,useApp as ur}from"ink";import si from"ink-spinner";import ni from"ink-select-input";import Hs from"fs";import he from"path";import dr from"os";Pe();As();import ye from"chalk";import jo from"ora";var ce=class{static spinner=null;static formatUserMessage(e){return ye.cyan("You: ")+e}static formatAssistantMessage(e){return ye.green("Assistant: ")+e}static formatError(e){return ye.red("Error: ")+e}static formatWarning(e){return ye.yellow("Warning: ")+e}static formatInfo(e){return ye.blue("Info: ")+e}static formatSuccess(e){return ye.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=jo(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(ye.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(ye.bold.cyan(e)),console.log(ye.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return ye.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return ye.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(ye.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};W();Xe();Ke();import{EventEmitter as Xo}from"events";import Os from"chalk";var es=class extends Xo{delegate=null;personalAgentService=ae.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 i=String(n[0]||"");(i.includes("▸")||i.includes("→")||i.includes("✎"))&&t&&(e&&(e=!1),t=""),s.apply(console,n)}),this.personalAgentService.on("data",n=>{if(t+=n,this.delegate){let i=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];i&&i.isStreaming&&(!i.content||i.content===""?i.content=n:i.content+=n),r&&r.isStreaming&&(!r.content||r.content===""?r.content=n:r.content+=n)}}),this.personalAgentService.on("thinking",n=>{}),this.personalAgentService.on("toolExecuting",n=>{this.delegate?.usesCustomUI||console.log(`
506
+ `);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 kr from"axios";import{EventEmitter as xr}from"events";import Er from"http";import Ir from"https";var ns,pi=M(()=>{"use strict";ue();ns=class extends xr{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Er.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Ir.Agent({keepAlive:!0,timeout:36e5}),this.client=kr.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=X.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 i=Math.pow(2,s);await new Promise(r=>setTimeout(r,i*1e3))}else throw n}throw new Error("Max retries exceeded")}buildRequest(e,t,s,n=.7,i=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:n,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:i,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,n=.9,i,r){let a=this.buildRequest(e,t,!1,s,n,i,r);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(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,s=.7,n=.9,i,r,a,l,u){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(di(),ui)),m=this.buildRequest(e,t,!0,s,n,i,r);return new Promise((S,w)=>{this.currentAbortController=new AbortController;let T=[],I=new Map,D=new d;this.client.post("/chat/completions",m,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async y=>{let A=y.data,_=y.headers["content-type"]||"",P=F=>{if(F?.index!==void 0){let H=F.index;I.has(H)||I.set(H,{});let g=I.get(H);F.id&&(g.id=F.id,g.type="function"),F.function&&(g.function||(g.function={name:"",arguments:""}),F.function.name&&(g.function.name=F.function.name),F.function.arguments&&(g.function.arguments+=F.function.arguments))}u?.(F),this.emit("tool_call_delta",F)};D.on("streamEnd",()=>{I.forEach((F,H)=>{F.id&&F.function?.name&&T.push(F)}),this.emit("done"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})}),D.on("cancelled",()=>{this.emit("canceled"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})});try{await D.processStreamingResponse(A,_,a||(()=>{}),l,P),I.forEach((F,H)=>{F.id&&F.function?.name&&T.push(F)}),this.emit("done"),S({content:D.getFinalResponse(),toolCalls:T.length>0?T:void 0})}catch(F){this.emit("error",F),w(F)}}).catch(y=>{y.code==="ERR_CANCELED"?(this.emit("canceled"),S({content:"",toolCalls:T.length>0?T:void 0})):w(y)})})}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 Pr}from"socket.io-client";import{EventEmitter as Dr}from"events";var is,mi=M(()=>{"use strict";_e();is=class c extends Dr{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=de.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let s={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=Pr(t,s),this.setupEventHandlers(),new Promise((n,i)=>{let r=setTimeout(()=>{i(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),n(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),i(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 gi,hi=M(()=>{"use strict";gi={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 vi={};Se(vi,{ServiceManager:()=>yt});import{EventEmitter as Ar}from"events";import{initializeApp as Nr,getApps as fi}from"firebase/app";import{getAuth as Rr}from"firebase/auth";var yt,Gs=M(()=>{"use strict";Pe();pi();ue();_e();mi();tt();Ls();$t();je();W();hi();yt=class c extends Ar{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=ae.getInstance(),this.networkClient=new ns,this.authService=X.getInstance(),this.deviceRegistration=de.getInstance(),this.webSocketService=is.getInstance(),this.frontendWebSocketService=ee.getInstance(),this.crossDeviceService=ot.getInstance(),this.toolCalling=ht.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||gi;if(fi().length===0?(this.firebaseApp=Nr(e),o.debug("Firebase app initialized")):(this.firebaseApp=fi()[0],o.debug("Using existing Firebase app")),this.firebaseAuth=Rr(this.firebaseApp),o.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),o.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Ms(),Vn));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),o.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{o.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){o.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){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=Q[0],s={}){let{usePersonalAgent:n=!0,enableToolCalling:i=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=s;try{let l=[];if(n)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=i?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,m)=>{let S="";this.networkClient.on("data",w=>{S+=w}),this.networkClient.on("done",()=>{d(S)}),this.networkClient.on("error",m),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:s}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return Q.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 i=setTimeout(()=>{n(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(i),this.deviceRegistration.off("DeviceRegistrationComplete",r),s()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(i),this.deviceRegistration.off("DeviceRegistrationComplete",r),s())})}}});import*as Ks from"@sentry/node";Ks.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as Br}from"commander";import $r from"react";import{withFullScreen as _r}from"fullscreen-ink";ue();import p,{useState as ei,useEffect as qe,useCallback as Ws,useRef as ss,useMemo as ti}from"react";import{Box as R,Text as k,useInput as cr,useApp as lr}from"ink";import si from"ink-spinner";import ni from"ink-select-input";import Bs from"fs";import he from"path";import ur from"os";Pe();Ds();import ye from"chalk";import jo from"ora";var ce=class{static spinner=null;static formatUserMessage(e){return ye.cyan("You: ")+e}static formatAssistantMessage(e){return ye.green("Assistant: ")+e}static formatError(e){return ye.red("Error: ")+e}static formatWarning(e){return ye.yellow("Warning: ")+e}static formatInfo(e){return ye.blue("Info: ")+e}static formatSuccess(e){return ye.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=jo(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(ye.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(ye.bold.cyan(e)),console.log(ye.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return ye.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return ye.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(ye.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};W();Xe();Ke();import{EventEmitter as Xo}from"events";import Fs from"chalk";var es=class extends Xo{delegate=null;personalAgentService=ae.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 i=String(n[0]||"");(i.includes("▸")||i.includes("→")||i.includes("✎"))&&t&&(e&&(e=!1),t=""),s.apply(console,n)}),this.personalAgentService.on("data",n=>{if(t+=n,this.delegate){let i=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];i&&i.isStreaming&&(!i.content||i.content===""?i.content=n:i.content+=n),r&&r.isStreaming&&(!r.content||r.content===""?r.content=n:r.content+=n)}}),this.personalAgentService.on("thinking",n=>{}),this.personalAgentService.on("toolExecuting",n=>{this.delegate?.usesCustomUI||console.log(`
507
507
  ▸ ${n}`)}),this.personalAgentService.on("tool_completed",n=>{if(!this.delegate?.usesCustomUI){let{toolName:i,success:r,error:a}=n;console.log(r!==!1?`✓ ${i}`:`✗ ${i} 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],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(n.isStreaming=!1),i&&i.isStreaming&&(i.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",n=>{console.error(`
508
- ❌ Error:`,n.message||n),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",n=>{if(o.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let i=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];i&&i.isStreaming&&(n.content&&n.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${n.content.substring(0,50)}..."`),i.content=n.content,i.originalContent=n.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),n.completeWithTools&&(i.metadata={toolResults:n.completeWithTools}),i.isStreaming=!1,o.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(n.content&&n.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${n.content.substring(0,50)}..."`),r.content=n.content,r.originalContent=n.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),n.completeWithTools&&(r.metadata={toolResults:n.completeWithTools}),r.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,s=!0){if(!this.delegate||!e.trim())return;let n=new be,i=e.trim(),r=n.count(i);if(r>Ve){console.log(ce.formatError(`Prompt too large (${r.toLocaleString()} tokens). Please reduce it to ${Ve.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let u=Ce.getInstance();u.addToQueue({content:i,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Os.blue(`⚡ Message queued (${u.getQueueCount()} in queue)`)),console.log(Os.dim(" Your feedback will be sent when AI completes current task"))):console.log(Os.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await nt.getInstance().captureScreen(),a?o.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):o.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let l=[];t&&t.length>0&&(l.push(...t),o.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&l.push(a),this.delegate.currentInput="";try{s?await this.processStreamingMessage(l.length>0?l:void 0):await this.processNonStreamingMessage(l.length>0?l:void 0)}catch(u){console.error(ce.formatError(`Message failed: ${u.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",u.message)}}async processStreamingMessage(e){if(this.delegate)try{o.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(i=>!(i.isStreaming||i.role==="system"||!i.content||typeof i.content=="string"&&i.content.trim().length===0)).map(i=>({role:i.role,content:i.content})),s=this.delegate.fullConversationHistory.filter(i=>i.role==="user"),n=s[s.length-1];if(n)try{let i={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(n.content,t,this.delegate.selectedModel,.7,!0,void 0,e,i),o.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(i){throw o.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${i.message}`),i}}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 i=t.content;i.trim().length>0&&(i+=`
508
+ ❌ Error:`,n.message||n),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",n=>{if(o.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let i=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];i&&i.isStreaming&&(n.content&&n.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${n.content.substring(0,50)}..."`),i.content=n.content,i.originalContent=n.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),n.completeWithTools&&(i.metadata={toolResults:n.completeWithTools}),i.isStreaming=!1,o.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(n.content&&n.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${n.content.substring(0,50)}..."`),r.content=n.content,r.originalContent=n.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),n.completeWithTools&&(r.metadata={toolResults:n.completeWithTools}),r.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,s=!0){if(!this.delegate||!e.trim())return;let n=new be,i=e.trim(),r=n.count(i);if(r>Ve){console.log(ce.formatError(`Prompt too large (${r.toLocaleString()} tokens). Please reduce it to ${Ve.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let u=Ce.getInstance();u.addToQueue({content:i,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Fs.blue(`⚡ Message queued (${u.getQueueCount()} in queue)`)),console.log(Fs.dim(" Your feedback will be sent when AI completes current task"))):console.log(Fs.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await nt.getInstance().captureScreen(),a?o.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):o.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let l=[];t&&t.length>0&&(l.push(...t),o.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&l.push(a),this.delegate.currentInput="";try{s?await this.processStreamingMessage(l.length>0?l:void 0):await this.processNonStreamingMessage(l.length>0?l:void 0)}catch(u){console.error(ce.formatError(`Message failed: ${u.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",u.message)}}async processStreamingMessage(e){if(this.delegate)try{o.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(i=>!(i.isStreaming||i.role==="system"||!i.content||typeof i.content=="string"&&i.content.trim().length===0)).map(i=>({role:i.role,content:i.content})),s=this.delegate.fullConversationHistory.filter(i=>i.role==="user"),n=s[s.length-1];if(n)try{let i={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(n.content,t,this.delegate.selectedModel,.7,!0,void 0,e,i),o.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(i){throw o.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${i.message}`),i}}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 i=t.content;i.trim().length>0&&(i+=`
509
509
 
510
- `),i+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=i}t.isStreaming=!1;let n=this.delegate.fullConversationHistory.find(i=>i.isStreaming);n&&(n.content=t.content,n.isStreaming=!1)}this.delegate.isLoading=!1,ae.getInstance().stopStreaming().catch(n=>{o.error("[MESSAGE HANDLER] Error in comprehensive stop:",n)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Pe();ms();Xe();tt();Us();je();ve();ke();import Ws from"terminal-link";import{homedir as tr}from"os";function Qn(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",tr())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function sr(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function ts(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,n)=>{let i=n;return!sr(n)&&!n.startsWith("file://")&&(n.startsWith("/")||n.startsWith("~")||/\.[a-z]{2,4}$/i.test(n))&&(i=Qn(n)),Ws(s,i,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return s.test(n)?t:Ws(t,t,{fallback:(i,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(s.test(n)||n.includes("http"))return t;let i=Qn(t);return Ws(t,i,{fallback:(r,a)=>r})}),e}import le from"react";import{Box as Tt,Text as He}from"ink";import nr from"ink-spinner";function ir(c,e){let t=c.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,i=e?.offset,r=e?.limit,a=n||void 0;if(n&&(i!==void 0||r!==void 0)){let l=i||0,u=r?l+r:"end";a=`${n} (lines ${l}-${u})`}return{title:"Reading file",details:a}}if(t==="write"||t==="writefile"){let n=e?.file_path,i=e?.content,r=n;if(i&&n){let a=i.split(`
510
+ `),i+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=i}t.isStreaming=!1;let n=this.delegate.fullConversationHistory.find(i=>i.isStreaming);n&&(n.content=t.content,n.isStreaming=!1)}this.delegate.isLoading=!1,ae.getInstance().stopStreaming().catch(n=>{o.error("[MESSAGE HANDLER] Error in comprehensive stop:",n)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Pe();ps();Xe();tt();Ls();je();ve();ke();import Us from"terminal-link";import{homedir as tr}from"os";function Kn(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",tr())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function sr(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function ts(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,s,n)=>{let i=n;return!sr(n)&&!n.startsWith("file://")&&(n.startsWith("/")||n.startsWith("~")||/\.[a-z]{2,4}$/i.test(n))&&(i=Kn(n)),Us(s,i,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return s.test(n)?t:Us(t,t,{fallback:(i,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let s=/\x1b\]8;;/,n=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(s.test(n)||n.includes("http"))return t;let i=Kn(t);return Us(t,i,{fallback:(r,a)=>r})}),e}import le from"react";import{Box as Tt,Text as He}from"ink";import nr from"ink-spinner";function ir(c,e){let t=c.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,i=e?.offset,r=e?.limit,a=n||void 0;if(n&&(i!==void 0||r!==void 0)){let l=i||0,u=r?l+r:"end";a=`${n} (lines ${l}-${u})`}return{title:"Reading file",details:a}}if(t==="write"||t==="writefile"){let n=e?.file_path,i=e?.content,r=n;if(i&&n){let a=i.split(`
511
511
  `).length;r=`${n} (${a} lines)`}return{title:"Writing file",details:r}}if(t==="edit"||t==="editfile"){let n=e?.file_path,i=e?.old_string,r=e?.new_string,a=n;if(n&&i&&r&&i.length<50&&r.length<50){let l=i.replace(/\n/g,"\\n").substring(0,45),u=r.replace(/\n/g,"\\n").substring(0,45);a=`${n}
512
512
  "${l}" → "${u}"`}return{title:"Editing file",details:a}}if(t==="grep"){let n=e?.pattern,i=e?.path,r=e?.glob,a=e?.type,l=n?`Pattern: ${n}`:"Searching...";return i&&(l+=`
513
513
  In: ${i}`),r&&(l+=` (${r})`),a&&(l+=` [${a} files]`),{title:"Searching content",details:l}}if(t==="glob"){let n=e?.pattern,i=e?.path,r=n?`Pattern: ${n}`:"Finding files...";return i&&i!=="."&&(r+=`
514
- In: ${i}`),{title:"Finding files",details:r}}if(t==="webfetch"||t==="web_fetch")return{title:"Fetching URL",details:e?.url};if(t==="task"){let n=e?.description,i=e?.prompt,r=n||i;return{title:"Running agent",details:r?r.length>60?r.substring(0,57)+"...":r: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:c}}function Jn({tool:c}){let{title:e,details:t}=ir(c.name,c.arguments);return le.createElement(Tt,{flexDirection:"column"},le.createElement(Tt,null,c.state==="running"?le.createElement(He,{color:"cyan"},le.createElement(nr,{type:"dots"})):c.state==="completed"?le.createElement(He,{color:"#5AD8A6"},"[done]"):le.createElement(He,{color:"#F5716C"},"[fail]"),le.createElement(He,null," "),le.createElement(He,{color:"whiteBright"},e)),t&&le.createElement(Tt,{flexDirection:"column",marginLeft:2},t.split(`
515
- `).map((n,i)=>le.createElement(Tt,{key:i},le.createElement(He,{color:"#6B7280"},n)))))}function Yn({activeTools:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([i,r])=>r.name.toLowerCase()!=="todowrite");if(e.length===0)return null;let t=e.filter(([i,r])=>r.state==="running"),s=e.filter(([i,r])=>r.state==="completed"),n=s.slice(-2);return le.createElement(Tt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1},t.map(([i,r])=>le.createElement(Jn,{key:i,tool:r})),n.map(([i,r])=>le.createElement(Jn,{key:i,tool:r})),s.length>2&&le.createElement(He,{color:"#6B7280"}," +",s.length-2," more"))}import G from"react";import{Box as Re,Text as ie}from"ink";import Zn from"ink-spinner";function or(c,e=60){return c?c.length<=e?c:c.substring(0,e-3)+"...":"Processing..."}function rr({agent:c}){let e=or(c.task||"Working..."),t=i=>{switch(i){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},s=()=>c.status==="running"?G.createElement(ie,{color:"cyan"},G.createElement(Zn,{type:"dots"})):c.status==="completed"?G.createElement(ie,{color:"#5AD8A6"},"[done]"):c.status==="failed"?G.createElement(ie,{color:"#F5716C"},"[fail]"):c.status==="timeout"?G.createElement(ie,{color:"#FBBF24"},"[time]"):G.createElement(ie,{color:"#6B7280"},"[ ]"),n=t(c.status);return G.createElement(Re,{flexDirection:"column",marginLeft:2},G.createElement(Re,null,s(),G.createElement(ie,{color:n,bold:!0}," Agent #",c.agentNumber)),G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#9CA3AF"},e)),c.error&&G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#F5716C"},"Error: ",c.error.substring(0,60),c.error.length>60?"...":"")),c.streamingContent&&c.status==="running"&&G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#6B7280"},c.streamingContent.split(`
516
- `)[0]?.substring(0,50),"...")))}function ar({operation:c}){let e=Array.from(c.agents.values()).sort((u,d)=>u.agentNumber-d.agentNumber),t=e.filter(u=>u.status==="completed").length,s=e.filter(u=>u.status==="failed").length,n=e.filter(u=>u.status==="running").length,i=c.totalAgents,r=()=>c.status==="starting"||c.status==="running"?`Spawning ${i} agents`:c.status==="completed"?`${i} agents completed`:"Operation failed",a=()=>c.status==="running"||c.status==="starting"?G.createElement(ie,{color:"cyan"},G.createElement(Zn,{type:"dots"})):c.status==="completed"?G.createElement(ie,{color:"#5AD8A6"},"[done]"):G.createElement(ie,{color:"#F5716C"},"[fail]"),l=c.status==="completed"?"#5AD8A6":c.status==="failed"?"#F5716C":"cyan";return G.createElement(Re,{flexDirection:"column"},G.createElement(Re,null,a(),G.createElement(ie,{color:l,bold:!0}," ",r()),G.createElement(ie,{color:"#6B7280"}," "),G.createElement(ie,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",t,"/",i," "),n>0&&G.createElement(ie,{color:"cyan"}," (",n," running)"),s>0&&G.createElement(ie,{color:"#F5716C"}," [",s," failed]")),G.createElement(Re,{flexDirection:"column",marginTop:1},e.map(u=>G.createElement(rr,{key:u.agentNumber,agent:u}))))}function ei({operations:c}){if(c.size===0)return null;let e=Array.from(c.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:G.createElement(Re,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,s])=>G.createElement(ar,{key:t,operation:s})))}fs();var pr=0;function Y(){return`msg-${Date.now()}-${++pr}`}function mr(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],s;for(;(s=e.exec(c))!==null;){let r=s[1].split(`
517
- `).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());r.length>0&&t.push({options:r})}let n=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return n=n.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:n}}function gr(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],s=new Set,n;for(;(n=e.exec(c))!==null;){let r=n[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],d=l[2];s.has(d)||(s.add(d),t.push({name:u,path:d}))}}let i=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return i=i.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:i}}var ai={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".tiff":"image/tiff",".tif":"image/tiff",".avif":"image/avif",".heic":"image/heic",".heif":"image/heif"},ci=Object.keys(ai),hr=[...ci,".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".mkv",".ttf",".otf",".woff",".woff2",".bin",".dat",".db",".sqlite"],ii=20*1024*1024,oi=1*1024*1024;function rt(c){return c<1024?`${c}B`:c<1024*1024?`${(c/1024).toFixed(1)}KB`:`${(c/(1024*1024)).toFixed(1)}MB`}function ri(c,e=30){if(c.length<=e)return c;let t=he.extname(c);return he.basename(c,t).slice(0,e-t.length-3)+"..."+t}function fr(c){let e=c.trim();if(e.startsWith("file://")){e=e.replace("file://","");try{e=decodeURIComponent(e)}catch{}}if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e=e.replace(/\\ /g," "),e.includes(`
518
- `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),s=/^[A-Za-z]:[\\\/]/.test(e),n=e.startsWith("./")||e.startsWith("../"),i=e.startsWith("~/");if(!(t||s||n||i))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),l=he.extname(a),u=ci.includes(l),d=hr.includes(l);return{isFilePath:!0,isImage:u,isBinary:d,path:e}}function vr(c){return c.startsWith("~/")?he.join(dr.homedir(),c.slice(2)):c}function qs(c){let e=vr(c);return he.isAbsolute(e)?e:he.resolve(process.cwd(),e)}function zs(c){try{let e=qs(c),t=Hs.statSync(e);return t.isFile()?{exists:!0,size:t.size}:{exists:!1,size:0,error:"Not a file"}}catch(e){return e.code==="ENOENT"?{exists:!1,size:0,error:"File not found"}:e.code==="EACCES"?{exists:!1,size:0,error:"Permission denied"}:{exists:!1,size:0,error:e.message}}}async function br(c){try{let e=qs(c),t=zs(c);if(!t.exists)return{data:null,error:t.error};if(t.size>ii)return{data:null,error:`Image too large (${rt(t.size)}, max ${rt(ii)})`};let s=Hs.readFileSync(e),n=he.extname(c).toLowerCase(),i=ai[n]||"image/png",r=s.toString("base64");return{data:`data:${i};base64,${r}`}}catch(e){return{data:null,error:e.message}}}function Tr(c){try{let e=qs(c),t=zs(c);return t.exists?t.size>oi?{content:null,error:`File too large (${rt(t.size)}, max ${rt(oi)})`}:{content:Hs.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}function li({initialProjectPath:c}={}){let e=c||process.cwd(),{exit:t}=ur(),s=X.getInstance(),n=ae.getInstance(),i=Ce.getInstance(),r=ee.getInstance(),a=ot.getInstance(),l=dt.getInstance();qe(()=>(U.enableCustomUI(),()=>U.disableCustomUI()),[]);let[u,d]=ti({messages:[{id:Y(),role:"system",content:`Welcome to Orion
514
+ In: ${i}`),{title:"Finding files",details:r}}if(t==="webfetch"||t==="web_fetch")return{title:"Fetching URL",details:e?.url};if(t==="task"){let n=e?.description,i=e?.prompt,r=n||i;return{title:"Running agent",details:r?r.length>60?r.substring(0,57)+"...":r: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:c}}function Qn({tool:c}){let{title:e,details:t}=ir(c.name,c.arguments);return le.createElement(Tt,{flexDirection:"column"},le.createElement(Tt,null,c.state==="running"?le.createElement(He,{color:"cyan"},le.createElement(nr,{type:"dots"})):c.state==="completed"?le.createElement(He,{color:"#5AD8A6"},"[done]"):le.createElement(He,{color:"#F5716C"},"[fail]"),le.createElement(He,null," "),le.createElement(He,{color:"whiteBright"},e)),t&&le.createElement(Tt,{flexDirection:"column",marginLeft:2},t.split(`
515
+ `).map((n,i)=>le.createElement(Tt,{key:i},le.createElement(He,{color:"#6B7280"},n)))))}function Jn({activeTools:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([i,r])=>r.name.toLowerCase()!=="todowrite");if(e.length===0)return null;let t=e.filter(([i,r])=>r.state==="running"),s=e.filter(([i,r])=>r.state==="completed"),n=s.slice(-2);return le.createElement(Tt,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1},t.map(([i,r])=>le.createElement(Qn,{key:i,tool:r})),n.map(([i,r])=>le.createElement(Qn,{key:i,tool:r})),s.length>2&&le.createElement(He,{color:"#6B7280"}," +",s.length-2," more"))}import G from"react";import{Box as Re,Text as ie}from"ink";import Yn from"ink-spinner";function or(c,e=60){return c?c.length<=e?c:c.substring(0,e-3)+"...":"Processing..."}function rr({agent:c}){let e=or(c.task||"Working..."),t=i=>{switch(i){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},s=()=>c.status==="running"?G.createElement(ie,{color:"cyan"},G.createElement(Yn,{type:"dots"})):c.status==="completed"?G.createElement(ie,{color:"#5AD8A6"},"[done]"):c.status==="failed"?G.createElement(ie,{color:"#F5716C"},"[fail]"):c.status==="timeout"?G.createElement(ie,{color:"#FBBF24"},"[time]"):G.createElement(ie,{color:"#6B7280"},"[ ]"),n=t(c.status);return G.createElement(Re,{flexDirection:"column",marginLeft:2},G.createElement(Re,null,s(),G.createElement(ie,{color:n,bold:!0}," Agent #",c.agentNumber)),G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#9CA3AF"},e)),c.error&&G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#F5716C"},"Error: ",c.error.substring(0,60),c.error.length>60?"...":"")),c.streamingContent&&c.status==="running"&&G.createElement(Re,{marginLeft:2},G.createElement(ie,{color:"#6B7280"},c.streamingContent.split(`
516
+ `)[0]?.substring(0,50),"...")))}function ar({operation:c}){let e=Array.from(c.agents.values()).sort((u,d)=>u.agentNumber-d.agentNumber),t=e.filter(u=>u.status==="completed").length,s=e.filter(u=>u.status==="failed").length,n=e.filter(u=>u.status==="running").length,i=c.totalAgents,r=()=>c.status==="starting"||c.status==="running"?`Spawning ${i} agents`:c.status==="completed"?`${i} agents completed`:"Operation failed",a=()=>c.status==="running"||c.status==="starting"?G.createElement(ie,{color:"cyan"},G.createElement(Yn,{type:"dots"})):c.status==="completed"?G.createElement(ie,{color:"#5AD8A6"},"[done]"):G.createElement(ie,{color:"#F5716C"},"[fail]"),l=c.status==="completed"?"#5AD8A6":c.status==="failed"?"#F5716C":"cyan";return G.createElement(Re,{flexDirection:"column"},G.createElement(Re,null,a(),G.createElement(ie,{color:l,bold:!0}," ",r()),G.createElement(ie,{color:"#6B7280"}," "),G.createElement(ie,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",t,"/",i," "),n>0&&G.createElement(ie,{color:"cyan"}," (",n," running)"),s>0&&G.createElement(ie,{color:"#F5716C"}," [",s," failed]")),G.createElement(Re,{flexDirection:"column",marginTop:1},e.map(u=>G.createElement(rr,{key:u.agentNumber,agent:u}))))}function Zn({operations:c}){if(c.size===0)return null;let e=Array.from(c.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:G.createElement(Re,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,s])=>G.createElement(ar,{key:t,operation:s})))}hs();var dr=0;function Y(){return`msg-${Date.now()}-${++dr}`}function pr(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],s;for(;(s=e.exec(c))!==null;){let r=s[1].split(`
517
+ `).map(a=>a.trim()).filter(a=>a.length>0).map(a=>a.replace(/^Option\s+\d+:\s*/i,"").trim());r.length>0&&t.push({options:r})}let n=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return n=n.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:n}}function mr(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],s=new Set,n;for(;(n=e.exec(c))!==null;){let r=n[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],d=l[2];s.has(d)||(s.add(d),t.push({name:u,path:d}))}}let i=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return i=i.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:i}}var ai={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".tiff":"image/tiff",".tif":"image/tiff",".avif":"image/avif",".heic":"image/heic",".heif":"image/heif"},ci=Object.keys(ai),gr=[...ci,".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".mkv",".ttf",".otf",".woff",".woff2",".bin",".dat",".db",".sqlite"],ii=20*1024*1024,oi=1*1024*1024;function rt(c){return c<1024?`${c}B`:c<1024*1024?`${(c/1024).toFixed(1)}KB`:`${(c/(1024*1024)).toFixed(1)}MB`}function ri(c,e=30){if(c.length<=e)return c;let t=he.extname(c);return he.basename(c,t).slice(0,e-t.length-3)+"..."+t}function hr(c){let e=c.trim();if(e.startsWith("file://")){e=e.replace("file://","");try{e=decodeURIComponent(e)}catch{}}if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1)),e=e.replace(/\\ /g," "),e.includes(`
518
+ `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),s=/^[A-Za-z]:[\\\/]/.test(e),n=e.startsWith("./")||e.startsWith("../"),i=e.startsWith("~/");if(!(t||s||n||i))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),l=he.extname(a),u=ci.includes(l),d=gr.includes(l);return{isFilePath:!0,isImage:u,isBinary:d,path:e}}function fr(c){return c.startsWith("~/")?he.join(ur.homedir(),c.slice(2)):c}function Hs(c){let e=fr(c);return he.isAbsolute(e)?e:he.resolve(process.cwd(),e)}function qs(c){try{let e=Hs(c),t=Bs.statSync(e);return t.isFile()?{exists:!0,size:t.size}:{exists:!1,size:0,error:"Not a file"}}catch(e){return e.code==="ENOENT"?{exists:!1,size:0,error:"File not found"}:e.code==="EACCES"?{exists:!1,size:0,error:"Permission denied"}:{exists:!1,size:0,error:e.message}}}async function vr(c){try{let e=Hs(c),t=qs(c);if(!t.exists)return{data:null,error:t.error};if(t.size>ii)return{data:null,error:`Image too large (${rt(t.size)}, max ${rt(ii)})`};let s=Bs.readFileSync(e),n=he.extname(c).toLowerCase(),i=ai[n]||"image/png",r=s.toString("base64");return{data:`data:${i};base64,${r}`}}catch(e){return{data:null,error:e.message}}}function br(c){try{let e=Hs(c),t=qs(c);return t.exists?t.size>oi?{content:null,error:`File too large (${rt(t.size)}, max ${rt(oi)})`}:{content:Bs.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}function li({initialProjectPath:c}={}){let e=c||process.cwd(),{exit:t}=lr(),s=X.getInstance(),n=ae.getInstance(),i=Ce.getInstance(),r=ee.getInstance(),a=ot.getInstance(),l=dt.getInstance();qe(()=>(U.enableCustomUI(),()=>U.disableCustomUI()),[]);let[u,d]=ei({messages:[{id:Y(),role:"system",content:`Welcome to Orion
519
519
 
520
520
  Your autonomous on-device AI agent.
521
521
  Current project path: ${e}
522
522
 
523
- 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:Q.find(g=>g.name===Fe.string("selectedPersonalModel"))||Q.find(g=>g.name==="snowx-c5")||Q[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1,activeTools:new Map,subAgentOperations:new Map,pastedTexts:[],isProcessingFiles:!1}),m=ss(0),S=ss(null),w=ss(u.isLoading),T=ss(u.selectedModel);qe(()=>{w.current=u.isLoading,T.current=u.selectedModel},[u.isLoading,u.selectedModel]);let[I]=ti(()=>{let g={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:Q.find(N=>N.name===Fe.string("selectedPersonalModel"))||Q.find(N=>N.name==="snowx-c5")||Q[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new es(g)}),D=Bs(async()=>{},[]);qe(()=>{let g=u.messages.map(x=>({role:x.role,content:x.content,timestamp:new Date(x.timestamp||Date.now()),...x.tool&&{tool:x.tool},...x.toolOutput&&{toolOutput:x.toolOutput}})),N={messages:g,fullConversationHistory:g,isLoading:u.isLoading,currentInput:u.input,selectedModel:u.selectedModel,isVisionEnabled:u.isVisionEnabled,conversationId:u.conversationId,usesCustomUI:!0,updateCurrentConversation:D};I.setDelegate(N)},[u.messages,u.selectedModel,u.isVisionEnabled,u.isLoading,u.input,u.conversationId,I,D]);let y=Bs(async(g,N=[])=>{if(g.startsWith("/")){let b=g.toLowerCase().trim();if(b==="/help"||b==="/?"){d(f=>({...f,showCommandMenu:!0,input:""}));return}if(b==="/model"){d(f=>({...f,showModelMenu:!0,input:""}));return}if(b==="/clear"||b==="/new"){d(f=>({...f,messages:[{id:Y(),role:"system",content:`Welcome to Orion
523
+ 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:Q.find(g=>g.name===Fe.string("selectedPersonalModel"))||Q.find(g=>g.name==="snowx-c5")||Q[0],isVisionEnabled:!1,queuedMessages:[],todoList:null,conversationId:null,conversationTitleGenerated:!1,activeTools:new Map,subAgentOperations:new Map,pastedTexts:[],isProcessingFiles:!1}),m=ss(0),S=ss(null),w=ss(u.isLoading),T=ss(u.selectedModel);qe(()=>{w.current=u.isLoading,T.current=u.selectedModel},[u.isLoading,u.selectedModel]);let[I]=ei(()=>{let g={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:Q.find(N=>N.name===Fe.string("selectedPersonalModel"))||Q.find(N=>N.name==="snowx-c5")||Q[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new es(g)}),D=Ws(async()=>{},[]);qe(()=>{let g=u.messages.map(x=>({role:x.role,content:x.content,timestamp:new Date(x.timestamp||Date.now()),...x.tool&&{tool:x.tool},...x.toolOutput&&{toolOutput:x.toolOutput}})),N={messages:g,fullConversationHistory:g,isLoading:u.isLoading,currentInput:u.input,selectedModel:u.selectedModel,isVisionEnabled:u.isVisionEnabled,conversationId:u.conversationId,usesCustomUI:!0,updateCurrentConversation:D};I.setDelegate(N)},[u.messages,u.selectedModel,u.isVisionEnabled,u.isLoading,u.input,u.conversationId,I,D]);let y=Ws(async(g,N=[])=>{if(g.startsWith("/")){let b=g.toLowerCase().trim();if(b==="/help"||b==="/?"){d(f=>({...f,showCommandMenu:!0,input:""}));return}if(b==="/model"){d(f=>({...f,showModelMenu:!0,input:""}));return}if(b==="/clear"||b==="/new"){d(f=>({...f,messages:[{id:Y(),role:"system",content:`Welcome to Orion
524
524
 
525
525
  Your intelligent AI assistant.
526
526
  Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1,pastedTexts:[]}));return}if(b==="/vision"){d(f=>({...f,isVisionEnabled:!f.isVisionEnabled,messages:[...f.messages,{id:Y(),role:"system",content:`Vision mode ${f.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(b==="/exit"||b==="/quit"){t();return}if(b==="/stop"){u.isLoading?(n.stopStreaming(),d(f=>({...f,isLoading:!1,messages:[...f.messages,{id:Y(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):d(f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(b==="/signout"){d(f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:"[...] Signing out...",timestamp:Date.now()}],input:""}));try{await s.signOut()?(d($=>({...$,messages:[...$.messages,{id:Y(),role:"system",content:"[OK] Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>t(),1e3)):d($=>({...$,messages:[...$.messages,{id:Y(),role:"system",content:"[!] Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(f){d($=>({...$,messages:[...$.messages,{id:Y(),role:"system",content:`[ERROR] ${f.message}`,timestamp:Date.now()}]}))}return}d(f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:`Unknown command: ${g}
527
527
 
528
- Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(u.isLoading){let b=i.addToQueue({content:g,imageUrls:N,attachments:[],model:u.selectedModel.name});d(b?f=>({...f,input:""}):f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}],input:f.input}));return}let x=Date.now(),E={id:Y(),role:"user",content:g,timestamp:x},h={id:Y(),role:"assistant",content:"",timestamp:x+1},v=[...u.messages,E,h];d(b=>({...b,messages:v,input:"",isLoading:!0,loadingMessage:"Processing"}));let C=v.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}}));I.setDelegate({messages:C,fullConversationHistory:C,isLoading:!1,currentInput:"",selectedModel:u.selectedModel,isVisionEnabled:u.isVisionEnabled,conversationId:u.conversationId,usesCustomUI:!0,updateCurrentConversation:D});try{await I.sendMessage(g,N.length>0?N:void 0)}catch(b){d(f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:`Error: ${b.message}`,timestamp:Date.now()}],isLoading:!1}))}},[u.isLoading,u.isVisionEnabled,u.selectedModel,u.messages,u.conversationId,i,I,s,t,D,n]),A=Bs(()=>{if(!i.hasQueuedMessages())return;let g=i.processNextMessage();g&&(i.startProcessing(),y(g.content))},[i,y]);qe(()=>{let g="",N=!0,x=!1,E=!1,h=null,v=100,C=O=>{d(J=>({...J,conversationId:O.conversationId,conversationTitleGenerated:!!O.title}))},b=O=>{},f=()=>{d(O=>({...O,loadingMessage:"Processing"}))},$=()=>{if(h=null,E=!1,!x||!N)return;x=!1;let O=g;d(J=>{let te=J.messages.map((fe,De)=>fe.role==="assistant"&&!J.messages.slice(De+1).some(we=>we.role==="assistant")?{...fe,content:O}:fe);return{...J,messages:te}})},L=O=>{g+=O,x=!0,E||(E=!0,h=setTimeout($,v))},V=O=>{let J=typeof O=="string"?O:O.name,te=typeof O=="string"?`tool-${Date.now()}`:O.toolCallId,fe=typeof O=="string"?void 0:O.arguments;d(De=>{let se=new Map(De.activeTools);return se.set(te,{toolCallId:te,name:J,arguments:fe,startTime:new Date,state:"running"}),{...De,activeTools:se,loadingMessage:J}})},Z=O=>{if(O&&O.toolName){let J=O.toolId||`tool-${O.toolName}-${Date.now()}`,te="";O.result&&(typeof O.result=="string"?te=O.result:Array.isArray(O.result)?te=O.result.map(se=>typeof se=="string"?se:se&&typeof se=="object"?se.text||se.content||JSON.stringify(se):"").join(""):O.result.output?te=typeof O.result.output=="string"?O.result.output:JSON.stringify(O.result.output,null,2):O.result.content?te=O.result.content:te=JSON.stringify(O.result,null,2));let fe=te.length>500?te.substring(0,500)+`
528
+ Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(u.isLoading){let b=i.addToQueue({content:g,imageUrls:N,attachments:[],model:u.selectedModel.name});d(b?f=>({...f,input:""}):f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}],input:f.input}));return}let x=Date.now(),E={id:Y(),role:"user",content:g,timestamp:x},h={id:Y(),role:"assistant",content:"",timestamp:x+1},v=[...u.messages,E,h];d(b=>({...b,messages:v,input:"",isLoading:!0,loadingMessage:"Processing"}));let C=v.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}}));I.setDelegate({messages:C,fullConversationHistory:C,isLoading:!1,currentInput:"",selectedModel:u.selectedModel,isVisionEnabled:u.isVisionEnabled,conversationId:u.conversationId,usesCustomUI:!0,updateCurrentConversation:D});try{await I.sendMessage(g,N.length>0?N:void 0)}catch(b){d(f=>({...f,messages:[...f.messages,{id:Y(),role:"system",content:`Error: ${b.message}`,timestamp:Date.now()}],isLoading:!1}))}},[u.isLoading,u.isVisionEnabled,u.selectedModel,u.messages,u.conversationId,i,I,s,t,D,n]),A=Ws(()=>{if(!i.hasQueuedMessages())return;let g=i.processNextMessage();g&&(i.startProcessing(),y(g.content))},[i,y]);qe(()=>{let g="",N=!0,x=!1,E=!1,h=null,v=100,C=O=>{d(J=>({...J,conversationId:O.conversationId,conversationTitleGenerated:!!O.title}))},b=O=>{},f=()=>{d(O=>({...O,loadingMessage:"Processing"}))},$=()=>{if(h=null,E=!1,!x||!N)return;x=!1;let O=g;d(J=>{let te=J.messages.map((fe,De)=>fe.role==="assistant"&&!J.messages.slice(De+1).some(we=>we.role==="assistant")?{...fe,content:O}:fe);return{...J,messages:te}})},L=O=>{g+=O,x=!0,E||(E=!0,h=setTimeout($,v))},V=O=>{let J=typeof O=="string"?O:O.name,te=typeof O=="string"?`tool-${Date.now()}`:O.toolCallId,fe=typeof O=="string"?void 0:O.arguments;d(De=>{let se=new Map(De.activeTools);return se.set(te,{toolCallId:te,name:J,arguments:fe,startTime:new Date,state:"running"}),{...De,activeTools:se,loadingMessage:J}})},Z=O=>{if(O&&O.toolName){let J=O.toolId||`tool-${O.toolName}-${Date.now()}`,te="";O.result&&(typeof O.result=="string"?te=O.result:Array.isArray(O.result)?te=O.result.map(se=>typeof se=="string"?se:se&&typeof se=="object"?se.text||se.content||JSON.stringify(se):"").join(""):O.result.output?te=typeof O.result.output=="string"?O.result.output:JSON.stringify(O.result.output,null,2):O.result.content?te=O.result.content:te=JSON.stringify(O.result,null,2));let fe=te.length>500?te.substring(0,500)+`
529
529
  ...(truncated)`:te,De=`<context>
530
530
  ${te}
531
531
  </context>`;d(se=>{let we=new Map(se.activeTools),Ge=J;if(!we.has(J)){for(let[Ae,wt]of we.entries())if(wt.name===O.toolName&&wt.state==="running"){Ge=Ae;break}}if(we.has(Ge)){let Ae=we.get(Ge);we.set(Ge,{...Ae,state:"completed",output:fe})}else we.set(Ge,{toolCallId:Ge,name:O.toolName,arguments:void 0,startTime:new Date,state:"completed",output:fe});let Si=se.messages.map((Ae,wt)=>{if(Ae.role==="assistant"&&!se.messages.slice(wt+1).some(St=>St.role==="assistant")){let St=Ae.metadata?.toolResults;return{...Ae,metadata:{...Ae.metadata,toolResults:St?St+`
532
- `+De:De}}}return Ae});return{...se,messages:Si,activeTools:we}})}},me=()=>{if(x){x=!1,E=!1;let O=g;d(J=>{let te=J.messages.map((fe,De)=>fe.role==="assistant"&&!J.messages.slice(De+1).some(we=>we.role==="assistant")?{...fe,content:O}:fe);return{...J,messages:te,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}})}else d(O=>({...O,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}));g=""},j=O=>{d(J=>({...J,messages:[...J.messages,{id:Y(),role:"system",content:`Error: ${O.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map})),g=""};return n.on("conversation_id_received",C),n.on("conversation_title_updated",b),n.on("thinking",f),n.on("data",L),n.on("toolExecuting",V),n.on("tool_completed",Z),n.on("done",me),n.on("error",j),()=>{N=!1,h&&(clearTimeout(h),h=null),n.off("conversation_id_received",C),n.off("conversation_title_updated",b),n.off("thinking",f),n.off("data",L),n.off("toolExecuting",V),n.off("tool_completed",Z),n.off("done",me),n.off("error",j)}},[n,A]),qe(()=>{let g=h=>{d(v=>({...v,queuedMessages:h}))},N=h=>{},x=h=>{S.current=h,d(v=>({...v,todoList:h}))},E=h=>{if(w.current){i.addToQueue({content:h.prompt,imageUrls:[],attachments:[],model:T.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:h.taskId})||d(C=>({...C,messages:[...C.messages,{id:Y(),role:"system",content:"[!] Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}y(h.prompt)};return i.on("queue:updated",g),r.on("feedback:sent",N),n.on("todo_update",x),a.on("CrossDeviceTaskSendMessage",E),()=>{i.off("queue:updated",g),r.off("feedback:sent",N),n.off("todo_update",x),a.off("CrossDeviceTaskSendMessage",E)}},[i,r,n,a,y]),qe(()=>{let g=()=>{let N=l.getOperations();d(x=>({...x,subAgentOperations:new Map(N)}))};return l.on("spawn_started",g),l.on("agent_started",g),l.on("agent_streaming",g),l.on("agent_completed",g),l.on("spawn_completed",g),l.on("progress",g),()=>{l.off("spawn_started",g),l.off("agent_started",g),l.off("agent_streaming",g),l.off("agent_completed",g),l.off("spawn_completed",g),l.off("progress",g)}},[l]),qe(()=>{!u.isLoading&&i.hasQueuedMessages()&&A()},[u.isLoading,i,A]),lr((g,N)=>{if(N.escape){if(u.isLoading){n.stopStreaming(),d(x=>({...x,isLoading:!1,messages:[...x.messages,{id:Y(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(u.showModelMenu||u.showCommandMenu){d(x=>({...x,showModelMenu:!1,showCommandMenu:!1,input:x.showCommandMenu&&x.input==="/"?"":x.input}));return}if(u.showHelp){d(x=>({...x,showHelp:!1}));return}if(u.pastedTexts.length>0){d(x=>({...x,pastedTexts:[]}));return}}if(!u.showModelMenu){if(N.ctrl&&g==="l"){process.stdout.write("\x1B[2J\x1B[H");return}if(N.ctrl&&g==="c"){u.isLoading?(n.stopStreaming(),d(x=>({...x,isLoading:!1,messages:[...x.messages,{id:Y(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):t();return}if(g==="?"&&u.input===""){d(x=>({...x,showHelp:!x.showHelp}));return}if(N.return&&!u.showCommandMenu){let x=u.pastedTexts.filter(b=>b.type==="image_path"&&b.filePath),E=u.pastedTexts.filter(b=>b.type==="file_path"&&b.filePath),h=u.pastedTexts.filter(b=>b.type==="text"),v=u.pastedTexts.filter(b=>!b.error||b.type==="text");(u.input.trim()||v.length>0)&&(d(b=>({...b,pastedTexts:[],isProcessingFiles:v.length>0})),(async()=>{let b=[],f=[],$=[];for(let j of E)if(j.filePath&&!j.error){let O=Tr(j.filePath);if(O.content){let J=he.basename(j.filePath),te=he.extname(J).slice(1)||"text";f.push(`[File: ${J}]
532
+ `+De:De}}}return Ae});return{...se,messages:Si,activeTools:we}})}},me=()=>{if(x){x=!1,E=!1;let O=g;d(J=>{let te=J.messages.map((fe,De)=>fe.role==="assistant"&&!J.messages.slice(De+1).some(we=>we.role==="assistant")?{...fe,content:O}:fe);return{...J,messages:te,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}})}else d(O=>({...O,isLoading:!1,activeTools:new Map,subAgentOperations:new Map}));g=""},j=O=>{d(J=>({...J,messages:[...J.messages,{id:Y(),role:"system",content:`Error: ${O.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map})),g=""};return n.on("conversation_id_received",C),n.on("conversation_title_updated",b),n.on("thinking",f),n.on("data",L),n.on("toolExecuting",V),n.on("tool_completed",Z),n.on("done",me),n.on("error",j),()=>{N=!1,h&&(clearTimeout(h),h=null),n.off("conversation_id_received",C),n.off("conversation_title_updated",b),n.off("thinking",f),n.off("data",L),n.off("toolExecuting",V),n.off("tool_completed",Z),n.off("done",me),n.off("error",j)}},[n]),qe(()=>{let g=h=>{d(v=>({...v,queuedMessages:h}))},N=h=>{},x=h=>{S.current=h,d(v=>({...v,todoList:h}))},E=h=>{if(w.current){i.addToQueue({content:h.prompt,imageUrls:[],attachments:[],model:T.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:h.taskId})||d(C=>({...C,messages:[...C.messages,{id:Y(),role:"system",content:"[!] Message queue is full - cross-device task rejected",timestamp:Date.now()}]}));return}y(h.prompt)};return i.on("queue:updated",g),r.on("feedback:sent",N),n.on("todo_update",x),a.on("CrossDeviceTaskSendMessage",E),()=>{i.off("queue:updated",g),r.off("feedback:sent",N),n.off("todo_update",x),a.off("CrossDeviceTaskSendMessage",E)}},[i,r,n,a,y]),qe(()=>{let g=()=>{let N=l.getOperations();d(x=>({...x,subAgentOperations:new Map(N)}))};return l.on("spawn_started",g),l.on("agent_started",g),l.on("agent_streaming",g),l.on("agent_completed",g),l.on("spawn_completed",g),l.on("progress",g),()=>{l.off("spawn_started",g),l.off("agent_started",g),l.off("agent_streaming",g),l.off("agent_completed",g),l.off("spawn_completed",g),l.off("progress",g)}},[l]),qe(()=>{!u.isLoading&&i.hasQueuedMessages()&&A()},[u.isLoading,i,A]),cr((g,N)=>{if(N.escape){if(u.isLoading){n.stopStreaming(),d(x=>({...x,isLoading:!1,messages:[...x.messages,{id:Y(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(u.showModelMenu||u.showCommandMenu){d(x=>({...x,showModelMenu:!1,showCommandMenu:!1,input:x.showCommandMenu&&x.input==="/"?"":x.input}));return}if(u.showHelp){d(x=>({...x,showHelp:!1}));return}if(u.pastedTexts.length>0){d(x=>({...x,pastedTexts:[]}));return}}if(!u.showModelMenu){if(N.ctrl&&g==="l"){process.stdout.write("\x1B[2J\x1B[H");return}if(N.ctrl&&g==="c"){u.isLoading?(n.stopStreaming(),d(x=>({...x,isLoading:!1,messages:[...x.messages,{id:Y(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):t();return}if(g==="?"&&u.input===""){d(x=>({...x,showHelp:!x.showHelp}));return}if(N.return&&!u.showCommandMenu){let x=u.pastedTexts.filter(b=>b.type==="image_path"&&b.filePath),E=u.pastedTexts.filter(b=>b.type==="file_path"&&b.filePath),h=u.pastedTexts.filter(b=>b.type==="text"),v=u.pastedTexts.filter(b=>!b.error||b.type==="text");(u.input.trim()||v.length>0)&&(d(b=>({...b,pastedTexts:[],isProcessingFiles:v.length>0})),(async()=>{let b=[],f=[],$=[];for(let j of E)if(j.filePath&&!j.error){let O=br(j.filePath);if(O.content){let J=he.basename(j.filePath),te=he.extname(J).slice(1)||"text";f.push(`[File: ${J}]
533
533
  \`\`\`${te}
534
534
  ${O.content}
535
- \`\`\``)}else O.error&&$.push(`${he.basename(j.filePath)}: ${O.error}`)}for(let j of x)if(j.filePath&&!j.error){let O=await br(j.filePath);O.data?b.push(O.data):O.error&&$.push(`${he.basename(j.filePath)}: ${O.error}`)}let L=h.map(j=>j.content).join(`
535
+ \`\`\``)}else O.error&&$.push(`${he.basename(j.filePath)}: ${O.error}`)}for(let j of x)if(j.filePath&&!j.error){let O=await vr(j.filePath);O.data?b.push(O.data):O.error&&$.push(`${he.basename(j.filePath)}: ${O.error}`)}let L=h.map(j=>j.content).join(`
536
536
 
537
537
  `),V=f.join(`
538
538
 
@@ -543,14 +543,14 @@ ${$.map(O=>` - ${O}`).join(`
543
543
  `)}`,timestamp:Date.now()}]}));return}let me=Z?u.input.trim()?`${Z}
544
544
 
545
545
  ${u.input}`:Z:u.input;y(me.trim()||"Please analyze this image.",b)})());return}if(N.delete||N.backspace){d(x=>{if(x.input===""&&x.pastedTexts.length>0)return{...x,pastedTexts:x.pastedTexts.slice(0,-1)};let E=x.input.slice(0,-1);return x.showCommandMenu&&!E.startsWith("/")?{...x,input:E,showCommandMenu:!1}:{...x,input:E}});return}if(!N.ctrl&&!N.meta&&g){let x=g.includes(`
546
- `),E=g.length>100;if(x||E){let h=fr(g),C=g.split(`
547
- `).length;d(b=>{m.current+=1;let f="text",$,L;if(h.isFilePath){h.isImage?f="image_path":h.isBinary?(f="file_path",L="Binary file - cannot read as text"):f="file_path";let Z=zs(h.path);Z.exists?$=Z.size:L=Z.error}let V={id:m.current,content:g,lineCount:C,type:f,filePath:h.isFilePath?h.path:void 0,fileSize:$,error:L};return{...b,pastedTexts:[...b.pastedTexts,V]}});return}d(h=>{let v=h.input+g;return v==="/"&&!h.showCommandMenu?{...h,input:v,showCommandMenu:!0}:{...h,input:v}})}}});let _=s.getUserEmail()||"User",P=ge.getDisplayName(ge.getCurrentUserTier()),F=ns(()=>u.queuedMessages.filter(g=>g.isCrossDeviceTask),[u.queuedMessages]),H=ns(()=>u.queuedMessages.filter(g=>!g.isCrossDeviceTask),[u.queuedMessages]);return p.createElement(R,{flexDirection:"column",width:"100%"},p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,width:"100%"},p.createElement(k,{color:"whiteBright"},u.selectedModel.displayName),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"#9CA3AF"},_),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"whiteBright"},P),u.queuedMessages.length>0&&p.createElement(p.Fragment,null,p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{backgroundColor:"#3F3F46",color:"whiteBright",bold:!0}," ",u.queuedMessages.length," "),p.createElement(k,{color:"#9CA3AF"}," queued")),F.length>0&&p.createElement(p.Fragment,null,p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{backgroundColor:"#0E7490",color:"whiteBright",bold:!0}," [mobile] ",F.length," "),p.createElement(k,{color:"#9CA3AF"}," cross-device"))),p.createElement(R,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},u.messages.map(g=>p.createElement(Cr,{key:g.id,message:g,onSuggestionClick:N=>{d(x=>({...x,input:N}))}}))),u.todoList&&u.todoList.todos.length>0&&u.todoList.todos.some(g=>g.status!=="completed")&&(()=>{let N=u.todoList.todos.filter(v=>v.status!=="completed"),x=u.todoList.todos.filter(v=>v.status==="completed"),E=[...N,...x.slice(-2)].slice(0,8),h=u.todoList.todos.length-E.length;return p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(R,{marginBottom:1},p.createElement(k,{color:"whiteBright",bold:!0},"Tasks"),p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{color:"#9CA3AF"},x.length,"/",u.todoList.todos.length)),E.map((v,C)=>{let b=v.status==="completed"?"[done]":v.status==="in_progress"?"[..]":"[ ]",f=v.status==="completed"?"#5AD8A6":v.status==="in_progress"?"cyan":"#6B7280";return p.createElement(R,{key:v.id||C},p.createElement(k,{color:f},b),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:v.status==="completed"?"#6B7280":"whiteBright"},v.status==="in_progress"&&v.activeForm?v.activeForm:v.text))}),h>0&&p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"}," +",h," more tasks"))))})(),u.activeTools.size>0&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(Yn,{activeTools:u.activeTools})),u.subAgentOperations.size>0&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(ei,{operations:u.subAgentOperations})),u.isProcessingFiles&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(k,{color:"cyan"},p.createElement(si,{type:"dots"})),p.createElement(k,{color:"whiteBright"}," Reading files...")),u.isLoading&&u.activeTools.size===0&&!u.isProcessingFiles&&p.createElement(R,{paddingX:0,marginBottom:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"cyan"},p.createElement(si,{type:"dots"})),p.createElement(k,{color:"whiteBright"}," ",u.loadingMessage,"... "),p.createElement(k,{color:"#9CA3AF"},"(esc to interrupt)")),p.createElement(R,{marginLeft:2},p.createElement(k,{color:"#FBBF24"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),u.showHelp&&p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),p.createElement(R,{marginTop:1,flexDirection:"column"},p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Enter")," ",p.createElement(k,{color:"#9CA3AF"},"Submit message")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"?")," ",p.createElement(k,{color:"#9CA3AF"},"Toggle this help")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Esc")," ",p.createElement(k,{color:"#9CA3AF"},"Stop generation / Close menus")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Ctrl+C")," ",p.createElement(k,{color:"#9CA3AF"},"Stop generation / Exit"))),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Press Esc to close"))),u.showModelMenu&&(()=>{let g=ge.getCurrentUserTier(),N=f=>{switch(f){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},x=Q.filter(f=>f.name.startsWith("snowx-o4")||f.name.startsWith("snowx-c")||f.name.startsWith("snowx-h")),E=Q.filter(f=>f.name.startsWith("snowx-5")||f.name.startsWith("snowx-o3")||f.name.startsWith("snowx-4")),h=Q.filter(f=>f.name.startsWith("snowx-g")),v=f=>f.map($=>{let L=ge.isModelAccessible($.name,g),V=N($.creditMultiplier);return{label:`${L?"":"[LOCKED] "}${$.displayName} ${V}`,value:$.name,isAccessible:L,creditMultiplier:$.creditMultiplier,isHeader:!1}}),C=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(x),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(E),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(h)],b=C.filter(f=>!f.isHeader);return p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Select Model"),p.createElement(R,null,p.createElement(k,{color:"#6B7280"},"Tier: ",ge.getDisplayName(g)," - "),p.createElement(k,{color:"#5AD8A6"},"[0.5x]"),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:"#9CA3AF"},"[1x]"),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:"#FBBF24"},"[2x]"),p.createElement(k,{color:"#6B7280"}," credits")),p.createElement(R,{marginTop:1},p.createElement(ni,{items:b.map(f=>({label:f.label,value:f.value})),onSelect:f=>{if(f.value.startsWith("_"))return;if(!C.find(V=>V.value===f.value)?.isAccessible){d(V=>({...V,messages:[...V.messages,{id:Y(),role:"system",content:ge.getAccessDeniedMessage(f.value),timestamp:Date.now()}]}));return}let L=Q.find(V=>V.name===f.value);L&&(Fe.set("selectedPersonalModel",L.name),d(V=>({...V,selectedModel:L,showModelMenu:!1,messages:[...V.messages,{id:Y(),role:"system",content:`Switched to ${L.displayName}`,timestamp:Date.now()}]})))}})),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Esc to cancel")))})(),u.showCommandMenu&&(()=>{let g=[{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"}],N=u.input.startsWith("/")?u.input.substring(1).toLowerCase():"",x=N?g.filter(E=>E.value.toLowerCase().includes(N)):g;return p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Available Commands ",N&&`(filtered: "${N}")`),p.createElement(R,{marginTop:1},p.createElement(ni,{items:x.length>0?x:[{label:"No matching commands",value:""}],onSelect:E=>{E.value&&(d(h=>({...h,showCommandMenu:!1,input:""})),y(`/${E.value}`))}})),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Esc to cancel")))})(),H.length>0&&p.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},H.map((g,N)=>p.createElement(R,{key:g.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},p.createElement(R,null,p.createElement(k,{color:"whiteBright",bold:!0},N+1),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"#9CA3AF"},g.content.length>60?g.content.substring(0,60)+"...":g.content)))),p.createElement(R,null,p.createElement(k,{color:"#9CA3AF"},H.length," message",H.length>1?"s":""," queued"))),F.length>0&&p.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},F.map((g,N)=>p.createElement(R,{key:`cross-${g.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},p.createElement(R,null,p.createElement(k,{color:"#22D3EE",bold:!0},"[M] ",N+1),p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{color:"#9CA3AF"},g.content.length>60?g.content.substring(0,60)+"...":g.content)))),p.createElement(R,null,p.createElement(k,{color:"#22D3EE"},F.length," cross-device task",F.length>1?"s":""," waiting"))),p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},u.pastedTexts.length>0&&p.createElement(R,{flexDirection:"column",marginBottom:0},u.pastedTexts.map((g,N)=>{if(g.type==="image_path"&&g.filePath){let h=ri(he.basename(g.filePath)),v=g.fileSize?` ${rt(g.fileSize)}`:"",C=!!g.error;return p.createElement(R,{key:`pasted-${g.id}`,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:C?"#EF4444":"#22D3EE"}," ","[IMG] "),p.createElement(k,{color:C?"#EF4444":"#9CA3AF"},h),v&&p.createElement(k,{color:"#6B7280"},v)),C&&p.createElement(R,{marginLeft:4},p.createElement(k,{color:"#EF4444",dimColor:!0},"[!] ",g.error)))}if(g.type==="file_path"&&g.filePath){let h=ri(he.basename(g.filePath)),v=g.fileSize?` ${rt(g.fileSize)}`:"",C=!!g.error;return p.createElement(R,{key:`pasted-${g.id}`,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:C?"#EF4444":"#22D3EE"}," ","[FILE] "),p.createElement(k,{color:C?"#EF4444":"#9CA3AF"},h),v&&p.createElement(k,{color:"#6B7280"},v)),C&&p.createElement(R,{marginLeft:4},p.createElement(k,{color:"#EF4444",dimColor:!0},"[!] ",g.error)))}let x=g.lineCount-1,E=x>0?`+${x} lines`:"1 line";return p.createElement(R,{key:`pasted-${g.id}`},p.createElement(k,{color:"#6B7280"}," ","[TEXT] "),p.createElement(k,{color:"#9CA3AF"},"Pasted text #",N+1),p.createElement(k,{color:"#6B7280"}," (",E,")"))})),p.createElement(R,null,p.createElement(k,{color:"cyan"},"▶ "),p.createElement(k,{color:"whiteBright"},u.input,!u.isLoading&&p.createElement(k,{color:"whiteBright",inverse:!0}," "))),p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"},u.isLoading?"Send feedback or press Enter to queue · esc to stop":u.pastedTexts.length>0?"enter to submit with pasted content · esc to clear":"/help · ? · enter to submit"))),p.createElement(R,{paddingX:2,paddingY:0},p.createElement(k,{color:"#6B7280"},"? help · Ctrl+L refresh · Ctrl+C exit")))}function yr(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=ts(e),e}function wr({suggestions:c,onSelect:e}){return c.length===0?null:p.createElement(R,{flexDirection:"column",marginTop:1},c.map((t,s)=>p.createElement(R,{key:`sug-block-${s}`,flexWrap:"wrap",gap:1},t.options.map((n,i)=>p.createElement(R,{key:`sug-opt-${s}-${i}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},p.createElement(k,{color:"#22D3EE"},n))))),e&&p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"},"Type a suggestion to use it")))}function Sr({workingFiles:c}){return c.length===0?null:p.createElement(R,{flexDirection:"column",marginTop:1},p.createElement(R,{marginBottom:0},p.createElement(k,{color:"#9CA3AF",bold:!0},"Working Files"),p.createElement(k,{color:"#6B7280"}," (",c.length,")")),p.createElement(R,{flexWrap:"wrap",gap:1},c.map(e=>p.createElement(R,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},p.createElement(k,{color:"white"},e.name)))))}var Cr=cr(function({message:e,onSuggestionClick:t}){let{role:s,content:n}=e,{suggestions:i,cleanedContentSuggestions:r}=ns(()=>{let u=mr(n);return{suggestions:u.suggestions,cleanedContentSuggestions:u.cleanedContent}},[n]),{workingFiles:a,finalContent:l}=ns(()=>{let u=gr(r),d=u.cleanedContent.replace(/\[TOOL:[^\]]+\]/g,"").trim();return{workingFiles:u.workingFiles,finalContent:d}},[r]);if(s==="system"){let u=n.split(`
548
- `);return p.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"#6B7280"},"System")),p.createElement(R,{paddingLeft:1,flexDirection:"column"},u.map((d,m)=>p.createElement(k,{key:`sys-line-${m}`,color:"#9CA3AF"},d))))}if(s==="user")return p.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"#60A5FA",bold:!0},"You")),p.createElement(R,{paddingLeft:1},p.createElement(k,{color:"whiteBright"},n)));if(s==="assistant"){let u=l.split(`
549
- `);return p.createElement(R,{marginBottom:1,flexDirection:"column"},p.createElement(R,{marginBottom:0},p.createElement(k,{color:"#5AD8A6",bold:!0},"Orion")),p.createElement(R,{flexDirection:"column",paddingLeft:1},u.map((d,m)=>d.trim()===""?p.createElement(k,{key:`asst-line-${m}`}," "):p.createElement(k,{key:`asst-line-${m}`,color:"whiteBright"},yr(d)))),a.length>0&&p.createElement(Sr,{workingFiles:a}),i.length>0&&p.createElement(wr,{suggestions:i,onSelect:t}))}return null});js();ue();ue();import q from"chalk";import Or from"inquirer";import{exec as $r}from"child_process";var We=class{authService;constructor(){this.authService=X.getInstance()}openBrowser(e){return new Promise(t=>{let s=process.platform,n;s==="darwin"?n=`open "${e}"`:s==="win32"?n=`start "" "${e}"`:n=`xdg-open "${e}"`,$r(n,i=>{i&&console.log(q.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(q.blue(`
546
+ `),E=g.length>100;if(x||E){let h=hr(g),C=g.split(`
547
+ `).length;d(b=>{m.current+=1;let f="text",$,L;if(h.isFilePath){h.isImage?f="image_path":h.isBinary?(f="file_path",L="Binary file - cannot read as text"):f="file_path";let Z=qs(h.path);Z.exists?$=Z.size:L=Z.error}let V={id:m.current,content:g,lineCount:C,type:f,filePath:h.isFilePath?h.path:void 0,fileSize:$,error:L};return{...b,pastedTexts:[...b.pastedTexts,V]}});return}d(h=>{let v=h.input+g;return v==="/"&&!h.showCommandMenu?{...h,input:v,showCommandMenu:!0}:{...h,input:v}})}}});let _=s.getUserEmail()||"User",P=ge.getDisplayName(ge.getCurrentUserTier()),F=ti(()=>u.queuedMessages.filter(g=>g.isCrossDeviceTask),[u.queuedMessages]),H=ti(()=>u.queuedMessages.filter(g=>!g.isCrossDeviceTask),[u.queuedMessages]);return p.createElement(R,{flexDirection:"column",width:"100%"},p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,width:"100%"},p.createElement(k,{color:"whiteBright"},u.selectedModel.displayName),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"#9CA3AF"},_),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"whiteBright"},P),u.queuedMessages.length>0&&p.createElement(p.Fragment,null,p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{backgroundColor:"#3F3F46",color:"whiteBright",bold:!0}," ",u.queuedMessages.length," "),p.createElement(k,{color:"#9CA3AF"}," queued")),F.length>0&&p.createElement(p.Fragment,null,p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{backgroundColor:"#0E7490",color:"whiteBright",bold:!0}," [mobile] ",F.length," "),p.createElement(k,{color:"#9CA3AF"}," cross-device"))),p.createElement(R,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},u.messages.map(g=>p.createElement(Sr,{key:g.id,message:g,onSuggestionClick:N=>{d(x=>({...x,input:N}))}}))),u.todoList&&u.todoList.todos.length>0&&u.todoList.todos.some(g=>g.status!=="completed")&&(()=>{let N=u.todoList.todos.filter(v=>v.status!=="completed"),x=u.todoList.todos.filter(v=>v.status==="completed"),E=[...N,...x.slice(-2)].slice(0,8),h=u.todoList.todos.length-E.length;return p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(R,{marginBottom:1},p.createElement(k,{color:"whiteBright",bold:!0},"Tasks"),p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{color:"#9CA3AF"},x.length,"/",u.todoList.todos.length)),E.map((v,C)=>{let b=v.status==="completed"?"[done]":v.status==="in_progress"?"[..]":"[ ]",f=v.status==="completed"?"#5AD8A6":v.status==="in_progress"?"cyan":"#6B7280";return p.createElement(R,{key:v.id||C},p.createElement(k,{color:f},b),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:v.status==="completed"?"#6B7280":"whiteBright"},v.status==="in_progress"&&v.activeForm?v.activeForm:v.text))}),h>0&&p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"}," +",h," more tasks"))))})(),u.activeTools.size>0&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(Jn,{activeTools:u.activeTools})),u.subAgentOperations.size>0&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(Zn,{operations:u.subAgentOperations})),u.isProcessingFiles&&p.createElement(R,{paddingX:2,marginBottom:1},p.createElement(k,{color:"cyan"},p.createElement(si,{type:"dots"})),p.createElement(k,{color:"whiteBright"}," Reading files...")),u.isLoading&&u.activeTools.size===0&&!u.isProcessingFiles&&p.createElement(R,{paddingX:0,marginBottom:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"cyan"},p.createElement(si,{type:"dots"})),p.createElement(k,{color:"whiteBright"}," ",u.loadingMessage,"... "),p.createElement(k,{color:"#9CA3AF"},"(esc to interrupt)")),p.createElement(R,{marginLeft:2},p.createElement(k,{color:"#FBBF24"},"If experiencing latency: rate limit hit. Screenshot & tag @MeetOrion on X for quota help"))),u.showHelp&&p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),p.createElement(R,{marginTop:1,flexDirection:"column"},p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Enter")," ",p.createElement(k,{color:"#9CA3AF"},"Submit message")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"?")," ",p.createElement(k,{color:"#9CA3AF"},"Toggle this help")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Esc")," ",p.createElement(k,{color:"#9CA3AF"},"Stop generation / Close menus")),p.createElement(k,{color:"#9CA3AF"},"• ",p.createElement(k,{color:"whiteBright",bold:!0},"Ctrl+C")," ",p.createElement(k,{color:"#9CA3AF"},"Stop generation / Exit"))),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Press Esc to close"))),u.showModelMenu&&(()=>{let g=ge.getCurrentUserTier(),N=f=>{switch(f){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},x=Q.filter(f=>f.name.startsWith("snowx-o4")||f.name.startsWith("snowx-c")||f.name.startsWith("snowx-h")),E=Q.filter(f=>f.name.startsWith("snowx-5")||f.name.startsWith("snowx-o3")||f.name.startsWith("snowx-4")),h=Q.filter(f=>f.name.startsWith("snowx-g")),v=f=>f.map($=>{let L=ge.isModelAccessible($.name,g),V=N($.creditMultiplier);return{label:`${L?"":"[LOCKED] "}${$.displayName} ${V}`,value:$.name,isAccessible:L,creditMultiplier:$.creditMultiplier,isHeader:!1}}),C=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(x),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(E),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...v(h)],b=C.filter(f=>!f.isHeader);return p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Select Model"),p.createElement(R,null,p.createElement(k,{color:"#6B7280"},"Tier: ",ge.getDisplayName(g)," - "),p.createElement(k,{color:"#5AD8A6"},"[0.5x]"),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:"#9CA3AF"},"[1x]"),p.createElement(k,{color:"#6B7280"}," "),p.createElement(k,{color:"#FBBF24"},"[2x]"),p.createElement(k,{color:"#6B7280"}," credits")),p.createElement(R,{marginTop:1},p.createElement(ni,{items:b.map(f=>({label:f.label,value:f.value})),onSelect:f=>{if(f.value.startsWith("_"))return;if(!C.find(V=>V.value===f.value)?.isAccessible){d(V=>({...V,messages:[...V.messages,{id:Y(),role:"system",content:ge.getAccessDeniedMessage(f.value),timestamp:Date.now()}]}));return}let L=Q.find(V=>V.name===f.value);L&&(Fe.set("selectedPersonalModel",L.name),d(V=>({...V,selectedModel:L,showModelMenu:!1,messages:[...V.messages,{id:Y(),role:"system",content:`Switched to ${L.displayName}`,timestamp:Date.now()}]})))}})),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Esc to cancel")))})(),u.showCommandMenu&&(()=>{let g=[{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"}],N=u.input.startsWith("/")?u.input.substring(1).toLowerCase():"",x=N?g.filter(E=>E.value.toLowerCase().includes(N)):g;return p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},p.createElement(k,{bold:!0,color:"whiteBright"},"Available Commands ",N&&`(filtered: "${N}")`),p.createElement(R,{marginTop:1},p.createElement(ni,{items:x.length>0?x:[{label:"No matching commands",value:""}],onSelect:E=>{E.value&&(d(h=>({...h,showCommandMenu:!1,input:""})),y(`/${E.value}`))}})),p.createElement(R,{marginTop:1},p.createElement(k,{color:"#6B7280"},"Esc to cancel")))})(),H.length>0&&p.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},H.map((g,N)=>p.createElement(R,{key:g.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},p.createElement(R,null,p.createElement(k,{color:"whiteBright",bold:!0},N+1),p.createElement(k,{color:"#6B7280"}," • "),p.createElement(k,{color:"#9CA3AF"},g.content.length>60?g.content.substring(0,60)+"...":g.content)))),p.createElement(R,null,p.createElement(k,{color:"#9CA3AF"},H.length," message",H.length>1?"s":""," queued"))),F.length>0&&p.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},F.map((g,N)=>p.createElement(R,{key:`cross-${g.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},p.createElement(R,null,p.createElement(k,{color:"#22D3EE",bold:!0},"[M] ",N+1),p.createElement(k,{color:"#6B7280"}," - "),p.createElement(k,{color:"#9CA3AF"},g.content.length>60?g.content.substring(0,60)+"...":g.content)))),p.createElement(R,null,p.createElement(k,{color:"#22D3EE"},F.length," cross-device task",F.length>1?"s":""," waiting"))),p.createElement(R,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},u.pastedTexts.length>0&&p.createElement(R,{flexDirection:"column",marginBottom:0},u.pastedTexts.map((g,N)=>{if(g.type==="image_path"&&g.filePath){let h=ri(he.basename(g.filePath)),v=g.fileSize?` ${rt(g.fileSize)}`:"",C=!!g.error;return p.createElement(R,{key:`pasted-${g.id}`,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:C?"#EF4444":"#22D3EE"}," ","[IMG] "),p.createElement(k,{color:C?"#EF4444":"#9CA3AF"},h),v&&p.createElement(k,{color:"#6B7280"},v)),C&&p.createElement(R,{marginLeft:4},p.createElement(k,{color:"#EF4444",dimColor:!0},"[!] ",g.error)))}if(g.type==="file_path"&&g.filePath){let h=ri(he.basename(g.filePath)),v=g.fileSize?` ${rt(g.fileSize)}`:"",C=!!g.error;return p.createElement(R,{key:`pasted-${g.id}`,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:C?"#EF4444":"#22D3EE"}," ","[FILE] "),p.createElement(k,{color:C?"#EF4444":"#9CA3AF"},h),v&&p.createElement(k,{color:"#6B7280"},v)),C&&p.createElement(R,{marginLeft:4},p.createElement(k,{color:"#EF4444",dimColor:!0},"[!] ",g.error)))}let x=g.lineCount-1,E=x>0?`+${x} lines`:"1 line";return p.createElement(R,{key:`pasted-${g.id}`},p.createElement(k,{color:"#6B7280"}," ","[TEXT] "),p.createElement(k,{color:"#9CA3AF"},"Pasted text #",N+1),p.createElement(k,{color:"#6B7280"}," (",E,")"))})),p.createElement(R,null,p.createElement(k,{color:"cyan"},"▶ "),p.createElement(k,{color:"whiteBright"},u.input,!u.isLoading&&p.createElement(k,{color:"whiteBright",inverse:!0}," "))),p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"},u.isLoading?"Send feedback or press Enter to queue · esc to stop":u.pastedTexts.length>0?"enter to submit with pasted content · esc to clear":"/help · ? · enter to submit"))),p.createElement(R,{paddingX:2,paddingY:0},p.createElement(k,{color:"#6B7280"},"? help · Ctrl+L refresh · Ctrl+C exit")))}function Tr(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=ts(e),e}function yr({suggestions:c,onSelect:e}){return c.length===0?null:p.createElement(R,{flexDirection:"column",marginTop:1},c.map((t,s)=>p.createElement(R,{key:`sug-block-${s}`,flexWrap:"wrap",gap:1},t.options.map((n,i)=>p.createElement(R,{key:`sug-opt-${s}-${i}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},p.createElement(k,{color:"#22D3EE"},n))))),e&&p.createElement(R,{marginTop:0},p.createElement(k,{color:"#6B7280"},"Type a suggestion to use it")))}function wr({workingFiles:c}){return c.length===0?null:p.createElement(R,{flexDirection:"column",marginTop:1},p.createElement(R,{marginBottom:0},p.createElement(k,{color:"#9CA3AF",bold:!0},"Working Files"),p.createElement(k,{color:"#6B7280"}," (",c.length,")")),p.createElement(R,{flexWrap:"wrap",gap:1},c.map(e=>p.createElement(R,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},p.createElement(k,{color:"white"},e.name)))))}function Sr({message:c,onSuggestionClick:e}){let{role:t,content:s}=c;if(t==="system"){let n=s.split(`
548
+ `);return p.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"#6B7280"},"System")),p.createElement(R,{paddingLeft:1,flexDirection:"column"},n.map((i,r)=>p.createElement(k,{key:`sys-line-${r}`,color:"#9CA3AF"},i))))}if(t==="user")return p.createElement(R,{marginBottom:1,marginTop:1,flexDirection:"column"},p.createElement(R,null,p.createElement(k,{color:"#60A5FA",bold:!0},"You")),p.createElement(R,{paddingLeft:1},p.createElement(k,{color:"whiteBright"},s)));if(t==="assistant"){let{suggestions:n,cleanedContent:i}=pr(s),{workingFiles:r,cleanedContent:a}=mr(i),u=a.replace(/\[TOOL:[^\]]+\]/g,"").trim().split(`
549
+ `);return p.createElement(R,{marginBottom:1,flexDirection:"column"},p.createElement(R,{marginBottom:0},p.createElement(k,{color:"#5AD8A6",bold:!0},"Orion")),p.createElement(R,{flexDirection:"column",paddingLeft:1},u.map((d,m)=>d.trim()===""?p.createElement(k,{key:`asst-line-${m}`}," "):p.createElement(k,{key:`asst-line-${m}`,color:"whiteBright"},Tr(d)))),r.length>0&&p.createElement(wr,{workingFiles:r}),n.length>0&&p.createElement(yr,{suggestions:n,onSelect:e}))}return null}Gs();ue();ue();import q from"chalk";import Fr from"inquirer";import{exec as Or}from"child_process";var We=class{authService;constructor(){this.authService=X.getInstance()}openBrowser(e){return new Promise(t=>{let s=process.platform,n;s==="darwin"?n=`open "${e}"`:s==="win32"?n=`start "" "${e}"`:n=`xdg-open "${e}"`,Or(n,i=>{i&&console.log(q.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(q.blue(`
550
550
  🔐 Orion Authentication`)),console.log(q.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(q.yellow(`
551
551
  📋 Opening browser for authentication...`)),console.log(q.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(q.white(`
552
552
  1. Log in with your Orion account in the browser`)),console.log(q.white("2. Copy the access token shown after login")),console.log(q.white("3. Paste the token below")),console.log(q.yellow(`
553
- Paste your access token here:`));let{accessToken:t}=await Or.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(q.gray(`
553
+ Paste your access token here:`));let{accessToken:t}=await Fr.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(q.gray(`
554
554
  Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let n=await this.authService.getUserInfo();console.log(q.green(`
555
555
  ✅ Authentication successful!`)),n&&(console.log(q.gray(`Logged in as: ${n.email||n.username||"User"}`)),console.log(q.gray(`Subscription: ${this.getSubscriptionDisplay(n.subscription?.tier)}`)))}else console.log(q.red(`
556
556
  ❌ Authentication failed. Please try again.`))}catch(s){console.log(q.red(`
@@ -560,7 +560,7 @@ Verifying access token...`));try{if(await this.authService.authenticateWithAcces
560
560
  ❌ Logout failed`)),console.log(q.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(q.green(`
561
561
  ✅ Authenticated`)),t){console.log(q.gray("─".repeat(50))),console.log(q.white("User:",t.name||t.username||"N/A")),console.log(q.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(q.white("Subscription:",s)),t.usage&&(console.log(q.gray(`
562
562
  Usage:`)),console.log(q.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(q.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(q.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(q.yellow(`
563
- ⚠️ Not authenticated`)),console.log(q.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"}}};ke();Rs();var bi=!1;async function Xs(){let c=process.cwd();if(bi){console.log("Already running...");return}bi=!0,U.enableCustomUI();let e=yt.getInstance(),t=X.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(i){console.error(`
563
+ ⚠️ Not authenticated`)),console.log(q.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"}}};ke();Ns();var bi=!1;async function js(){let c=process.cwd();if(bi){console.log("Already running...");return}bi=!0,U.enableCustomUI();let e=yt.getInstance(),t=X.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(i){console.error(`
564
564
  ❌ Failed to initialize services:`,i.message),console.error(`
565
565
  💡 Tip: Check your internet connection and Firebase configuration.
566
566
  `),process.exit(1)}}(!await t.autoAuthenticate()||!t.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
@@ -570,8 +570,8 @@ Usage:`)),console.log(q.white(` Standard prompts: ${t.usage.prompt||0}`)),conso
570
570
  `)),t.isFirebaseAuthenticated()||(console.error(`
571
571
  ❌ 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(`
572
572
  Please check your connection and try again.
573
- `),process.exit(1)),console.log("✅ Authentication verified"),Zt.getInstance().setWorkingDirectory(c),await Mr(_r.createElement(li,{initialProjectPath:c}),{exitOnCtrlC:!1}).start()}je();W();import{EventEmitter as Lr}from"events";import Ur from"axios";import{spawn as Wr}from"child_process";import rs from"chalk";import ze from"fs";import as from"path";import Vs from"os";var Br={enabled:!0,checkIntervalMs:1440*60*1e3},Ti=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,cs=class c extends Lr{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Br,...t},this.cacheFilePath=as.join(Vs.homedir(),".orion","update-cache.json")}static getInstance(e,t){return c.instance||(c.instance=new c(e,t)),c.instance}static resetInstance(){c.instance=void 0}isEnabled(){return this.config.enabled}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}async checkAndUpdate(){if(!this.config.enabled){o.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){o.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){o.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):o.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){o.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(ze.existsSync(this.cacheFilePath)){let e=ze.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){o.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=as.dirname(this.cacheFilePath);ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0}),ze.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){o.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:Ti.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,s=(await Ur.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!s)throw new Error("No latest version found in registry response");return s}isNewerVersion(e,t){let s=this.parseVersion(e),n=this.parseVersion(t);if(!s||!n)return o.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let i=0;i<3;i++){if(s.numbers[i]>n.numbers[i])return!0;if(s.numbers[i]<n.numbers[i])return!1}return!s.prerelease&&n.prerelease?!0:s.prerelease&&!n.prerelease?!1:s.prerelease&&n.prerelease?this.comparePrerelease(s.prerelease,n.prerelease)>0:!1}parseVersion(e){let t=e.match(Ti);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let s=e.split("."),n=t.split(".");for(let i=0;i<Math.max(s.length,n.length);i++){let r=s[i],a=n[i];if(r===void 0)return-1;if(a===void 0)return 1;let l=parseInt(r,10),u=parseInt(a,10);if(!isNaN(l)&&!isNaN(u)){if(l!==u)return l-u;continue}if(!isNaN(l))return-1;if(!isNaN(u))return 1;if(r!==a)return r.localeCompare(a)}return 0}detectPackageManager(){try{let e=process.env.PNPM_HOME||as.join(Vs.homedir(),".local","share","pnpm");if(process.argv[1]?.includes("pnpm")||process.argv[1]?.includes(e))return"pnpm";let t=as.join(Vs.homedir(),".yarn");if(process.argv[1]?.includes("yarn")||process.argv[1]?.includes(t))return"yarn";let s=process.env.npm_config_user_agent||"";if(s.includes("pnpm"))return"pnpm";if(s.includes("yarn"))return"yarn"}catch(e){o.debug("Failed to detect package manager:",e)}return"npm"}getInstallCommand(){let e=this.detectPackageManager(),t=`${this.packageName}@latest`;switch(e){case"pnpm":return{command:"pnpm",args:["add","-g",t]};case"yarn":return{command:"yarn",args:["global","add",t]};default:return{command:"npm",args:["install","-g",t]}}}async performUpdate(e){return new Promise(t=>{try{let{command:s,args:n}=this.getInstallCommand();o.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${s}`);let i=Wr(s,n,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),r="";i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>{a===0?(this.updateCompleted=!0,this.emit("updated",{from:this.currentVersion,to:e}),setImmediate(()=>{this.isUserInteracting()?this.emit("update_notification_pending",{from:this.currentVersion,to:e}):console.log(rs.green(`
574
- ✓ Updated to v${e}`)+rs.gray(` - restart CLI to use new version
575
- `))}),o.debug(`Successfully updated to ${e}`)):o.debug(`Update failed with code ${a}: ${r}`),t()}),i.on("error",a=>{o.debug("Auto-update spawn error:",a),t()}),setTimeout(()=>{this.updateCompleted||(i.kill(),o.debug("Update timed out"),t())},6e4)}catch(s){o.debug("Auto-update failed:",s),t()}})}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(rs.green(`
576
- ✓ Updated to v${e.latestVersion}`)+rs.gray(` - restart CLI to use new version
577
- `))}}wasUpdated(){return this.updateCompleted}async checkForUpdates(){try{let e=this.loadCache();if(e&&Date.now()-e.lastCheck<this.config.checkIntervalMs)return{hasUpdate:this.isNewerVersion(e.latestVersion,this.currentVersion),latestVersion:e.latestVersion};let t=await this.fetchLatestVersion();return this.isValidVersion(t)?(this.saveCache({lastCheck:Date.now(),latestVersion:t}),{hasUpdate:this.isNewerVersion(t,this.currentVersion),latestVersion:t}):{hasUpdate:!1}}catch(e){return o.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{ze.existsSync(this.cacheFilePath)&&ze.unlinkSync(this.cacheFilePath)}catch(e){o.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function yi(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1"||process.argv[1]?.includes("tsx")||process.argv[1]?.endsWith(".ts"))return!0;let c=process.argv[1]||"";if(c.includes("/src/")&&!c.includes("node_modules"))return!0;let e=["/orion-cli/dist/","/orion-cli/src/"];for(let s of e)if(c.includes(s)&&!c.includes("node_modules"))return!0;return!1}import qr from"dotenv";import{fileURLToPath as zr}from"url";import{dirname as Gr,join as jr}from"path";import{readFileSync as Xr}from"fs";qr.config();var Vr=zr(import.meta.url),Kr=Gr(Vr),wi=JSON.parse(Xr(jr(Kr,"..","package.json"),"utf8")),Qr=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!yi()&&!Qr&&cs.getInstance(wi.version).checkAndUpdate().catch(()=>{});var at=new Hr;at.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(wi.version).option("--no-update","Disable automatic update check");at.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Xs()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});at.command("ask <question>").description("Ask a single question (Advanced Mode with Orion features)").option("-m, --model <model>","Select AI model","snowx-5c").option("-s, --stream","Enable streaming response",!0).action(async(c,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(js(),vi)),s=t.getInstance();console.log("🔧 Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let n=Q.find(r=>r.name===e.model)||Q[0];console.log("💭 Sending message...");let i=await s.sendMessage(c,n,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(ts(i))}catch(t){ce.stopSpinner(!1),console.error(ce.formatError(t.message)),process.exit(1)}});var Ks=at.command("auth").description("Authentication commands");Ks.command("login").description("Login to Orion").action(async()=>{try{await new We().login()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});Ks.command("logout").description("Logout from Orion").action(async()=>{try{await new We().logout()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});Ks.command("status").description("Check authentication status").action(async()=>{try{await new We().status()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});at.command("models").description("List available AI models").action(()=>{ce.printHeader("Available Models");for(let c of Q)console.log(`${ce.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?Xs().catch(c=>{console.error(ce.formatError(c.message)),process.exit(1)}):at.parse(process.argv);
573
+ `),process.exit(1)),console.log("✅ Authentication verified"),Zt.getInstance().setWorkingDirectory(c),await _r($r.createElement(li,{initialProjectPath:c}),{exitOnCtrlC:!1}).start()}je();W();import{EventEmitter as Mr}from"events";import Lr from"axios";import{spawn as Ur}from"child_process";import os from"chalk";import ze from"fs";import rs from"path";import Xs from"os";var Wr={enabled:!0,checkIntervalMs:1440*60*1e3},Ti=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,as=class c extends Mr{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Wr,...t},this.cacheFilePath=rs.join(Xs.homedir(),".orion","update-cache.json")}static getInstance(e,t){return c.instance||(c.instance=new c(e,t)),c.instance}static resetInstance(){c.instance=void 0}isEnabled(){return this.config.enabled}disable(){this.config.enabled=!1}enable(){this.config.enabled=!0}async checkAndUpdate(){if(!this.config.enabled){o.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){o.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){o.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):o.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){o.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(ze.existsSync(this.cacheFilePath)){let e=ze.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){o.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=rs.dirname(this.cacheFilePath);ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0}),ze.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){o.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:Ti.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,s=(await Lr.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!s)throw new Error("No latest version found in registry response");return s}isNewerVersion(e,t){let s=this.parseVersion(e),n=this.parseVersion(t);if(!s||!n)return o.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let i=0;i<3;i++){if(s.numbers[i]>n.numbers[i])return!0;if(s.numbers[i]<n.numbers[i])return!1}return!s.prerelease&&n.prerelease?!0:s.prerelease&&!n.prerelease?!1:s.prerelease&&n.prerelease?this.comparePrerelease(s.prerelease,n.prerelease)>0:!1}parseVersion(e){let t=e.match(Ti);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let s=e.split("."),n=t.split(".");for(let i=0;i<Math.max(s.length,n.length);i++){let r=s[i],a=n[i];if(r===void 0)return-1;if(a===void 0)return 1;let l=parseInt(r,10),u=parseInt(a,10);if(!isNaN(l)&&!isNaN(u)){if(l!==u)return l-u;continue}if(!isNaN(l))return-1;if(!isNaN(u))return 1;if(r!==a)return r.localeCompare(a)}return 0}detectPackageManager(){try{let e=process.env.PNPM_HOME||rs.join(Xs.homedir(),".local","share","pnpm");if(process.argv[1]?.includes("pnpm")||process.argv[1]?.includes(e))return"pnpm";let t=rs.join(Xs.homedir(),".yarn");if(process.argv[1]?.includes("yarn")||process.argv[1]?.includes(t))return"yarn";let s=process.env.npm_config_user_agent||"";if(s.includes("pnpm"))return"pnpm";if(s.includes("yarn"))return"yarn"}catch(e){o.debug("Failed to detect package manager:",e)}return"npm"}getInstallCommand(){let e=this.detectPackageManager(),t=`${this.packageName}@latest`;switch(e){case"pnpm":return{command:"pnpm",args:["add","-g",t]};case"yarn":return{command:"yarn",args:["global","add",t]};default:return{command:"npm",args:["install","-g",t]}}}async performUpdate(e){return new Promise(t=>{try{let{command:s,args:n}=this.getInstallCommand();o.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${s}`);let i=Ur(s,n,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),r="";i.stderr?.on("data",a=>{r+=a.toString()}),i.on("close",a=>{a===0?(this.updateCompleted=!0,this.emit("updated",{from:this.currentVersion,to:e}),setImmediate(()=>{this.isUserInteracting()?this.emit("update_notification_pending",{from:this.currentVersion,to:e}):console.log(os.green(`
574
+ ✓ Updated to v${e}`)+os.gray(` - restart CLI to use new version
575
+ `))}),o.debug(`Successfully updated to ${e}`)):o.debug(`Update failed with code ${a}: ${r}`),t()}),i.on("error",a=>{o.debug("Auto-update spawn error:",a),t()}),setTimeout(()=>{this.updateCompleted||(i.kill(),o.debug("Update timed out"),t())},6e4)}catch(s){o.debug("Auto-update failed:",s),t()}})}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(os.green(`
576
+ ✓ Updated to v${e.latestVersion}`)+os.gray(` - restart CLI to use new version
577
+ `))}}wasUpdated(){return this.updateCompleted}async checkForUpdates(){try{let e=this.loadCache();if(e&&Date.now()-e.lastCheck<this.config.checkIntervalMs)return{hasUpdate:this.isNewerVersion(e.latestVersion,this.currentVersion),latestVersion:e.latestVersion};let t=await this.fetchLatestVersion();return this.isValidVersion(t)?(this.saveCache({lastCheck:Date.now(),latestVersion:t}),{hasUpdate:this.isNewerVersion(t,this.currentVersion),latestVersion:t}):{hasUpdate:!1}}catch(e){return o.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{ze.existsSync(this.cacheFilePath)&&ze.unlinkSync(this.cacheFilePath)}catch(e){o.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function yi(){if(process.env.ORION_DEV==="true"||process.env.ORION_DEV==="1"||process.argv[1]?.includes("tsx")||process.argv[1]?.endsWith(".ts"))return!0;let c=process.argv[1]||"";if(c.includes("/src/")&&!c.includes("node_modules"))return!0;let e=["/orion-cli/dist/","/orion-cli/src/"];for(let s of e)if(c.includes(s)&&!c.includes("node_modules"))return!0;return!1}import Hr from"dotenv";import{fileURLToPath as qr}from"url";import{dirname as zr,join as Gr}from"path";import{readFileSync as jr}from"fs";Hr.config();var Xr=qr(import.meta.url),Vr=zr(Xr),wi=JSON.parse(jr(Gr(Vr,"..","package.json"),"utf8")),Kr=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!yi()&&!Kr&&as.getInstance(wi.version).checkAndUpdate().catch(()=>{});var at=new Br;at.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(wi.version).option("--no-update","Disable automatic update check");at.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await js()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});at.command("ask <question>").description("Ask a single question (Advanced Mode with Orion features)").option("-m, --model <model>","Select AI model","snowx-5c").option("-s, --stream","Enable streaming response",!0).action(async(c,e)=>{try{let{ServiceManager:t}=await Promise.resolve().then(()=>(Gs(),vi)),s=t.getInstance();console.log("🔧 Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let n=Q.find(r=>r.name===e.model)||Q[0];console.log("💭 Sending message...");let i=await s.sendMessage(c,n,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(ts(i))}catch(t){ce.stopSpinner(!1),console.error(ce.formatError(t.message)),process.exit(1)}});var Vs=at.command("auth").description("Authentication commands");Vs.command("login").description("Login to Orion").action(async()=>{try{await new We().login()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});Vs.command("logout").description("Logout from Orion").action(async()=>{try{await new We().logout()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});Vs.command("status").description("Check authentication status").action(async()=>{try{await new We().status()}catch(c){console.error(ce.formatError(c.message)),process.exit(1)}});at.command("models").description("List available AI models").action(()=>{ce.printHeader("Available Models");for(let c of Q)console.log(`${ce.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?js().catch(c=>{console.error(ce.formatError(c.message)),process.exit(1)}):at.parse(process.argv);