@zinley/orion 1.2.21 → 1.2.23

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 +238 -230
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- var eo=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var ki=Object.prototype.hasOwnProperty;var Ii=(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 D=(c,e)=>()=>(c&&(e=c(c=0)),e);var Ee=(c,e)=>{for(var t in e)eo(c,t,{get:e[t],enumerable:!0})},Pi=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ei(e))!ki.call(c,o)&&o!==t&&eo(c,o,{get:()=>e[o],enumerable:!(n=xi(e,o))||n.enumerable});return c};var Ai=c=>Pi(eo({},"__esModule",{value:!0}),c);var Q,He=D(()=>{"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 to,i,$=D(()=>{"use strict";to=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},i=to.getInstance()});var Ne={};Ee(Ne,{UserDefaults:()=>Fe});import Dt from"fs";import no from"path";import Di from"os";var oo,Fe,be=D(()=>{"use strict";$();oo=class c{static instance;preferencesPath;preferences={};constructor(){let e=no.join(Di.homedir(),".orion");this.preferencesPath=no.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Dt.existsSync(this.preferencesPath)){let e=Dt.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),i.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{i.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=no.dirname(this.preferencesPath);Dt.existsSync(e)||Dt.mkdirSync(e,{recursive:!0}),Dt.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),i.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){i.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),i.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),i.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Fe=oo.getInstance()});var ae,Nt=D(()=>{"use strict";He();be();$();ae=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),i.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let n=this.getRequiredTier(e),o=t>=n;return i.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${n} (${this.getDisplayName(n)}), Access=${o}`),o}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 Ni from"axios";import{EventEmitter as Ri}from"events";var qe,Ge,Zt=D(()=>{"use strict";qe="firebase_timestamp",Ge=class c extends Ri{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Ni.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(()=>(be(),Ne));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(ce(),us));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let o={"Content-Type":"application/json"};await this.addAuthorizationHeader(o);let s={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",s,{headers:o})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let o={collection:e};t&&(o.limit=t.toString());try{let r=(await this.client.get("/documents",{params:o,headers:n})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(s){throw s}}async queryDocuments(e,t,n,o,s,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:n,value:String(o)};s&&(u.limit=s.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let p=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(p.success)return Array.isArray(p.doc)?p.doc:p.doc&&typeof p.doc=="object"?[p.doc]:[];{let m=p.error||"Unknown error";throw new Error(m)}}catch(d){throw d}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let o={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:o,headers:n})).data;return r.success?r.doc:null}catch(s){throw s}}async updateDocument(e,t,n){let o={"Content-Type":"application/json"};await this.addAuthorizationHeader(o);let s={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,s,{headers:o})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let o={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:o,headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(s){throw s}}async createDocumentInSubcollection(e,t,n,o,s){let r=`${e}/${t}/${n}`;return this.createDocument(r,o,s)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let o=await this.getDocuments(n);for(let s of o)s.id&&await this.deleteDocument(n,s.id);for(let[s,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${s}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:s,conversationId:e};try{await this.createDocument(n,a,l)}catch{}}}catch(o){throw o}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((o,s)=>{if(o.order!==void 0&&s.order!==void 0)return o.order-s.order;let r=new Date(o.timestamp||0).getTime(),a=new Date(s.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={path:e,updates:t};try{let r=(await this.client.put("/realtime",o,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(s){throw s}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=(await this.client.get("/realtime",{params:n,headers:t})).data;if(s.success)return s.doc;{let r=s.error||"Unknown error";throw new Error(r)}}catch(o){throw o}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!s.success){let r=s.error||"Unknown error";throw new Error(r)}}catch(o){throw o}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=await this.client.get("/realtime",{params:n,headers:t}),s=o.data;if(s.success)return o.data.data;{let r=s.error||"Unknown error";throw new Error(r)}}catch(o){throw o}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={path:e,data:t};try{let r=(await this.client.post("/realtime",o,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(s){throw s}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let o={path:e,data:t};try{let r=(await this.client.post("/realtime/push",o,{headers:n})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(s){throw s}}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 so={};Ee(so,{DeviceRegistrationService:()=>me});import{EventEmitter as Mi}from"events";import{v4 as ds}from"uuid";import Rt from"os";import ps from"fs/promises";import Oi from"path";import{execSync as Mt}from"child_process";import Fi from"crypto";var me,ze=D(()=>{"use strict";Zt();ce();$();me=class c extends Mi{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=Ge.getInstance(),this.authService=H.getInstance(),this.configDir=Oi.join(Rt.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){i.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{i.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{i.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();i.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(i.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){i.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),i.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(i.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,i.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),i.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw i.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}i.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),i.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){i.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return i.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=Rt.platform();if(e==="darwin")try{let o=Mt("scutil --get ComputerName",{encoding:"utf8"}).trim();if(o)return i.debug(`[DEVICE REG] macOS ComputerName: ${o}`),o}catch{i.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let o=Mt('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(o&&o[1]){let s=o[1].trim();if(s)return i.debug(`[DEVICE REG] Windows ComputerName: ${s}`),s}}catch{i.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=Rt.hostname();return i.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return i.debug(`[DEVICE REG] Error getting computer name: ${e}`),Rt.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=Rt.platform();try{let t=null;switch(e){case"darwin":try{let a=Mt("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],i.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=Mt("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],i.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await ps.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await ps.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),i.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{i.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=Mt("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
- `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),i.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:i.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=Fi.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return i.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Ne)),o="snowx_fallback_device_id",s=n.string(o);return s?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${s}`):(s=ds(),n.set(o,s),i.debug(`[DEVICE REG] Generated NEW fallback UUID: ${s}`)),s}catch(t){i.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Ne)),o="snowx_fallback_device_id",s=n.string(o);return s?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${s}`):(s=ds(),n.set(o,s),i.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${s}`)),s}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let o=await this.api.getDocument(this.devicesCollection,e);if(o&&o.devices){let s=o.devices;if(s.some(a=>a.deviceId===t)){let a=s.map(l=>l.deviceId===t?{...l,lastSeenAt:qe,computerName:n,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:qe,lastSeenAt:qe};s.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:s})}}else{let r={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:qe,lastSeenAt:qe}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}i.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(o){throw i.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:o.message,code:o.code}),o}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let o=n.devices;if(!o.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=o.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var us={};Ee(us,{AuthService:()=>H});import{EventEmitter as _i}from"events";import{signInAnonymously as $i,signInWithEmailAndPassword as Ui,createUserWithEmailAndPassword as Li,signOut as Wi,onAuthStateChanged as ms,updateProfile as Bi,signInWithCustomToken as Hi}from"firebase/auth";import Xe from"axios";import ro from"fs/promises";import gs from"path";import Gi from"os";var H,ce=D(()=>{"use strict";Nt();$();H=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=gs.join(Gi.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=gs.dirname(this.tokenFilePath);await ro.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(be(),Ne)),t=e.string("snowx_auth_token"),n=e.string("snowx_access_token");if(!t||!n)try{let o=await ro.readFile(this.tokenFilePath,"utf-8"),s=JSON.parse(o);s.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",s.userId),e.set("snowx_access_token",s.token),t=s.userId,n=s.token,await ro.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&n){let o={token:n,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=o,i.debug("Session restored from UserDefaults");try{let s=await this.getUserProfile();s&&s.tier!==void 0?this.authToken.tier=s.tier:await this.updateUserTierFromToken(o)}catch(s){console.warn("⚠️ Failed to fetch user profile during session restore:",s instanceof Error?s.message:"Unknown error"),await this.updateUserTierFromToken(o)}this.emit("authenticated",o)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(be(),Ne));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(()=>(be(),Ne));e.remove("snowx_auth_token"),e.remove("snowx_access_token"),this.authToken=null}catch(e){console.error("❌ Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,ms(e,t=>{this.currentUser=t,this.emit("auth_state_changed",t)})}getFirebaseAuth(){return this.auth}async getCustomTokenFromAPI(e){return this.getCustomTokenFromAPIInternal(e)}async signInWithCustomToken(e){if(!this.auth)throw new Error("Firebase Auth not initialized");let{signInWithCustomToken:t}=await import("firebase/auth");return t(this.auth,e)}async updateUserTierFromToken(e){let t;switch(e.tier){case 1:t=1;break;case 2:t=2;break;case 0:default:t=0;break}ae.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Ne));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),i.debug(`User tier updated: ${ae.getDisplayName(t)} (${e.tier})`),i.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await $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 n=await Ui(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let o=await Li(this.auth,e,t);return this.currentUser=o.user,n&&await Bi(o.user,{displayName:n}),!0}catch(o){return console.error("❌ Failed to sign up with email:",o.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(ze(),so));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Wi(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(()=>(ze(),so));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(be(),Ne)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of n)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let s=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of s)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Xe.post(`${this.snowxAuthEndpoint}/login`,e):t=await Xe.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await Xe.post(`${this.snowxAuthEndpoint}/refresh`,{token:this.authToken.token});if(e.data?.token){let t={...this.authToken,token:e.data.token,expiresAt:Date.now()+(e.data.expiresIn||86400)*1e3};return await this.saveToken(t),!0}return!1}catch(e){return console.warn("⚠️ Failed to refresh token:",e),!1}}getCurrentUser(){return this.currentUser}getAuthToken(){return this.authToken}getAccessToken(){return this.authToken?.token||null}async getAccessTokenFromStorage(){let{UserDefaults:e}=await Promise.resolve().then(()=>(be(),Ne));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(o=>{let s=!1,r,a=ms(this.auth,async l=>{if(!s)if(s=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);o(u)}catch{o(null)}else o(null)});r=setTimeout(()=>{s||(s=!0,a(),o(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(i.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){i.debug("Using existing authentication token"),i.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(i.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(i.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return i.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(i.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):i.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),i.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),i.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),i.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),i.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),i.debug("Signing into Firebase with custom token...");let t=await Hi(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),i.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),i.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),i.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let o="https://snowx.ai/api-beta/api/fb/custom-token",s={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: ${o}`);try{let l=await Xe.post(o,s,{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"),i.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),i.error("Failed to get custom token:",{attempt:n,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let d=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),i.debug(`Retrying in ${d}ms...`),await new Promise(p=>setTimeout(p,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 n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let o=await this.getUserProfileWithIdToken(e,t.userId);o&&(this.authToken.tier=o.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await Xe.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let o=n.data.doc,s=o.subscription?.tier??0;return{id:t,email:o.email,tier:s}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await Xe.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,o=n.id||n.uid||n.user_id||n.userId||n.email;if(!o)throw new Error("No user ID found in API response");let s={token:e,userId:o,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(s),this.userProfile=n,await this.updateUserTierFromToken(s);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(i.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):i.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",s),this.emit("AuthenticationComplete",o),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await Xe.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return ae.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Xe.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var hs={};Ee(hs,{MessageQueueManager:()=>ke});import{EventEmitter as qi}from"events";var ke,dt=D(()=>{"use strict";$();ke=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),i.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),i.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});import{encode as fs,decode as vs,isWithinTokenLimit as bs,countTokens as zi}from"gpt-tokenizer/encoding/cl100k_base";var pt,Xi,ji,ye,mt=D(()=>{"use strict";pt=25e3,Xi=1400,ji=17e3,ye=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??pt,this.previewTokens=e?.previewTokens??Xi,this.maxContentTokens=e?.maxContentTokens??ji}count(e){return e?zi(e):0}encode(e){return e?fs(e):[]}decode(e){return!e||e.length===0?"":vs(e)}isWithinLimit(e,t){return e?bs(e,t??this.maxResponseTokens):0}exceedsResponseLimit(e){return this.isWithinLimit(e,this.maxResponseTokens)===!1}exceedsContentLimit(e){return this.isWithinLimit(e,this.maxContentTokens)===!1}truncate(e,t){if(!e)return{text:"",tokens:0,truncated:!1};let n=t??this.maxResponseTokens,o=bs(e,n);if(o!==!1)return{text:e,tokens:o,truncated:!1};let r=fs(e).slice(0,n);return{text:vs(r),tokens:n,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let n=t??this.previewTokens,o=this.count(e);if(o<=n)return{preview:e,totalTokens:o,previewTokens:o,remainingTokens:0};let{text:s,tokens:r}=this.truncate(e,n);return{preview:s,totalTokens:o,previewTokens:r,remainingTokens:o-r}}truncateContent(e,t){let n=t??this.maxContentTokens,o=this.truncate(e,n);return o.truncated?o.text+`
4
- ... [Content truncated at ${o.tokens.toLocaleString()} tokens]`:e}truncateOutput(e,t){let n=t??this.maxResponseTokens,o=this.truncate(e,n);return o.truncated?o.text+`
2
+ var ao=Object.defineProperty;var Mi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var Oi=Object.prototype.hasOwnProperty;var Fi=(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 D=(c,e)=>()=>(c&&(e=c(c=0)),e);var ke=(c,e)=>{for(var t in e)ao(c,t,{get:e[t],enumerable:!0})},$i=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _i(e))!Oi.call(c,s)&&s!==t&&ao(c,s,{get:()=>e[s],enumerable:!(n=Mi(e,s))||n.enumerable});return c};var Ui=c=>$i(ao({},"__esModule",{value:!0}),c);var Y,qe=D(()=>{"use strict";Y=[{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 lo,i,L=D(()=>{"use strict";lo=class c{static instance;logLevel=0;debugMode=!1;static getInstance(){return c.instance||(c.instance=new c),c.instance}setLogLevel(e){this.logLevel=e}setDebugMode(e){this.debugMode=e}getDebugMode(){return this.debugMode}error(e,...t){this.logLevel>=0&&console.error(`❌ ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`⚠️ ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`ℹ️ ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`✅ ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`🔍 [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},i=lo.getInstance()});var Me={};ke(Me,{UserDefaults:()=>Fe});import Rt from"fs";import uo from"path";import Bi from"os";var po,Fe,be=D(()=>{"use strict";L();po=class c{static instance;preferencesPath;preferences={};constructor(){let e=uo.join(Bi.homedir(),".orion");this.preferencesPath=uo.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Rt.existsSync(this.preferencesPath)){let e=Rt.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),i.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{i.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=uo.dirname(this.preferencesPath);Rt.existsSync(e)||Rt.mkdirSync(e,{recursive:!0}),Rt.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),i.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){i.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),i.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),i.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},Fe=po.getInstance()});var ce,Mt=D(()=>{"use strict";qe();be();L();ce=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),i.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let n=this.getRequiredTier(e),s=t>=n;return i.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${n} (${this.getDisplayName(n)}), Access=${s}`),s}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return Y.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 Hi from"axios";import{EventEmitter as Gi}from"events";var je,ze,on=D(()=>{"use strict";je="firebase_timestamp",ze=class c extends Gi{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=Hi.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(()=>(be(),Me));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(le(),Ss));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let n=await this.getAccessToken();n&&(e.Authorization=n)}}async createDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,docId:t,data:n};try{let a=(await this.client.post("/documents",o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("❌ [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(r){throw console.error("❌ [SnowXFirebaseAPI] createDocument failed:"),console.error("❌ [SnowXFirebaseAPI] Error status:",r.response?.status),console.error("❌ [SnowXFirebaseAPI] Error data:",r.response?.data),console.error("❌ [SnowXFirebaseAPI] Full error:",r),r}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};t&&(s.limit=t.toString());try{let r=(await this.client.get("/documents",{params:s,headers:n})).data;if(r.success)return Array.isArray(r.doc)?r.doc:[];{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async queryDocuments(e,t,n,s,o,r,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:n,value:String(s)};o&&(u.limit=o.toString()),r&&(u.orderBy=r),a&&(u.orderDirection=a);try{let p=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(p.success)return Array.isArray(p.doc)?p.doc:p.doc&&typeof p.doc=="object"?[p.doc]:[];{let m=p.error||"Unknown error";throw new Error(m)}}catch(d){throw d}}async getDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.get(`/documents/${t}`,{params:s,headers:n})).data;return r.success?r.doc:null}catch(o){throw o}}async updateDocument(e,t,n){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let o={collection:e,data:n};try{let a=(await this.client.patch(`/documents/${t}`,o,{headers:s})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(r){throw r}}async deleteDocument(e,t){let n={};await this.addAuthorizationHeader(n);let s={collection:e};try{let r=(await this.client.delete(`/documents/${t}`,{params:s,headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async createDocumentInSubcollection(e,t,n,s,o){let r=`${e}/${t}/${n}`;return this.createDocument(r,s,o)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let n=`snowx_conversations/${e}/messages`;try{let s=await this.getDocuments(n);for(let o of s)o.id&&await this.deleteDocument(n,o.id);for(let[o,r]of t.entries()){if(r.role==="system"||r.isStreaming)continue;let a=`message_${o}_${Date.now()}`,l={id:a,role:r.role,content:r.content,timestamp:r.timestamp||new Date,order:o,conversationId:e};try{await this.createDocument(n,a,l)}catch{}}}catch(s){throw s}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((s,o)=>{if(s.order!==void 0&&o.order!==void 0)return s.order-o.order;let r=new Date(s.timestamp||0).getTime(),a=new Date(o.timestamp||0).getTime();return r-a})}async updateRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,updates:t};try{let r=(await this.client.put("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.get("/realtime",{params:n,headers:t})).data;if(o.success)return o.doc;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let o=(await this.client.delete("/realtime",{params:n,headers:t})).data;if(!o.success){let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let n={path:e};try{let s=await this.client.get("/realtime",{params:n,headers:t}),o=s.data;if(o.success)return s.data.data;{let r=o.error||"Unknown error";throw new Error(r)}}catch(s){throw s}}async writeRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime",s,{headers:n})).data;if(!r.success){let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}async pushRealtimeData(e,t){let n={"Content-Type":"application/json"};await this.addAuthorizationHeader(n);let s={path:e,data:t};try{let r=(await this.client.post("/realtime/push",s,{headers:n})).data;if(r.success){if(r.key)return r.key;throw new Error("No key returned")}else{let a=r.error||"Unknown error";throw new Error(a)}}catch(o){throw o}}setAuthToken(e){console.warn("⚠️ setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("⚠️ clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var mo={};ke(mo,{DeviceRegistrationService:()=>me});import{EventEmitter as qi}from"events";import{v4 as ws}from"uuid";import _t from"os";import Cs from"fs/promises";import zi from"path";import{execSync as Ot}from"child_process";import ji from"crypto";var me,Xe=D(()=>{"use strict";on();le();L();me=class c extends qi{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=ze.getInstance(),this.authService=z.getInstance(),this.configDir=zi.join(_t.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){i.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{i.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{i.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();i.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(i.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){i.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),i.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(i.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,i.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),i.debug(`[DeviceRegistration] ✅ Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw i.debug("[DeviceRegistration] ❌ FAILED to get device ID:",t.message),t}i.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),i.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){i.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return i.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){try{let e=_t.platform();if(e==="darwin")try{let s=Ot("scutil --get ComputerName",{encoding:"utf8"}).trim();if(s)return i.debug(`[DEVICE REG] macOS ComputerName: ${s}`),s}catch{i.debug("[DEVICE REG] Failed to get ComputerName via scutil, using hostname")}else if(e==="win32")try{let s=Ot('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName" /v ComputerName',{encoding:"utf8"}).match(/ComputerName\s+REG_SZ\s+(.+)/i);if(s&&s[1]){let o=s[1].trim();if(o)return i.debug(`[DEVICE REG] Windows ComputerName: ${o}`),o}}catch{i.debug("[DEVICE REG] Failed to get ComputerName from registry, using hostname")}let t=_t.hostname();return i.debug(`[DEVICE REG] Using hostname: ${t}`),t||"Unknown CLI Device"}catch(e){return i.debug(`[DEVICE REG] Error getting computer name: ${e}`),_t.hostname()||"Unknown CLI Device"}}async getHardwareDeviceId(){let e=_t.platform();try{let t=null;switch(e){case"darwin":try{let a=Ot("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],i.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=Ot("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],i.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Cs.readFile("/etc/machine-id","utf-8").then(r=>r.trim()),i.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Cs.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),i.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{i.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=Ot("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
+ `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),i.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{i.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:i.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let r=ji.createHash("sha256").update(t).digest("hex"),a=[r.substring(0,8),r.substring(8,12),r.substring(12,16),r.substring(16,20),r.substring(20,32)].join("-");return i.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Me)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${o}`):(o=ws(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID: ${o}`)),o}catch(t){i.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Me)),s="snowx_fallback_device_id",o=n.string(s);return o?i.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${o}`):(o=ws(),n.set(s,o),i.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${o}`)),o}}async registerDevice(e,t,n){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,n);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,n){try{let s=await this.api.getDocument(this.devicesCollection,e);if(s&&s.devices){let o=s.devices;if(o.some(a=>a.deviceId===t)){let a=o.map(l=>l.deviceId===t?{...l,lastSeenAt:je,computerName:n,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:je,lastSeenAt:je};o.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:o})}}else{let r={userId:e,devices:[{deviceId:t,computerName:n,type:"on-device",platform:"cli",registeredAt:je,lastSeenAt:je}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,r)}i.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:n})}catch(s){throw i.error("[DeviceRegistration] Failed to register device:",{userId:e,deviceId:t,error:s.message,code:s.code}),s}}getCurrentDeviceId(){return this.currentDeviceId}getCurrentUserId(){return this.currentUserId}getCurrentDeviceInfo(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,computerName:this.getComputerName()}}async refreshDeviceRegistration(){this.currentUserId&&this.currentDeviceId&&await this.autoRegisterDevice(this.currentUserId)}async removeDeviceRegistration(e){try{let t=await this.getUserDeviceId(e);if(!t||t.trim()===""){console.log("⚠️ [DEVICE REG] No device ID found, skipping device removal");return}let n=await this.api.getDocument(this.devicesCollection,e);if(!n||!n.devices||!Array.isArray(n.devices)){console.log("⚠️ [DEVICE REG] No devices document found for user");return}let s=n.devices;if(!s.some(a=>a.deviceId===t)){console.log(`⚠️ [DEVICE REG] Device ${t} not found in registration list`);return}let r=s.filter(a=>a.deviceId!==t);r.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:r})}catch(t){console.error(`❌ [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Ss={};ke(Ss,{AuthService:()=>z});import{EventEmitter as Xi}from"events";import{signInAnonymously as Vi,signInWithEmailAndPassword as Ki,createUserWithEmailAndPassword as Qi,signOut as Ji,onAuthStateChanged as xs,updateProfile as Yi,signInWithCustomToken as Zi}from"firebase/auth";import Ve from"axios";import go from"fs/promises";import Es from"path";import ea from"os";var z,le=D(()=>{"use strict";Mt();L();z=class c extends Xi{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=Es.join(ea.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=Es.dirname(this.tokenFilePath);await go.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(be(),Me)),t=e.string("snowx_auth_token"),n=e.string("snowx_access_token");if(!t||!n)try{let s=await go.readFile(this.tokenFilePath,"utf-8"),o=JSON.parse(s);o.expiresAt>Date.now()&&(console.log("🔄 Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",o.userId),e.set("snowx_access_token",o.token),t=o.userId,n=o.token,await go.unlink(this.tokenFilePath),console.log("✅ Migration completed - old auth file removed"))}catch{}if(t&&n){let s={token:n,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=s,i.debug("Session restored from UserDefaults");try{let o=await this.getUserProfile();o&&o.tier!==void 0?this.authToken.tier=o.tier:await this.updateUserTierFromToken(s)}catch(o){console.warn("⚠️ Failed to fetch user profile during session restore:",o instanceof Error?o.message:"Unknown error"),await this.updateUserTierFromToken(s)}this.emit("authenticated",s)}}catch(e){console.warn("⚠️ Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(be(),Me));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(()=>(be(),Me));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,xs(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}ce.setUserTier(t);let{UserDefaults:n}=await Promise.resolve().then(()=>(be(),Me));n.set("userSubscriptionTier",e.tier||0),n.set("isTrialUser",!1),i.debug(`User tier updated: ${ce.getDisplayName(t)} (${e.tier})`),i.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let e=await Vi(this.auth);this.currentUser=e.user;let t={token:`anonymous_${e.user.uid}`,userId:e.user.uid,tier:0,expiresAt:Date.now()+1440*60*1e3};return await this.saveToken(t),this.updateUserTierFromToken(t),!0}catch(e){return console.error("❌ Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let n=await Ki(this.auth,e,t);return this.currentUser=n.user,!0}catch(n){return console.error("❌ Failed to sign in with email:",n.message),!1}}async signUpWithEmail(e,t,n){if(!this.auth)return console.error("❌ Firebase auth not initialized"),!1;try{let s=await Qi(this.auth,e,t);return this.currentUser=s.user,n&&await Yi(s.user,{displayName:n}),!0}catch(s){return console.error("❌ Failed to sign up with email:",s.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(Xe(),mo));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("⚠️ [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Ji(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(()=>(Xe(),mo));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(be(),Me)),n=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let r of n)t.remove(r);if(e){let r=`snowx_device_id_${e}`;t.remove(r)}let o=t.getAllKeys().filter(r=>r.startsWith("snowx_device_id_"));for(let r of o)t.remove(r)}catch(t){console.warn("⚠️ [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await Ve.post(`${this.snowxAuthEndpoint}/login`,e):t=await Ve.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let n={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(n),!0}return!1}catch(t){return console.error("❌ Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await Ve.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(()=>(be(),Me));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(this.currentUser)try{return await this.currentUser.getIdToken(!0)}catch(t){console.error("❌ Failed to get Firebase ID token:",t)}if(this.auth){let n=await new Promise(s=>{let o=!1,r,a=xs(this.auth,async l=>{if(!o)if(o=!0,clearTimeout(r),a(),l)try{let u=await l.getIdToken(!0);s(u)}catch{s(null)}else s(null)});r=setTimeout(()=>{o||(o=!0,a(),s(null))},2e3)});if(n)return n}let e=await this.getAccessTokenFromStorage();return e?(i.debug("Using stored access token as fallback (Firebase SDK not signed in)"),e):null}getUserId(){return this.authToken?.userId||this.currentUser?.uid||null}getUserEmail(){return this.authToken?.email||this.currentUser?.email||null}async getUserTier(){if(this.authToken?.tier!==void 0)return this.authToken.tier;try{return(await this.getUserProfile())?.tier??0}catch{return console.warn("⚠️ Failed to fetch user tier, defaulting to Free tier"),0}}getCachedUserTier(){return this.authToken?.tier??0}isAuthenticated(){return!!this.authToken&&this.authToken.expiresAt>Date.now()}isFirebaseAuthenticated(){if(this.currentUser)return!0;if(this.authToken?.token&&this.isFirebaseIdToken(this.authToken.token)){let e=this.parseFirebaseIdToken(this.authToken.token);if(e&&Date.now()<=e.exp*1e3)return!0}return!1}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId(),t=this.authToken?.token;if(e&&t){i.debug("Using existing authentication token"),i.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e);try{if(this.isFirebaseIdToken(t)){let n=this.parseFirebaseIdToken(t);return n&&Date.now()<=n.exp*1e3?(i.debug("Firebase ID Token is still valid"),this.emit("AuthenticationComplete",e),!0):(i.error("Firebase ID Token has expired"),await this.clearStoredToken(),this.authToken=null,!1)}return await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}catch(n){return i.error("Failed to authenticate with Firebase during auto-authenticate:",n.message),n.response?.status===401||n.response?.status===403||n.response?.status===404?(i.error("Token is invalid - clearing stored credentials"),await this.clearStoredToken(),this.authToken=null):i.warn("Transient Firebase auth error - keeping stored token for retry"),!1}}}return!1}async authenticateFirebaseWithStoredToken(){if(console.log("🔥 [AUTH] Starting Firebase authentication..."),!this.auth)throw console.error("❌ [AUTH] Firebase Auth not initialized!"),i.error("Firebase Auth not initialized - cannot authenticate"),new Error("Firebase Auth not initialized. Please ensure ServiceManager is initialized first.");if(console.log("✅ [AUTH] Firebase Auth instance is available"),!this.authToken)throw console.error("❌ [AUTH] No auth token available!"),i.error("No auth token available - cannot authenticate with Firebase"),new Error("No authentication token available");if(console.log("✅ [AUTH] Auth token is available"),console.log(`📋 [AUTH] User ID: ${this.authToken.userId}`),this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log(`✅ [AUTH] Firebase already authenticated for user: ${this.authToken.userId}`),i.debug("🔥 Firebase already authenticated for user:",this.authToken.userId);return}try{console.log(`🔑 [AUTH] Requesting custom token from API for user: ${this.authToken.userId}`),i.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId);console.log("✅ [AUTH] Custom token received from API"),console.log("🔐 [AUTH] Signing into Firebase with custom token..."),i.debug("Signing into Firebase with custom token...");let t=await Zi(this.auth,e);console.log(`✅ [AUTH] Firebase sign-in successful - UID: ${t.user.uid}`),i.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user,console.log("✅ Firebase authentication successful")}catch(e){throw console.error("❌ [AUTH] Firebase authentication FAILED!"),console.error(`❌ [AUTH] Error details: ${e.message}`),console.error(`❌ [AUTH] Error code: ${e.code||"none"}`),console.error(`❌ [AUTH] HTTP status: ${e.response?.status||"none"}`),i.error("Firebase authentication failed:",{userId:this.authToken.userId,errorMessage:e.message,errorCode:e.code,errorStatus:e.response?.status,errorData:e.response?.data}),new Error(`Firebase authentication failed: ${e.message}`)}}async getCustomTokenFromAPIInternal(e,t=3){let n=4-t;console.log(`📡 [AUTH-API] Attempt ${n}/3: Getting custom token for user: ${e}`),i.debug(`Getting custom token from API for user: ${e} (attempt ${n}/3)`);let s="https://snowx.ai/api-beta/api/fb/custom-token",o={userId:e},r=this.authToken?.token,a={"Content-Type":"application/json"};r?(a.Authorization=`Bearer ${r}`,console.log("📋 [AUTH-API] Access token added to request headers")):console.warn("⚠️ [AUTH-API] No access token available for authorization"),console.log(`📡 [AUTH-API] Sending POST to: ${s}`);try{let l=await Ve.post(s,o,{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"),i.debug("Successfully received custom token from SnowX API"),u.customToken}catch(l){if(console.error(`❌ [AUTH-API] Request failed on attempt ${n}/3`),console.error(`❌ [AUTH-API] Error message: ${l.message}`),console.error(`❌ [AUTH-API] Error code: ${l.code||"none"}`),console.error(`❌ [AUTH-API] HTTP status: ${l.response?.status||"none"}`),l.response?.data&&console.error(`❌ [AUTH-API] Response data: ${JSON.stringify(l.response.data)}`),i.error("Failed to get custom token:",{attempt:n,error:l.message,code:l.code,status:l.response?.status,responseData:l.response?.data}),t>0&&(l.code==="ECONNABORTED"||l.code==="ETIMEDOUT"||l.code==="ECONNREFUSED"||l.code==="ENOTFOUND"||l.response?.status>=500&&l.response?.status<600)){let d=Math.pow(2,n)*1e3;return console.log(`⏳ [AUTH-API] Retrying in ${d}ms... (${t-1} attempts remaining)`),i.debug(`Retrying in ${d}ms...`),await new Promise(p=>setTimeout(p,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 n=JSON.parse(Buffer.from(t[1],"base64url").toString());return{userId:n.user_id||n.sub,email:n.email,name:n.name,exp:n.exp}}catch{return null}}async authenticateWithAccessToken(e){try{return this.isFirebaseIdToken(e)?await this.authenticateWithFirebaseIdToken(e):await this.authenticateWithSnowXAccessToken(e)}catch(t){return console.error("❌ Failed to authenticate with access token:",t.response?.data?.message||t.message),console.error("Full error details:",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,url:t.config?.url}),!1}}async authenticateWithFirebaseIdToken(e){console.log("🔥 Detected Firebase ID Token, using direct authentication...");let t=this.parseFirebaseIdToken(e);if(!t)return console.error("❌ Failed to parse Firebase ID Token"),!1;if(Date.now()>t.exp*1e3)return console.error("❌ Firebase ID Token has expired"),!1;console.log(`📋 User ID from token: ${t.userId}`),console.log(`📋 Email from token: ${t.email||"N/A"}`);let n={token:e,userId:t.userId,email:t.email,tier:0,expiresAt:t.exp*1e3};await this.saveToken(n);try{let s=await this.getUserProfileWithIdToken(e,t.userId);s&&(this.authToken.tier=s.tier,await this.saveToken(this.authToken))}catch{console.warn("⚠️ Failed to fetch user profile, using default tier")}return this.userProfile={name:t.name,email:t.email},await this.updateUserTierFromToken(this.authToken),this.emit("authStateChanged",this.authToken),this.emit("AuthenticationComplete",t.userId),console.log("✅ Firebase ID Token authentication successful!"),!0}async getUserProfileWithIdToken(e,t){try{let n=await Ve.get(`https://snowx.ai/api-beta/api/fb/documents/${t}?collection=users`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(n.data?.success&&n.data?.doc){let s=n.data.doc,o=s.subscription?.tier??0;return{id:t,email:s.email,tier:o}}return null}catch(n){return console.warn(`⚠️ Failed to fetch user profile with ID Token: ${n.response?.status||n.message}`),null}}async authenticateWithSnowXAccessToken(e){let t=await Ve.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let n=t.data.data,s=n.id||n.uid||n.user_id||n.userId||n.email;if(!s)throw new Error("No user ID found in API response");let o={token:e,userId:s,email:n.email,tier:n.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};await this.saveToken(o),this.userProfile=n,await this.updateUserTierFromToken(o);try{await this.authenticateFirebaseWithStoredToken()}catch(r){throw r.response?.status===401||r.response?.status===403||r.response?.status===404?(i.error("Firebase auth failed with permanent error - clearing token"),await this.clearStoredToken(),this.authToken=null,this.userProfile=null):i.warn("Firebase auth failed with transient error - keeping token for retry"),r}return this.emit("authStateChanged",o),this.emit("AuthenticationComplete",s),!0}return!1}async getUserInfo(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available"),null;try{let e=await Ve.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});return e.data?.data?(this.userProfile=e.data.data,this.userProfile):null}catch(e){throw e.response?.status===401&&(console.warn("⚠️ Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),n=t===1?1:t===2?2:0;return ce.isModelAccessible(e,n)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("⚠️ No auth token available for profile fetch"),null;try{let e=await Ve.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,n=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=n,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:n}}return console.warn("⚠️ Empty response from profile API"),null}catch(e){return console.warn(`⚠️ Failed to fetch user profile: ${e.response?.status||e.message}`),this.authToken.tier=0,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),null}}async hasUserProfile(){return await this.getUserProfile()!==null}}});var ks={};ke(ks,{MessageQueueManager:()=>Ie});import{EventEmitter as ta}from"events";var Ie,mt=D(()=>{"use strict";L();Ie=class c extends ta{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),i.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),i.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});import{encode as Is,decode as Ps,isWithinTokenLimit as As,countTokens as na}from"gpt-tokenizer/encoding/cl100k_base";var gt,oa,sa,Se,ht=D(()=>{"use strict";gt=25e3,oa=1400,sa=17e3,Se=class{maxResponseTokens;previewTokens;maxContentTokens;constructor(e){this.maxResponseTokens=e?.maxResponseTokens??gt,this.previewTokens=e?.previewTokens??oa,this.maxContentTokens=e?.maxContentTokens??sa}count(e){return e?na(e):0}encode(e){return e?Is(e):[]}decode(e){return!e||e.length===0?"":Ps(e)}isWithinLimit(e,t){return e?As(e,t??this.maxResponseTokens):0}exceedsResponseLimit(e){return this.isWithinLimit(e,this.maxResponseTokens)===!1}exceedsContentLimit(e){return this.isWithinLimit(e,this.maxContentTokens)===!1}truncate(e,t){if(!e)return{text:"",tokens:0,truncated:!1};let n=t??this.maxResponseTokens,s=As(e,n);if(s!==!1)return{text:e,tokens:s,truncated:!1};let r=Is(e).slice(0,n);return{text:Ps(r),tokens:n,truncated:!0}}generatePreview(e,t){if(!e)return{preview:"",totalTokens:0,previewTokens:0,remainingTokens:0};let n=t??this.previewTokens,s=this.count(e);if(s<=n)return{preview:e,totalTokens:s,previewTokens:s,remainingTokens:0};let{text:o,tokens:r}=this.truncate(e,n);return{preview:o,totalTokens:s,previewTokens:r,remainingTokens:s-r}}truncateContent(e,t){let n=t??this.maxContentTokens,s=this.truncate(e,n);return s.truncated?s.text+`
4
+ ... [Content truncated at ${s.tokens.toLocaleString()} tokens]`:e}truncateOutput(e,t){let n=t??this.maxResponseTokens,s=this.truncate(e,n);return s.truncated?s.text+`
5
5
 
6
- [Output truncated at ${o.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,n){let{preview:o,totalTokens:s,previewTokens:r,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`Response too large (${s.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
6
+ [Output truncated at ${s.tokens.toLocaleString()} tokens]`:e}formatLargeResponsePreview(e,t,n){let{preview:s,totalTokens:o,previewTokens:r,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`Response too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit), saved to temporary file.
7
7
 
8
8
  `;return l+=`TEMP FILE PATH: ${t}
9
9
  `,l+=`Use read_file, grep, cat, or other tools to access the full content.
10
10
 
11
11
  `,l+=`PREVIEW (first ${r.toLocaleString()} tokens):
12
12
  `,l+=`${"─".repeat(50)}
13
- `,l+=o,a>0&&(l+=`
13
+ `,l+=s,a>0&&(l+=`
14
14
  ${"─".repeat(50)}`,l+=`
15
15
  ... (${a.toLocaleString()} more tokens available in temp file)`),l+=`
16
16
 
17
- To read full content: use tools like 'read_file' with path above`,l}formatLargeFileMessage(e,t,n){let{preview:o,totalTokens:s,previewTokens:r,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`File too large (${s.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit).
17
+ To read full content: use tools like 'read_file' with path above`,l}formatLargeFileMessage(e,t,n){let{preview:s,totalTokens:o,previewTokens:r,remainingTokens:a}=this.generatePreview(e,n?.previewTokens??this.previewTokens),l=`File too large (${o.toLocaleString()} tokens > ${this.maxResponseTokens.toLocaleString()} limit).
18
18
 
19
19
  `;return l+=`FILE PATH: ${t}
20
20
 
@@ -22,37 +22,37 @@ To read full content: use tools like 'read_file' with path above`,l}formatLargeF
22
22
 
23
23
  `,l+=`PREVIEW (first ${r.toLocaleString()} tokens):
24
24
  `,l+=`${"─".repeat(50)}
25
- `,l+=o,a>0&&(l+=`
25
+ `,l+=s,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 Vi}from"events";var Ts,ys,Ki,Qi,Ji,Ot,Ss,io=D(()=>{"use strict";$();Ts=10,ys=2e3,Ki=5e3,Qi=200,Ji=3e3,Ot=class c extends Vi{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),i.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:i.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:n}=e;if(!t||!n){i.debug("[SubAgentManager] Invalid spawn_agents_started event");return}this.cleanupOldOperations();let o={operationId:t,totalAgents:n,agents:new Map,status:"starting",startTime:new Date};for(let s=1;s<=n;s++)o.agents.set(s,{agentNumber:s,task:"",status:"pending"});this.operations.set(t,o),i.debug(`[SubAgentManager] Spawn started: ${t} with ${n} agents`),this.emit("spawn_started",{operationId:t,totalAgents:n}),this.emitProgressUpdate(t)}handleAgentStarted(e){let{operationId:t,agentNumber:n,task:o}=e;if(!t||!n)return;let s=this.operations.get(t);if(!s){i.debug(`[SubAgentManager] Operation not found: ${t}`);return}s.status==="starting"&&(s.status="running");let r=this.truncateString(o||"",Qi);s.agents.set(n,{agentNumber:n,task:r,status:"running",startTime:new Date}),i.debug(`[SubAgentManager] Agent ${n} started: ${r.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:n,task:r}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:n,content:o}=e;if(!t||!n||!o)return;let s=this.operations.get(t);if(!s)return;let r=s.agents.get(n);if(!r)return;let l=(r.streamingContent||"")+o;l.length>ys?r.streamingContent=l.slice(-ys):r.streamingContent=l,this.emit("agent_streaming",{operationId:t,agentNumber:n,content:r.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:n,result:o,error:s}=e;if(!t||!n)return;let r=this.operations.get(t);if(!r)return;let a=r.agents.get(n);if(!a)return;let l=s?"failed":"completed";a.status=l,a.endTime=new Date,a.result=this.truncateString(o||"",Ki),a.error=s;let u=a.startTime?(a.endTime.getTime()-a.startTime.getTime())/1e3:0;i.debug(`[SubAgentManager] Agent ${n} ${l} (${u.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:n,status:l,duration:u}),this.emitProgressUpdate(t)}handleSpawnCompleted(e){let{operationId:t}=e;if(!t)return;let n=this.operations.get(t);if(!n)return;let o=Array.from(n.agents.values()),s=o.some(d=>d.status==="failed"),r=o.every(d=>d.status==="completed"||d.status==="failed");n.status=s?"failed":"completed",n.endTime=new Date;let a=(n.endTime.getTime()-n.startTime.getTime())/1e3,l=o.filter(d=>d.status==="completed").length,u=o.filter(d=>d.status==="failed").length;i.debug(`[SubAgentManager] Spawn completed: ${l} success, ${u} failed (${a.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:n.status,duration:a,successCount:l,failCount:u,totalAgents:n.totalAgents}),this.emitProgressUpdate(t),this.scheduleCleanup(t)}emitProgressUpdate(e){let t=this.operations.get(e);if(!t)return;let n=Array.from(t.agents.values()),o=n.filter(l=>l.status==="pending").length,s=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="completed").length,a=n.filter(l=>l.status==="failed").length;this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:o,running:s,completed:r,failed:a,agents:n.map(l=>({agentNumber:l.agentNumber,task:l.task,status:l.status}))})}getProgressString(e){let t=this.operations.get(e);if(!t)return"";let n=Array.from(t.agents.values()),o=n.filter(d=>d.status==="pending").length,s=n.filter(d=>d.status==="running").length,r=n.filter(d=>d.status==="completed").length,a=n.filter(d=>d.status==="failed").length,u=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${r}/${t.totalAgents} complete`;return s>0&&(u+=` (${s} running)`),a>0&&(u+=` [${a} failed]`),u}getAgentListString(e){let t=this.operations.get(e);if(!t)return"";let n=[],o=Array.from(t.agents.values()).sort((s,r)=>s.agentNumber-r.agentNumber);for(let s of o){let r={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[s.status]||"❓",a=s.task?`: ${s.task.substring(0,60)}${s.task.length>60?"...":""}`:"";n.push(` ${r} Agent ${s.agentNumber}${a}`),s.error&&n.push(` └─ Error: ${s.error.substring(0,80)}${s.error.length>80?"...":""}`)}return n.join(`
28
- `)}cleanupOldOperations(){if(this.operations.size<Ts)return;let e=[];for(let[n,o]of this.operations)(o.status==="completed"||o.status==="failed")&&e.push({id:n,endTime:o.endTime?.getTime()||o.startTime.getTime()});e.sort((n,o)=>n.endTime-o.endTime);let t=e.slice(0,Math.max(1,e.length-Ts+1));for(let{id:n}of t){this.operations.delete(n);let o=this.cleanupTimers.get(n);o&&(clearTimeout(o),this.cleanupTimers.delete(n)),i.debug(`[SubAgentManager] Cleaned up old operation: ${n}`)}}scheduleCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),i.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},Ji);this.cleanupTimers.set(e,n)}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(),i.debug("[SubAgentManager] Cleared all operations")}},Ss=Ot.getInstance()});var en,ws=D(()=>{"use strict";$();en=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),i.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[o,s]of this.tools.entries())if(o.toLowerCase()===n)return s}async executeTool(e,t,n,o){let s=this.getTool(e);if(!s)return i.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{i.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await s.execute(t,e,n,o),l=Date.now()-r;i.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 i.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let o of this.tools.keys())o.toLowerCase()===t&&n.push(o);for(let o of n)this.tools.delete(o);i.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),i.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var Cs={};Ee(Cs,{ToolDisplay:()=>F});import X from"chalk";var F,Ie=D(()=>{"use strict";F=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,n){if(c.customUIMode)return;let o=this.getToolPrefix(e);if(console.log(X.cyan(`
30
- ${o} ${X.bold(e)}`)),t&&console.log(X.gray(` ${t}`)),n){let s=n.length>120?n.substring(0,120)+X.gray("..."):n;console.log(X.white(` ${s}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(c.customUIMode)return;let{toolName:t,output:n,success:o,executionTime:s,truncateLines:r=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,r):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,r):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,r):a=this.formatGenericOutput(n,r)),a&&a.trim()&&console.log(a);let l=o?X.green("✓"):X.red("✗"),u=o?X.green("SUCCESS"):X.red("FAILED"),d=s?X.gray(` (${s}ms)`):"";console.log(`${l} ${u}${d}
27
+ ... (${a.toLocaleString()} more tokens)`),l}get maxResponse(){return this.maxResponseTokens}get maxContent(){return this.maxContentTokens}get maxPreview(){return this.previewTokens}}});import{EventEmitter as ra}from"events";var Ds,Ns,ia,aa,ca,Ft,Rs,ho=D(()=>{"use strict";L();Ds=10,Ns=2e3,ia=5e3,aa=200,ca=3e3,Ft=class c extends ra{static instance;operations=new Map;cleanupTimers=new Map;constructor(){super(),i.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:i.debug(`[SubAgentManager] Unknown event type: ${t}`)}}handleSpawnStarted(e){let{operationId:t,totalAgents:n}=e;if(!t||!n){i.debug("[SubAgentManager] Invalid spawn_agents_started event");return}this.cleanupOldOperations();let s={operationId:t,totalAgents:n,agents:new Map,status:"starting",startTime:new Date};for(let o=1;o<=n;o++)s.agents.set(o,{agentNumber:o,task:"",status:"pending"});this.operations.set(t,s),i.debug(`[SubAgentManager] Spawn started: ${t} with ${n} agents`),this.emit("spawn_started",{operationId:t,totalAgents:n}),this.emitProgressUpdate(t)}handleAgentStarted(e){let{operationId:t,agentNumber:n,task:s}=e;if(!t||!n)return;let o=this.operations.get(t);if(!o){i.debug(`[SubAgentManager] Operation not found: ${t}`);return}o.status==="starting"&&(o.status="running");let r=this.truncateString(s||"",aa);o.agents.set(n,{agentNumber:n,task:r,status:"running",startTime:new Date}),i.debug(`[SubAgentManager] Agent ${n} started: ${r.substring(0,50)}...`),this.emit("agent_started",{operationId:t,agentNumber:n,task:r}),this.emitProgressUpdate(t)}handleAgentStreaming(e){let{operationId:t,agentNumber:n,content:s}=e;if(!t||!n||!s)return;let o=this.operations.get(t);if(!o)return;let r=o.agents.get(n);if(!r)return;let l=(r.streamingContent||"")+s;l.length>Ns?r.streamingContent=l.slice(-Ns):r.streamingContent=l,this.emit("agent_streaming",{operationId:t,agentNumber:n,content:r.streamingContent})}handleAgentCompleted(e){let{operationId:t,agentNumber:n,result:s,error:o}=e;if(!t||!n)return;let r=this.operations.get(t);if(!r)return;let a=r.agents.get(n);if(!a)return;let l=o?"failed":"completed";a.status=l,a.endTime=new Date,a.result=this.truncateString(s||"",ia),a.error=o;let u=a.startTime?(a.endTime.getTime()-a.startTime.getTime())/1e3:0;i.debug(`[SubAgentManager] Agent ${n} ${l} (${u.toFixed(1)}s)`),this.emit("agent_completed",{operationId:t,agentNumber:n,status:l,duration:u}),this.emitProgressUpdate(t)}handleSpawnCompleted(e){let{operationId:t}=e;if(!t)return;let n=this.operations.get(t);if(!n)return;let s=Array.from(n.agents.values()),o=s.some(d=>d.status==="failed"),r=s.every(d=>d.status==="completed"||d.status==="failed");n.status=o?"failed":"completed",n.endTime=new Date;let a=(n.endTime.getTime()-n.startTime.getTime())/1e3,l=s.filter(d=>d.status==="completed").length,u=s.filter(d=>d.status==="failed").length;i.debug(`[SubAgentManager] Spawn completed: ${l} success, ${u} failed (${a.toFixed(1)}s)`),this.emit("spawn_completed",{operationId:t,status:n.status,duration:a,successCount:l,failCount:u,totalAgents:n.totalAgents}),this.emitProgressUpdate(t),this.scheduleCleanup(t)}emitProgressUpdate(e){let t=this.operations.get(e);if(!t)return;let n=Array.from(t.agents.values()),s=n.filter(l=>l.status==="pending").length,o=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="completed").length,a=n.filter(l=>l.status==="failed").length;this.emit("progress",{operationId:e,status:t.status,totalAgents:t.totalAgents,pending:s,running:o,completed:r,failed:a,agents:n.map(l=>({agentNumber:l.agentNumber,task:l.task,status:l.status}))})}getProgressString(e){let t=this.operations.get(e);if(!t)return"";let n=Array.from(t.agents.values()),s=n.filter(d=>d.status==="pending").length,o=n.filter(d=>d.status==="running").length,r=n.filter(d=>d.status==="completed").length,a=n.filter(d=>d.status==="failed").length,u=`${{starting:"🚀",running:"⏳",completed:"✅",failed:"❌"}[t.status]||"❓"} Sub-agents: ${r}/${t.totalAgents} complete`;return o>0&&(u+=` (${o} running)`),a>0&&(u+=` [${a} failed]`),u}getAgentListString(e){let t=this.operations.get(e);if(!t)return"";let n=[],s=Array.from(t.agents.values()).sort((o,r)=>o.agentNumber-r.agentNumber);for(let o of s){let r={pending:"⏸️",running:"🔄",completed:"✅",failed:"❌",timeout:"⏰"}[o.status]||"❓",a=o.task?`: ${o.task.substring(0,60)}${o.task.length>60?"...":""}`:"";n.push(` ${r} Agent ${o.agentNumber}${a}`),o.error&&n.push(` └─ Error: ${o.error.substring(0,80)}${o.error.length>80?"...":""}`)}return n.join(`
28
+ `)}cleanupOldOperations(){if(this.operations.size<Ds)return;let e=[];for(let[n,s]of this.operations)(s.status==="completed"||s.status==="failed")&&e.push({id:n,endTime:s.endTime?.getTime()||s.startTime.getTime()});e.sort((n,s)=>n.endTime-s.endTime);let t=e.slice(0,Math.max(1,e.length-Ds+1));for(let{id:n}of t){this.operations.delete(n);let s=this.cleanupTimers.get(n);s&&(clearTimeout(s),this.cleanupTimers.delete(n)),i.debug(`[SubAgentManager] Cleaned up old operation: ${n}`)}}scheduleCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),i.debug(`[SubAgentManager] Cleaned up operation: ${e}`)},ca);this.cleanupTimers.set(e,n)}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(),i.debug("[SubAgentManager] Cleared all operations")}},Rs=Ft.getInstance()});var sn,Ms=D(()=>{"use strict";L();sn=class{tools=new Map;register(e){for(let t of e.toolNames)this.tools.set(t,e),i.debug(`[ToolRegistry] Registered tool: ${t}`)}getTool(e){let t=this.tools.get(e);if(t)return t;let n=e.toLowerCase();for(let[s,o]of this.tools.entries())if(s.toLowerCase()===n)return o}async executeTool(e,t,n,s){let o=this.getTool(e);if(!o)return i.error(`[ToolRegistry] Unknown tool: ${e}`),{id:t,toolName:e,success:!1,output:"",error:`Unknown tool: ${e}`};try{i.debug(`[ToolRegistry] Executing tool: ${e} (id: ${t})`);let r=Date.now(),a=await o.execute(t,e,n,s),l=Date.now()-r;i.debug(`[ToolRegistry] Tool ${e} completed in ${l}ms`);let u=a.map(d=>d.text||"").join(`
29
+ `);return{id:t,toolName:e,success:!0,output:u,content:a}}catch(r){return i.error(`[ToolRegistry] Tool execution error (${e}):`,r),{id:t,toolName:e,success:!1,output:"",error:r instanceof Error?r.message:String(r)}}}getAllToolNames(){return Array.from(this.tools.keys())}hasToolRegistered(e){return this.getTool(e)!==void 0}unregister(e){let t=e.toLowerCase(),n=[];for(let s of this.tools.keys())s.toLowerCase()===t&&n.push(s);for(let s of n)this.tools.delete(s);i.debug(`[ToolRegistry] Unregistered tool: ${e}`)}clear(){this.tools.clear(),i.debug("[ToolRegistry] All tools unregistered")}getToolCount(){return this.tools.size}}});var _s={};ke(_s,{ToolDisplay:()=>F});import K from"chalk";var F,Pe=D(()=>{"use strict";F=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,n){if(c.customUIMode)return;let s=this.getToolPrefix(e);if(console.log(K.cyan(`
30
+ ${s} ${K.bold(e)}`)),t&&console.log(K.gray(` ${t}`)),n){let o=n.length>120?n.substring(0,120)+K.gray("..."):n;console.log(K.white(` ${o}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"▸":t.includes("write")?"→":t.includes("edit")?"✎":t.includes("read")?"◆":t.includes("search")||t.includes("grep")?"⌕":"•"}static result(e){if(c.customUIMode)return;let{toolName:t,output:n,success:s,executionTime:o,truncateLines:r=50}=e,a=n||"";n&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(n,r):t.toLowerCase().includes("write")?a=this.formatWriteOutput(n,r):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(n,r):a=this.formatGenericOutput(n,r)),a&&a.trim()&&console.log(a);let l=s?K.green("✓"):K.red("✗"),u=s?K.green("SUCCESS"):K.red("FAILED"),d=o?K.gray(` (${o}ms)`):"";console.log(`${l} ${u}${d}
31
31
  `)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
32
- `),u=a.slice(0,20).map(d=>X.gray(" ")+d).join(`
32
+ `),u=a.slice(0,20).map(d=>K.gray(" ")+d).join(`
33
33
  `);return a.length>20&&(u+=`
34
- `+X.gray(` ... (${a.length-20} more lines)`)),u}let n=e.split(`
35
- `),o=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),s="";o&&(s+=X.gray(" ")+X.dim(o[1])+`
36
- `);let r=n.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(s+=r.slice(0,10).map(a=>X.gray(" ")+X.dim(a)).join(`
37
- `),r.length>10&&(s+=`
38
- `+X.gray(` ... (${r.length-10} more changes)`)),s):this.truncateOutput(e,Math.min(15,t))}static formatWriteOutput(e,t){return this.truncateOutput(e,Math.min(15,t))}static formatBashOutput(e,t){return this.truncateOutput(e,Math.min(30,t))}static formatGenericOutput(e,t){return this.truncateOutput(e,Math.min(20,t))}static truncateOutput(e,t){let n=e.split(`
39
- `).filter(r=>r.trim());if(n.length===0)return"";if(n.length<=t)return n.map(r=>X.gray(" ")+X.dim(r)).join(`
40
- `);let s=n.slice(0,t).map(r=>X.gray(" ")+X.dim(r)).join(`
41
- `);return s+=`
42
- `+X.gray(` ... (${n.length-t} more lines)`),s}static error(e,t){c.customUIMode||(console.log(`
43
- ${X.red("✗")} ${X.red.bold(e)} ${X.red("ERROR")}`),console.log(X.gray(" ")+X.white(t)),console.log(""))}}});import xs from"os";import ao from"path";function tn(){return process.platform==="win32"}function tt(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,xs.homedir())),tn()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,xs.homedir())),!tn()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),tn()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function gt(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=tt(c);if(tn()){let n=ao.basename(e).split(".")[0].toUpperCase();if(Yi.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return ao.isAbsolute(e)?ao.resolve(e).includes("..")?{valid:!1,error:`Security Error: Path traversal not allowed: ${c}`}:{valid:!0}:{valid:!1,error:`Invalid path format: "${c}"
34
+ `+K.gray(` ... (${a.length-20} more lines)`)),u}let n=e.split(`
35
+ `),s=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),o="";s&&(o+=K.gray(" ")+K.dim(s[1])+`
36
+ `);let r=n.filter(a=>a.toLowerCase().includes("replaced")||a.includes("→")||a.includes("->"));return r.length>0?(o+=r.slice(0,10).map(a=>K.gray(" ")+K.dim(a)).join(`
37
+ `),r.length>10&&(o+=`
38
+ `+K.gray(` ... (${r.length-10} more changes)`)),o):this.truncateOutput(e,Math.min(15,t))}static formatWriteOutput(e,t){return this.truncateOutput(e,Math.min(15,t))}static formatBashOutput(e,t){return this.truncateOutput(e,Math.min(30,t))}static formatGenericOutput(e,t){return this.truncateOutput(e,Math.min(20,t))}static truncateOutput(e,t){let n=e.split(`
39
+ `).filter(r=>r.trim());if(n.length===0)return"";if(n.length<=t)return n.map(r=>K.gray(" ")+K.dim(r)).join(`
40
+ `);let o=n.slice(0,t).map(r=>K.gray(" ")+K.dim(r)).join(`
41
+ `);return o+=`
42
+ `+K.gray(` ... (${n.length-t} more lines)`),o}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 Os from"os";import fo from"path";function rn(){return process.platform==="win32"}function rt(c){if(!c)return c;let e=c.trim();return e.startsWith("~")&&(e=e.replace(/^~/,Os.homedir())),rn()&&e.includes("%USERPROFILE%")&&(e=e.replace(/%USERPROFILE%/g,Os.homedir())),!rn()&&e.startsWith("Users/")&&(e="/"+e,console.log("🔧 [Path] Fixed path missing leading slash")),rn()&&e.startsWith("Users\\")&&!e.match(/^[A-Z]:/i)&&(e="C:\\"+e,console.log("🔧 [Path] Fixed Windows path missing drive letter")),e}function ft(c){if(!c||typeof c!="string")return{valid:!1,error:"File path is required"};let e=rt(c);if(rn()){let n=fo.basename(e).split(".")[0].toUpperCase();if(la.includes(n))return{valid:!1,error:`Security Error: Reserved device name not allowed: ${n}`}}return fo.isAbsolute(e)?fo.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 Yi,nn=D(()=>{"use strict";Yi=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import Es from"path";var Zi,ea,on,ks=D(()=>{"use strict";$();Ie();nn();mt();Zi=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],ea={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"},on=class{toolNames=["read","Read"];async execute(e,t,n,o){let s=n.file_path||n.path,r=n.offset,a=n.limit;if(!s)throw new Error("Missing file_path or path argument");let l=tt(s),u=gt(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];i.debug(`[ReadFileTool] Reading file: ${l}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();F.start("Read",n.description,l);try{let p=await import("fs/promises");try{await p.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let m=await p.stat(l);if(m.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let h=Es.extname(l).substring(1).toLowerCase();if(Zi.includes(h)){i.debug(`[ReadFileTool] Image file detected: ${l}`);let C=(await p.readFile(l)).toString("base64"),E=ea[h]||"application/octet-stream",g=Es.basename(l);i.debug(`[ReadFileTool] Image converted to base64: ${g} (${C.length} chars)`);let T=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:`Image loaded: ${g}`,success:!0,executionTime:T}),[{type:"image_url",image_url:{url:`data:${E};base64,${C}`}}]}let y=await p.readFile(l,"utf-8"),S=y.length,b=y.split(`
49
- `),w=b.length,k=Math.max(r??0,0),v=new ye;if(r===void 0&&a===void 0&&v.exceedsResponseLimit(y)){let N=v.count(y),C=m.size/1024,E=C/1024,g=E>=1?`${E.toFixed(2)} MB`:`${C.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
48
+ Correct: /Users/username/Downloads/file.pdf`}}var la,an=D(()=>{"use strict";la=["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]});import Fs from"path";var ua,da,cn,$s=D(()=>{"use strict";L();Pe();an();ht();ua=["png","jpg","jpeg","gif","bmp","webp","ico","tiff","tif"],da={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"},cn=class{toolNames=["read","Read"];async execute(e,t,n,s){let o=n.file_path||n.path,r=n.offset,a=n.limit;if(!o)throw new Error("Missing file_path or path argument");let l=rt(o),u=ft(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];i.debug(`[ReadFileTool] Reading file: ${l}${r!==void 0?`, offset: ${r}`:""}${a!==void 0?`, limit: ${a}`:""}`);let d=Date.now();F.start("Read",n.description,l);try{let p=await import("fs/promises");try{await p.access(l)}catch{return[{type:"text",text:`Error: File does not exist at path: ${l}`}]}let m=await p.stat(l);if(m.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${l}`}];let g=Fs.extname(l).substring(1).toLowerCase();if(ua.includes(g)){i.debug(`[ReadFileTool] Image file detected: ${l}`);let N=(await p.readFile(l)).toString("base64"),k=da[g]||"application/octet-stream",f=Fs.basename(l);i.debug(`[ReadFileTool] Image converted to base64: ${f} (${N.length} chars)`);let v=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:`Image loaded: ${f}`,success:!0,executionTime:v}),[{type:"image_url",image_url:{url:`data:${k};base64,${N}`}}]}let y=await p.readFile(l,"utf-8"),T=y.length,S=y.split(`
49
+ `),w=S.length,E=Math.max(r??0,0),b=new Se;if(r===void 0&&a===void 0&&b.exceedsResponseLimit(y)){let q=b.count(y),N=m.size/1024,k=N/1024,f=k>=1?`${k.toFixed(2)} MB`:`${N.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
50
50
 
51
51
  File Information:
52
52
  - Path: ${l}
53
- - Size: ${g} (${N.toLocaleString()} tokens)
53
+ - Size: ${f} (${q.toLocaleString()} tokens)
54
54
  - Total Lines: ${w}
55
- - Token Limit: ${pt.toLocaleString()}
55
+ - Token Limit: ${gt.toLocaleString()}
56
56
 
57
57
  Suggested Solutions:
58
58
  1. Read specific lines using offset and limit:
@@ -66,19 +66,19 @@ Suggested Solutions:
66
66
  - Lines 2000-4000: Read(path: "${l}", offset: 2000, limit: 2000)
67
67
  - And so on...
68
68
 
69
- The file has ${w.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(w===0||y.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(k>=w)return[{type:"text",text:`Error: Offset ${k} is beyond file length. File has ${w} total lines. Try a smaller offset (0 to ${w-1}).`}];let x=a!==void 0?Math.min(k+a,w):w,P=b.slice(k,x),A=P.map((N,C)=>`${(k+C+1).toString().padStart(6," ")} ${N}`).join(`
70
- `),B=A;if(r!==void 0||a!==void 0){let N=`
69
+ The file has ${w.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(w===0||y.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(E>=w)return[{type:"text",text:`Error: Offset ${E} is beyond file length. File has ${w} total lines. Try a smaller offset (0 to ${w-1}).`}];let C=a!==void 0?Math.min(E+a,w):w,P=S.slice(E,C),R=P.map((q,N)=>`${(E+N+1).toString().padStart(6," ")} ${q}`).join(`
70
+ `),O=R;if(r!==void 0||a!==void 0){let q=`
71
71
 
72
- [Read ${P.length} lines (${k+1}-${x}) of ${w} total lines]`;B=A+N}let _=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:B,success:!0,executionTime:_}),[{type:"text",text:B}]}catch(p){i.debug(`[ReadFileTool] Failed to read file: ${p.message}`);let m;p.code==="ENOENT"?m=`Error: File does not exist at path: ${l}`:p.code==="EACCES"?m=`Error: Permission denied. Cannot read file: ${l}`:p.code==="EISDIR"?m=`Error: Path is a directory, not a file: ${l}`:m=`Error reading file: ${p.message}`;let h=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:m,success:!1,executionTime:h}),[{type:"text",text:m}]}}}});import sn from"fs/promises";import ta from"form-data";import co from"axios";import lo from"path";var rn,Is=D(()=>{"use strict";$();Ie();ce();rn=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,o){let s=n.path;if(!s)throw new Error("Missing path argument");i.debug(`[ReadSpecialFileTool] Converting file: ${s}`);let r=Date.now();F.start("ReadSpecialFile",n.description,s);try{try{await sn.access(s)}catch{return[{type:"text",text:`Error: File does not exist at path: ${s}`}]}let a=lo.extname(s).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let k=this.supportedExtensions.join(", ");return[{type:"text",text:`Error: Unsupported file type '${a}'. The read_special_file tool only supports Microsoft Office documents (docx, doc, xlsx, xls, pptx, ppt), PDF files (pdf), audio/video files (mp3, mp4, wav), web files (html, htm), and images (png, jpg, jpeg, gif, bmp, webp, ico). For plain text files, use the run_command tool with 'cat' instead.
72
+ [Read ${P.length} lines (${E+1}-${C}) of ${w} total lines]`;O=R+q}let j=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:O,success:!0,executionTime:j}),[{type:"text",text:O}]}catch(p){i.debug(`[ReadFileTool] Failed to read file: ${p.message}`);let m;p.code==="ENOENT"?m=`Error: File does not exist at path: ${l}`:p.code==="EACCES"?m=`Error: Permission denied. Cannot read file: ${l}`:p.code==="EISDIR"?m=`Error: Path is a directory, not a file: ${l}`:m=`Error reading file: ${p.message}`;let g=Date.now()-d;return F.result({toolName:"Read",filePath:l,output:m,success:!1,executionTime:g}),[{type:"text",text:m}]}}}});import ln from"fs/promises";import pa from"form-data";import vo from"axios";import bo from"path";var un,Us=D(()=>{"use strict";L();Pe();le();un=class{toolNames=["read_special_file","read_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm","png","jpg","jpeg","gif","bmp","webp","ico"];imageExtensions=["png","jpg","jpeg","gif","bmp","webp","ico"];imageMimeTypes={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",webp:"image/webp",ico:"image/x-icon"};async execute(e,t,n,s){let o=n.path;if(!o)throw new Error("Missing path argument");i.debug(`[ReadSpecialFileTool] Converting file: ${o}`);let r=Date.now();F.start("ReadSpecialFile",n.description,o);try{try{await ln.access(o)}catch{return[{type:"text",text:`Error: File does not exist at path: ${o}`}]}let a=bo.extname(o).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let E=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: ${k}`}]}let l=await sn.stat(s),u=lo.basename(s);if(i.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){i.debug(`[ReadSpecialFileTool] Image file detected: ${s}`);let v=(await sn.readFile(s)).toString("base64"),x=this.imageMimeTypes[a]||"application/octet-stream";i.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${v.length} chars)`);let P=Date.now()-r;return F.result({toolName:"ReadSpecialFile",filePath:s,output:`Image loaded: ${u}`,success:!0,executionTime:P}),[{type:"image_url",image_url:{url:`data:${x};base64,${v}`}}]}let d=await this.uploadToBatchAPI(s,u);i.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let p=await this.pollBatchStatus(d);i.debug("[ReadSpecialFileTool] Conversion completed");let m=p.files[0];if(!m||m.status==="failed"){let k=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${k}`}]}let h=await this.fetchFileContent(m.file_id);if(!h.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let f=l.size/1024,y=f/1024,S=y>=1?`${y.toFixed(2)} MB`:`${f.toFixed(2)} KB`,b=`# File: ${u}
74
+ Supported file types: ${E}`}]}let l=await ln.stat(o),u=bo.basename(o);if(i.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`),this.imageExtensions.includes(a)){i.debug(`[ReadSpecialFileTool] Image file detected: ${o}`);let b=(await ln.readFile(o)).toString("base64"),C=this.imageMimeTypes[a]||"application/octet-stream";i.debug(`[ReadSpecialFileTool] Image converted to base64: ${u} (${b.length} chars)`);let P=Date.now()-r;return F.result({toolName:"ReadSpecialFile",filePath:o,output:`Image loaded: ${u}`,success:!0,executionTime:P}),[{type:"image_url",image_url:{url:`data:${C};base64,${b}`}}]}let d=await this.uploadToBatchAPI(o,u);i.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${d}`);let p=await this.pollBatchStatus(d);i.debug("[ReadSpecialFileTool] Conversion completed");let m=p.files[0];if(!m||m.status==="failed"){let E=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${E}`}]}let g=await this.fetchFileContent(m.file_id);if(!g.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let h=l.size/1024,y=h/1024,T=y>=1?`${y.toFixed(2)} MB`:`${h.toFixed(2)} KB`,S=`# File: ${u}
75
75
  **Type:** ${a.toUpperCase()}
76
- **Size:** ${S}
76
+ **Size:** ${T}
77
77
  **Conversion:** ✅ Successful
78
78
 
79
79
  ---
80
80
 
81
- ${h.markdown_content}`,w=Date.now()-r;return F.result({toolName:"ReadSpecialFile",filePath:s,output:`Successfully converted ${u} (${S})`,success:!0,executionTime:w}),[{type:"text",text:b}]}catch(a){i.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
81
+ ${g.markdown_content}`,w=Date.now()-r;return F.result({toolName:"ReadSpecialFile",filePath:o,output:`Successfully converted ${u} (${T})`,success:!0,executionTime:w}),[{type:"text",text:S}]}catch(a){i.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
82
82
 
83
83
  This could be due to:
84
84
  • File corruption or invalid format
@@ -86,37 +86,37 @@ 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 F.result({toolName:"ReadSpecialFile",filePath:s,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let n=await sn.readFile(e),o=lo.extname(t).substring(1).toLowerCase(),r=await H.getInstance().getFirebaseIdToken(),a=new ta;a.append("files",n,{filename:t,contentType:this.getMimeType(o)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await co.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let n=await H.getInstance().getFirebaseIdToken(),o={};n&&(o.Authorization=`Bearer ${n}`);for(let s=1;s<=this.maxPollAttempts;s++)try{let a=(await co.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:o})).data;if(i.debug(`[ReadSpecialFileTool] Poll ${s} - 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 n=await H.getInstance().getFirebaseIdToken(),o={};n&&(o.Authorization=`Bearer ${n}`);try{let s=await co.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:o});if(s.data.status==="failed")throw new Error(s.data.error||"Unknown conversion error");return s.data}catch(s){throw s.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${s.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 an,Ps=D(()=>{"use strict";$();Ie();nn();an=class{toolNames=["write","Write","write_file"];async execute(e,t,n,o){let s=n.file_path,r=n.content,a=n.edits;if(!s)throw new Error("Missing file_path argument");let l=tt(s),u=gt(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let d=Date.now();return F.start("Write",n.description,l),r!=null?await this.executeSimpleWrite(l,r,d):await this.executeEditsMode(l,a,d)}async executeSimpleWrite(e,t,n){i.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let o=await import("fs/promises"),r=(await import("path")).dirname(e);await o.mkdir(r,{recursive:!0}),await o.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 F.result({toolName:"ReadSpecialFile",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let n=await ln.readFile(e),s=bo.extname(t).substring(1).toLowerCase(),r=await z.getInstance().getFirebaseIdToken(),a=new pa;a.append("files",n,{filename:t,contentType:this.getMimeType(s)});try{let l={...a.getHeaders()};r&&(l.Authorization=`Bearer ${r}`);let u=await vo.post(`${this.baseEndpoint}/convert-batch`,a,{headers:l,timeout:3e4});if(u.status!==202)throw new Error(`Upload failed with HTTP ${u.status}`);return u.data.request_id}catch(l){throw l.response?new Error(`Upload failed (HTTP ${l.response.status}): ${JSON.stringify(l.response.data)}`):new Error(`Upload failed: ${l.message}`)}}async pollBatchStatus(e){let n=await z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);for(let o=1;o<=this.maxPollAttempts;o++)try{let a=(await vo.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4,headers:s})).data;if(i.debug(`[ReadSpecialFileTool] Poll ${o} - Status: ${a.files[0]?.status}, Progress: ${a.completed}/${a.total_files}`),a.completed+a.failed>=a.total_files)return a;await this.sleep(this.pollInterval)}catch(r){throw r.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${r.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){let n=await z.getInstance().getFirebaseIdToken(),s={};n&&(s.Authorization=`Bearer ${n}`);try{let o=await vo.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4,headers:s});if(o.data.status==="failed")throw new Error(o.data.error||"Unknown conversion error");return o.data}catch(o){throw o.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${o.message}`)}}getMimeType(e){switch(e.toLowerCase()){case"pdf":return"application/pdf";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"doc":return"application/msword";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xls":return"application/vnd.ms-excel";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"ppt":return"application/vnd.ms-powerpoint";case"mp3":return"audio/mpeg";case"mp4":return"video/mp4";case"wav":return"audio/wav";case"html":case"htm":return"text/html";default:return"application/octet-stream"}}sleep(e){return new Promise(t=>setTimeout(t,e))}}});var dn,Ls=D(()=>{"use strict";L();Pe();an();dn=class{toolNames=["write","Write","write_file"];async execute(e,t,n,s){let o=n.file_path,r=n.content,a=n.edits;if(!o)throw new Error("Missing file_path argument");let l=rt(o),u=ft(l);if(!u.valid)return[{type:"text",text:`Error: ${u.error}`}];let d=Date.now();return F.start("Write",n.description,l),r!=null?await this.executeSimpleWrite(l,r,d):await this.executeEditsMode(l,a,d)}async executeSimpleWrite(e,t,n){i.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let s=await import("fs/promises"),r=(await import("path")).dirname(e);await s.mkdir(r,{recursive:!0}),await s.writeFile(e,t,"utf-8");let a=t.split(`
90
90
  `),l="";for(let p=0;p<Math.min(a.length,8);p++)l+=`+ ${a[p]}
91
91
  `;a.length>8&&(l+=`+ ...
92
92
 
93
- (${a.length-8} more lines)`);let u=l.trim();i.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let d=Date.now()-n;return F.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:d}),[{type:"text",text:u}]}catch(o){i.debug(`[WriteFileTool] Failed to write file: ${o.message}`);let s=`Error writing file: ${o.message}`,r=Date.now()-n;return F.result({toolName:"Write",filePath:e,output:s,success:!1,executionTime:r}),[{type:"text",text:s}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");i.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let o=await import("fs/promises"),s=await import("path");for(let h=0;h<t.length;h++){let f=t[h];if(!f||typeof f!="object")throw new Error(`Edit operation ${h+1} must be an object with 'search' and 'replace' fields`);if(!f.hasOwnProperty("search")||typeof f.search!="string")throw new Error(`Edit operation ${h+1} missing required 'search' field (must be string)`);if(!f.hasOwnProperty("replace")||typeof f.replace!="string")throw new Error(`Edit operation ${h+1} missing required 'replace' field (must be string)`)}let r=t[0].search==="",a;if(r)if(i.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let h=s.dirname(e);await o.mkdir(h,{recursive:!0}),await o.writeFile(e,a,"utf-8");let f=a.split(`
94
- `),y="";for(let S=0;S<Math.min(f.length,8);S++)y+=`+ ${f[S]}
95
- `;return f.length>8&&(y+=`+ ...
93
+ (${a.length-8} more lines)`);let u=l.trim();i.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let d=Date.now()-n;return F.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:d}),[{type:"text",text:u}]}catch(s){i.debug(`[WriteFileTool] Failed to write file: ${s.message}`);let o=`Error writing file: ${s.message}`,r=Date.now()-n;return F.result({toolName:"Write",filePath:e,output:o,success:!1,executionTime:r}),[{type:"text",text:o}]}}async executeEditsMode(e,t,n){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");i.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let s=await import("fs/promises"),o=await import("path");for(let g=0;g<t.length;g++){let h=t[g];if(!h||typeof h!="object")throw new Error(`Edit operation ${g+1} must be an object with 'search' and 'replace' fields`);if(!h.hasOwnProperty("search")||typeof h.search!="string")throw new Error(`Edit operation ${g+1} missing required 'search' field (must be string)`);if(!h.hasOwnProperty("replace")||typeof h.replace!="string")throw new Error(`Edit operation ${g+1} missing required 'replace' field (must be string)`)}let r=t[0].search==="",a;if(r)if(i.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let g=o.dirname(e);await s.mkdir(g,{recursive:!0}),await s.writeFile(e,a,"utf-8");let h=a.split(`
94
+ `),y="";for(let T=0;T<Math.min(h.length,8);T++)y+=`+ ${h[T]}
95
+ `;return h.length>8&&(y+=`+ ...
96
96
 
97
- (${f.length-8} more lines)`),i.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:y.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{i.debug("[WriteFileTool] Reading existing file");try{a=await o.readFile(e,"utf-8"),i.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(h){throw h.code==="ENOENT"?new Error(`File does not exist at path: ${e}. Use empty search string to create new file.`):new Error(`Failed to read existing file: ${h.message}`)}}let l=0,u=a,d=[];for(let h=0;h<t.length;h++){let f=t[h];if(i.debug(`[WriteFileTool] Applying edit ${h+1}/${t.length}`),f.search==="")if(r){d.push({index:h+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{i.debug("[WriteFileTool] Rewriting entire existing file"),u=f.replace,d.push({index:h+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let y=u.indexOf(f.search);if(y!==-1)u=u.substring(0,y)+f.replace+u.substring(y+f.search.length),i.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:h+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let S=`Search string not found: '${f.search}'`;return d.push({index:h+1,success:!1,message:S,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${h+1}: '${f.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(w=>w.success).length}\\n- Failed: ${d.filter(w=>!w.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(w=>`${w.success?"✅":"❌"} Edit ${w.index}: ${w.message}`).join("\\n")}]}}await o.writeFile(e,u,"utf-8"),i.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let p=u.split(`
98
- `),m="";for(let h=0;h<Math.min(p.length,8);h++)m+=`+ ${p[h]}
97
+ (${h.length-8} more lines)`),i.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:y.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{i.debug("[WriteFileTool] Reading existing file");try{a=await s.readFile(e,"utf-8"),i.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(g){throw g.code==="ENOENT"?new Error(`File does not exist at path: ${e}. Use empty search string to create new file.`):new Error(`Failed to read existing file: ${g.message}`)}}let l=0,u=a,d=[];for(let g=0;g<t.length;g++){let h=t[g];if(i.debug(`[WriteFileTool] Applying edit ${g+1}/${t.length}`),h.search==="")if(r){d.push({index:g+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{i.debug("[WriteFileTool] Rewriting entire existing file"),u=h.replace,d.push({index:g+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let y=u.indexOf(h.search);if(y!==-1)u=u.substring(0,y)+h.replace+u.substring(y+h.search.length),i.debug("[WriteFileTool] Replaced first occurrence"),d.push({index:g+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let T=`Search string not found: '${h.search}'`;return d.push({index:g+1,success:!1,message:T,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${g+1}: '${h.search}'\\n\\nEdit Summary:\\n- Total edits: ${d.length}\\n- Successful: ${d.filter(w=>w.success).length}\\n- Failed: ${d.filter(w=>!w.success).length}\\n\\nIndividual Edit Results:\\n`+d.map(w=>`${w.success?"✅":"❌"} Edit ${w.index}: ${w.message}`).join("\\n")}]}}await s.writeFile(e,u,"utf-8"),i.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let p=u.split(`
98
+ `),m="";for(let g=0;g<Math.min(p.length,8);g++)m+=`+ ${p[g]}
99
99
  `;return p.length>8&&(m+=`+ ...
100
100
 
101
- (${p.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(o){return i.debug(`[WriteFileTool] Failed to write file: ${o.message}`),[{type:"text",text:`Error writing file: ${o.message}`}]}}}});var cn,As=D(()=>{"use strict";$();Ie();nn();cn=class{toolNames=["edit","Edit"];async execute(e,t,n,o){let s=n.file_path,r=n.old_string,a=n.new_string,l=n.replace_all===!0;if(!s)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=tt(s),d=gt(u);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];i.debug(`[EditFileTool] Editing file: ${u}`);let p=Date.now();F.start("Edit",n.description,u);try{let m=await import("fs/promises"),h=await m.readFile(u,"utf-8"),f,y=0;if(l)for(f=h;f.includes(r);)f=f.replace(r,a),y++;else h.includes(r)?(f=h.replace(r,a),y=1):f=h;if(y===0){let v=`No matches found for the specified old_string in file: ${u}`,x=Date.now()-p;return F.result({toolName:"Edit",filePath:u,output:v,success:!1,executionTime:x}),[{type:"text",text:v}]}await m.writeFile(u,f,"utf-8");let S=`Successfully edited file: Replaced ${y} occurrence(s)`;i.debug(`[EditFileTool] ${S}`);let b=Date.now()-p,w=(await import("chalk")).default,k=`${w.red("- "+r.split(`
101
+ (${p.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(s){return i.debug(`[WriteFileTool] Failed to write file: ${s.message}`),[{type:"text",text:`Error writing file: ${s.message}`}]}}}});var pn,Ws=D(()=>{"use strict";L();Pe();an();pn=class{toolNames=["edit","Edit"];async execute(e,t,n,s){let o=n.file_path,r=n.old_string,a=n.new_string,l=n.replace_all===!0;if(!o)throw new Error("Missing file_path argument");if(r==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");let u=rt(o),d=ft(u);if(!d.valid)return[{type:"text",text:`Error: ${d.error}`}];i.debug(`[EditFileTool] Editing file: ${u}`);let p=Date.now();F.start("Edit",n.description,u);try{let m=await import("fs/promises"),g=await m.readFile(u,"utf-8"),h,y=0;if(l)for(h=g;h.includes(r);)h=h.replace(r,a),y++;else g.includes(r)?(h=g.replace(r,a),y=1):h=g;if(y===0){let b=`No matches found for the specified old_string in file: ${u}`,C=Date.now()-p;return F.result({toolName:"Edit",filePath:u,output:b,success:!1,executionTime:C}),[{type:"text",text:b}]}await m.writeFile(u,h,"utf-8");let T=`Successfully edited file: Replaced ${y} occurrence(s)`;i.debug(`[EditFileTool] ${T}`);let S=Date.now()-p,w=(await import("chalk")).default,E=`${w.red("- "+r.split(`
102
102
  `).slice(0,5).join(`
103
103
  - `))}
104
104
  ${w.green("+ "+a.split(`
105
105
  `).slice(0,5).join(`
106
106
  + `))}
107
107
 
108
- Replaced ${y} occurrence(s)`;return F.result({toolName:"Edit",filePath:u,output:k,success:!0,executionTime:b}),[{type:"text",text:S}]}catch(m){i.debug(`[EditFileTool] Failed to edit file: ${m.message}`);let h=`Error editing file: ${m.message}`,f=Date.now()-p;return F.result({toolName:"Edit",filePath:u,output:h,success:!1,executionTime:f}),[{type:"text",text:h}]}}}});var ln,Ds=D(()=>{"use strict";$();ln=class{toolNames=["upload_file"];async execute(e,t,n,o){let s=n.file_path;if(!s)throw new Error("Missing file_path argument");return i.debug(`[UploadFileTool] Upload file not implemented for CLI: ${s}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${s}`}]}}});import uo from"fs/promises";import na from"path";import oa from"form-data";import sa from"axios";var un,Ns=D(()=>{"use strict";$();Ie();ce();un=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,o){let s=n.zip_file_path;if(!s)throw new Error("Missing zip_file_path argument");let r=Date.now();F.start("DeployZipHTML",n.description,s);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let A=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 ${A} seconds.`)}i.debug(`[DeployZipHTML] Deploying HTML project: ${s}`);try{await uo.access(s)}catch{throw new Error(`ZIP file not found at path: ${s}`)}if(!s.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${s}`);let l=await uo.stat(s),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 uo.readFile(s),p=na.basename(s).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipHTML] File: ${p}, Size: ${l.size} bytes`);let h=await H.getInstance().getFirebaseIdToken();if(!h)throw new Error("User must be authenticated to deploy projects");let f=new oa;f.append("zipFile",d,{filename:p,contentType:"application/zip"});let y="https://snowx.ai/api/v2/deploy-zip";i.debug(`[DeployZipHTML] Uploading to ${y}`);let S=await sa.post(y,f,{headers:{...f.getHeaders(),Authorization:`Bearer ${h}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(S.status!==200&&S.status!==201)throw new Error(`Deployment failed with status ${S.status}: ${JSON.stringify(S.data)}`);let b=S.data;i.debug("[DeployZipHTML] Deployed successfully"),i.debug(`[DeployZipHTML] Response: ${JSON.stringify(b,null,2)}`);let w=b.data?.deployUrl||b.deployUrl||b.url||b.deploymentUrl||b.site_url||b.siteUrl||b.website_url,k=b.data?.deployId||b.deployId||b.projectId||b.deploymentId,v=b.data?.siteId||b.siteId;this.deployCount++;let x=`# HTML Project Deployed Successfully!
108
+ Replaced ${y} occurrence(s)`;return F.result({toolName:"Edit",filePath:u,output:E,success:!0,executionTime:S}),[{type:"text",text:T}]}catch(m){i.debug(`[EditFileTool] Failed to edit file: ${m.message}`);let g=`Error editing file: ${m.message}`,h=Date.now()-p;return F.result({toolName:"Edit",filePath:u,output:g,success:!1,executionTime:h}),[{type:"text",text:g}]}}}});var mn,Bs=D(()=>{"use strict";L();mn=class{toolNames=["upload_file"];async execute(e,t,n,s){let o=n.file_path;if(!o)throw new Error("Missing file_path argument");return i.debug(`[UploadFileTool] Upload file not implemented for CLI: ${o}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${o}`}]}}});import To from"fs/promises";import ma from"path";import ga from"form-data";import ha from"axios";var gn,Hs=D(()=>{"use strict";L();Pe();le();gn=class{toolNames=["deploy_zip_html","DeployZipHTML"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();F.start("DeployZipHTML",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let R=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${R} seconds.`)}i.debug(`[DeployZipHTML] Deploying HTML project: ${o}`);try{await To.access(o)}catch{throw new Error(`ZIP file not found at path: ${o}`)}if(!o.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${o}`);let l=await To.stat(o),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await To.readFile(o),p=ma.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipHTML] File: ${p}, Size: ${l.size} bytes`);let g=await z.getInstance().getFirebaseIdToken();if(!g)throw new Error("User must be authenticated to deploy projects");let h=new ga;h.append("zipFile",d,{filename:p,contentType:"application/zip"});let y="https://snowx.ai/api/v2/deploy-zip";i.debug(`[DeployZipHTML] Uploading to ${y}`);let T=await ha.post(y,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${g}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(T.status!==200&&T.status!==201)throw new Error(`Deployment failed with status ${T.status}: ${JSON.stringify(T.data)}`);let S=T.data;i.debug("[DeployZipHTML] Deployed successfully"),i.debug(`[DeployZipHTML] Response: ${JSON.stringify(S,null,2)}`);let w=S.data?.deployUrl||S.deployUrl||S.url||S.deploymentUrl||S.site_url||S.siteUrl||S.website_url,E=S.data?.deployId||S.deployId||S.projectId||S.deploymentId,b=S.data?.siteId||S.siteId;this.deployCount++;let C=`# HTML Project Deployed Successfully!
109
109
 
110
110
  **Deployment URL**: ${w}
111
111
 
112
112
  **Project**: ${p}
113
113
  **Type**: Static HTML
114
- ${k?`**Deploy ID**: ${k}
115
- `:""}${v?`**Site ID**: ${v}
114
+ ${E?`**Deploy ID**: ${E}
115
+ `:""}${b?`**Site ID**: ${b}
116
116
  `:""}
117
117
  Your site is now live and accessible!
118
118
 
119
- ${b.message||""}`,P=Date.now()-r;return F.result({toolName:"DeployZipHTML",filePath:s,output:`Deployed to ${w}`,success:!0,executionTime:P}),[{type:"text",text:x}]}catch(a){i.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let l=`HTML deployment failed
119
+ ${S.message||""}`,P=Date.now()-r;return F.result({toolName:"DeployZipHTML",filePath:o,output:`Deployed to ${w}`,success:!0,executionTime:P}),[{type:"text",text:C}]}catch(a){i.error(`[DeployZipHTML] Deployment failed: ${a.message}`);let l=`HTML deployment failed
120
120
 
121
121
  ${a.message}
122
122
 
@@ -127,18 +127,18 @@ 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 F.result({toolName:"DeployZipHTML",filePath:s,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import po from"fs/promises";import ra from"path";import ia from"form-data";import aa from"axios";var dn,Rs=D(()=>{"use strict";$();Ie();ce();dn=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,o){let s=n.zip_file_path;if(!s)throw new Error("Missing zip_file_path argument");let r=Date.now();F.start("DeployZipReact",n.description,s);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let A=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 ${A} seconds.`)}i.debug(`[DeployZipReact] Deploying React project: ${s}`);try{await po.access(s)}catch{throw new Error(`ZIP file not found at path: ${s}`)}if(!s.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${s}`);let l=await po.stat(s),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 po.readFile(s),p=ra.basename(s).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipReact] File: ${p}, Size: ${l.size} bytes`);let h=await H.getInstance().getFirebaseIdToken();if(!h)throw new Error("User must be authenticated to deploy projects");let f=new ia;f.append("zipFile",d,{filename:p,contentType:"application/zip"});let y="https://snowx.ai/api/v2/deploy-zip-react";i.debug(`[DeployZipReact] Uploading to ${y}`);let S=await aa.post(y,f,{headers:{...f.getHeaders(),Authorization:`Bearer ${h}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(S.status!==200&&S.status!==201)throw new Error(`Deployment failed with status ${S.status}: ${JSON.stringify(S.data)}`);let b=S.data;i.debug("[DeployZipReact] Deployed successfully"),i.debug(`[DeployZipReact] Response: ${JSON.stringify(b,null,2)}`);let w=b.data?.deployUrl||b.deployUrl||b.url||b.deploymentUrl||b.site_url||b.siteUrl||b.website_url,k=b.data?.deployId||b.deployId||b.projectId||b.deploymentId,v=b.data?.siteId||b.siteId;this.deployCount++;let x=`# React Project Deployed Successfully!
130
+ If the issue persists, contact support.`,u=Date.now()-r;return F.result({toolName:"DeployZipHTML",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});import yo from"fs/promises";import fa from"path";import va from"form-data";import ba from"axios";var hn,Gs=D(()=>{"use strict";L();Pe();le();hn=class{toolNames=["deploy_zip_react","DeployZipReact"];lastDeployTime=0;deployCount=0;maxDeploysPerWindow=5;windowMs=600*1e3;async execute(e,t,n,s){let o=n.zip_file_path;if(!o)throw new Error("Missing zip_file_path argument");let r=Date.now();F.start("DeployZipReact",n.description,o);try{let a=Date.now();if(a-this.lastDeployTime>this.windowMs&&(this.deployCount=0,this.lastDeployTime=a),this.deployCount>=this.maxDeploysPerWindow){let R=Math.ceil((this.windowMs-(a-this.lastDeployTime))/1e3);throw new Error(`Rate limit exceeded. You can only deploy ${this.maxDeploysPerWindow} projects every ${this.windowMs/6e4} minutes. Please try again in ${R} seconds.`)}i.debug(`[DeployZipReact] Deploying React project: ${o}`);try{await yo.access(o)}catch{throw new Error(`ZIP file not found at path: ${o}`)}if(!o.toLowerCase().endsWith(".zip"))throw new Error(`File must be a ZIP archive. Provided file: ${o}`);let l=await yo.stat(o),u=100*1024*1024;if(l.size>u)throw new Error(`ZIP file too large. Maximum size is 100MB, file is ${(l.size/1024/1024).toFixed(2)}MB`);let d=await yo.readFile(o),p=fa.basename(o).replace(/[\r\n\t"']/g,"_");i.debug(`[DeployZipReact] File: ${p}, Size: ${l.size} bytes`);let g=await z.getInstance().getFirebaseIdToken();if(!g)throw new Error("User must be authenticated to deploy projects");let h=new va;h.append("zipFile",d,{filename:p,contentType:"application/zip"});let y="https://snowx.ai/api/v2/deploy-zip-react";i.debug(`[DeployZipReact] Uploading to ${y}`);let T=await ba.post(y,h,{headers:{...h.getHeaders(),Authorization:`Bearer ${g}`},timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0});if(T.status!==200&&T.status!==201)throw new Error(`Deployment failed with status ${T.status}: ${JSON.stringify(T.data)}`);let S=T.data;i.debug("[DeployZipReact] Deployed successfully"),i.debug(`[DeployZipReact] Response: ${JSON.stringify(S,null,2)}`);let w=S.data?.deployUrl||S.deployUrl||S.url||S.deploymentUrl||S.site_url||S.siteUrl||S.website_url,E=S.data?.deployId||S.deployId||S.projectId||S.deploymentId,b=S.data?.siteId||S.siteId;this.deployCount++;let C=`# React Project Deployed Successfully!
131
131
 
132
132
  **Deployment URL**: ${w}
133
133
 
134
134
  **Project**: ${p}
135
135
  **Type**: React / SPA
136
- ${k?`**Deploy ID**: ${k}
137
- `:""}${v?`**Site ID**: ${v}
136
+ ${E?`**Deploy ID**: ${E}
137
+ `:""}${b?`**Site ID**: ${b}
138
138
  `:""}
139
139
  Your React app is now live and accessible!
140
140
 
141
- ${b.message||""}`,P=Date.now()-r;return F.result({toolName:"DeployZipReact",filePath:s,output:`Deployed to ${w}`,success:!0,executionTime:P}),[{type:"text",text:x}]}catch(a){i.error(`[DeployZipReact] Deployment failed: ${a.message}`);let l=`React deployment failed
141
+ ${S.message||""}`,P=Date.now()-r;return F.result({toolName:"DeployZipReact",filePath:o,output:`Deployed to ${w}`,success:!0,executionTime:P}),[{type:"text",text:C}]}catch(a){i.error(`[DeployZipReact] Deployment failed: ${a.message}`);let l=`React deployment failed
142
142
 
143
143
  ${a.message}
144
144
 
@@ -149,8 +149,9 @@ 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 F.result({toolName:"DeployZipReact",filePath:s,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var Ms=D(()=>{"use strict"});function ca(c){let e=c.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),o=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(o)}function Ft(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(ca(c))return Se.pipedWithTerminator;if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("DOC")))return Se.extended;let n=["python","python3","python2","node ",`node
153
- `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let u of n)if(e.includes(u))return Se.extended;let o=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let u of o)if(e.includes(u))return Se.extended;return(c.match(/\n/g)||[]).length>5?Se.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)?Se.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?Se.fast:Se.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)?Se.extended:c.includes("|")?Se.default:c.length<30?Se.fast:Se.default}var Se,mo=D(()=>{"use strict";Ms();Se={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 la,exec as ua,execSync as da}from"child_process";import{promisify as pa}from"util";function ho(){return process.platform}function _e(){return process.platform==="win32"}function ha(){return process.platform==="darwin"}function ht(c,e="SIGTERM"){if(c)try{if(_e())try{da(`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){i.debug(`[killProcessTree] Failed for PID ${c}: ${t}`)}}function fa(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(_e()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let o=["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(o)return{isPrivileged:!0,reason:`Privileged command: ${o.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 Os(){return _e()?"PowerShell or Command Prompt":(ha(),"Terminal")}function va(c,e){let t=Os();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
152
+ If the issue persists, contact support.`,u=Date.now()-r;return F.result({toolName:"DeployZipReact",filePath:o,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var qs=D(()=>{"use strict"});function Ta(c){let e=c.toLowerCase();if(!e.includes("|"))return!1;let t=e.split("|"),s=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(s)}function $t(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"";if(Ta(c))return we.pipedWithTerminator;if(c.includes("<<")&&(c.includes("EOF")||c.includes("'EOF'")||c.includes('"EOF"')||c.includes("END")||c.includes("SCRIPT")||c.includes("DOC")))return we.extended;let n=["python","python3","python2","node ",`node
153
+ `,"ruby","perl","php","julia","r ","rscript","scala","groovy","kotlin"];for(let u of n)if(e.includes(u))return we.extended;let s=["pandas","numpy","scipy","matplotlib","import pd","import np","read_csv","read_excel","to_csv","dataframe","groupby","merge"];for(let u of s)if(e.includes(u))return we.extended;return(c.match(/\n/g)||[]).length>5?we.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)?we.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?we.fast:we.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)?we.extended:c.includes("|")?we.default:c.length<30?we.fast:we.default}var we,So=D(()=>{"use strict";qs();we={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 ya,exec as Sa,execSync as wa}from"child_process";import{promisify as Ca}from"util";function xo(){return process.platform}function $e(){return process.platform==="win32"}function ka(){return process.platform==="darwin"}function vt(c,e="SIGTERM"){if(c)try{if($e())try{wa(`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){i.debug(`[killProcessTree] Failed for PID ${c}: ${t}`)}}function Ia(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($e()&&(e.includes("runas")||e.includes("-verb")&&e.includes("runas")||e.includes("start-process")&&e.includes("runas")))return{isPrivileged:!0,reason:"Windows administrator elevation"};let s=["apt-get","apt ","yum ","dnf ","pacman ","zypper ","systemctl ","service ","mount ","umount ","iptables ","firewall-cmd ","useradd ","userdel ","usermod ","groupadd ","groupdel ","chmod 777","chown "].find(a=>e.startsWith(a)||e.includes(`&& ${a}`)||e.includes(`; ${a}`)||e.includes(`| ${a}`));if(s)return{isPrivileged:!0,reason:`Privileged command: ${s.trim()}`};let 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 zs(){return $e()?"PowerShell or Command Prompt":(ka(),"Terminal")}function wo(c,e,t="max",n){let s=y=>{if(y>=6e4){let S=Math.round(y/6e4);return`${S} minute${S>1?"s":""}`}let T=Math.round(y/1e3);return`${T} second${T>1?"s":""}`},o=()=>{switch(process.platform){case"darwin":return"Terminal.app (or iTerm2)";case"win32":return"PowerShell or Windows Terminal";case"linux":return"your terminal emulator (e.g., GNOME Terminal, Konsole)";default:return"your system terminal"}},r=()=>{switch(process.platform){case"darwin":return'Press Cmd+Space, type "Terminal", and press Enter';case"win32":return'Press Win+X and select "Windows Terminal" or "PowerShell"';case"linux":return"Press Ctrl+Alt+T or open your terminal from the applications menu";default:return"Open your system terminal application"}},a=()=>process.platform==="darwin"?["","🔍 Tip: You can also start the command in Terminal and ask me to monitor it."," I can track running Terminal processes and capture their output using the"," MonitorRunningCli tool - just tell me the Terminal window/tab to monitor."]:null,l=()=>{switch(t){case"max":return`The command exceeded the maximum allowed execution time of ${s(e)}.`;case"initial":return`The command produced no output within the initial ${s(e)} window.`;case"activity":return`The command stopped producing output for ${s(e)} (activity timeout).`;default:return`The command timed out after ${s(e)}.`}},u=o(),d=r(),p=l(),m=a(),g=["","❌ Command Timed Out","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","",p,""];n&&g.push(`Details: ${n}`,"");let h=c.length>100?c.substring(0,97)+"...":c;return g.push(`Command: ${h}`,""),g.push(`💡 For long-running commands, consider using ${u}:`,"",` 1. ${d}`," 2. Run your command there:",` ${h}`," 3. The command will continue running regardless of duration",""),m&&g.push(...m),g.push("","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","This is expected behavior for commands that take a long time to execute.","The Bash tool is designed for quick operations and has built-in timeouts","to prevent hanging indefinitely."),g.join(`
154
+ `)}function Pa(c,e){let t=zs();return`This command requires elevated privileges (sudo/administrator) and interactive password input.
154
155
 
155
156
  Reason: ${e}
156
157
 
@@ -164,7 +165,7 @@ To run this command:
164
165
  2. Run the command manually: ${c}
165
166
  3. Enter your password when prompted
166
167
 
167
- Alternative: Break down the task into non-privileged commands if possible.`}function ba(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:u,reason:d}of n)if(e.startsWith(u)||e.includes(`&& ${u}`)||e.includes(`; ${u}`))return{isInteractive:!0,reason:d};let o=[{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:p}of o)if(e.startsWith(u)&&!d?.some(h=>e.startsWith(h)))return{isInteractive:!0,reason:p};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 Ta(c,e){let t=Os();return`This command requires interactive input and cannot run in the Bash tool.
168
+ Alternative: Break down the task into non-privileged commands if possible.`}function Aa(c){let e=c.trim().toLowerCase(),t=e.split(/\s+/)[0]||"",n=[{cmd:"npm login",reason:"npm login requires interactive authentication"},{cmd:"npm adduser",reason:"npm adduser requires interactive authentication"},{cmd:"yarn login",reason:"yarn login requires interactive authentication"},{cmd:"docker login",reason:"docker login requires interactive password input"},{cmd:"docker logout",reason:"docker logout may require confirmation"},{cmd:"gh auth login",reason:"GitHub CLI login requires interactive browser/token input"},{cmd:"firebase login",reason:"Firebase login requires interactive browser authentication"},{cmd:"heroku login",reason:"Heroku login requires interactive browser authentication"},{cmd:"aws configure",reason:"AWS configure requires interactive credential input"},{cmd:"gcloud auth login",reason:"Google Cloud login requires interactive browser authentication"},{cmd:"az login",reason:"Azure CLI login requires interactive browser authentication"},{cmd:"netlify login",reason:"Netlify login requires interactive authentication"},{cmd:"vercel login",reason:"Vercel login requires interactive authentication"},{cmd:"supabase login",reason:"Supabase login requires interactive authentication"},{cmd:"wrangler login",reason:"Cloudflare Wrangler login requires interactive authentication"},{cmd:"flyctl auth login",reason:"Fly.io login requires interactive authentication"},{cmd:"railway login",reason:"Railway login requires interactive authentication"}];for(let{cmd:u,reason:d}of n)if(e.startsWith(u)||e.includes(`&& ${u}`)||e.includes(`; ${u}`))return{isInteractive:!0,reason:d};let s=[{cmd:"npm init",except:["npm init -y","npm init --yes"],reason:"npm init requires interactive prompts (use npm init -y for non-interactive)"},{cmd:"yarn init",except:["yarn init -y","yarn init --yes"],reason:"yarn init requires interactive prompts (use yarn init -y for non-interactive)"},{cmd:"pnpm init",except:["pnpm init -y","pnpm init --yes"],reason:"pnpm init requires interactive prompts"}];for(let{cmd:u,except:d,reason:p}of s)if(e.startsWith(u)&&!d?.some(g=>e.startsWith(g)))return{isInteractive:!0,reason:p};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 Da(c,e){let t=zs();return`This command requires interactive input and cannot run in the Bash tool.
168
169
 
169
170
  Reason: ${e}
170
171
 
@@ -178,7 +179,7 @@ To run this command:
178
179
  2. Run the command manually: ${c}
179
180
  3. Follow the interactive prompts
180
181
 
181
- Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function Sa(c){for(let e of ya){let t=e.pattern.exec(c);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function wa(c,e){return!e.isCatastrophic||!e.pattern?"Unknown catastrophic command error":`🛑 BLOCKED: Catastrophic command detected!
182
+ Alternative: Look for non-interactive flags (e.g., --yes, -y, --non-interactive) or environment variables for authentication.`}function Ra(c){for(let e of Na){let t=e.pattern.exec(c);if(t)return{isCatastrophic:!0,pattern:e,matchedText:t[0]}}return{isCatastrophic:!1}}function Ma(c,e){return!e.isCatastrophic||!e.pattern?"Unknown catastrophic command error":`🛑 BLOCKED: Catastrophic command detected!
182
183
 
183
184
  Category: ${{filesystem_destruction:"Filesystem Destruction",disk_destruction:"Disk/Device Destruction",filesystem_formatting:"Filesystem Formatting",fork_bomb:"Fork Bomb / System Crash",permission_destruction:"Permission Destruction",root_modification:"Root Directory Modification",kernel_panic:"Kernel Panic Trigger",environment_destruction:"System Environment Destruction",partition_destruction:"Partition Table Destruction"}[e.pattern.category]||"Unknown Category"}
184
185
  Reason: ${e.pattern.description}
@@ -194,23 +195,17 @@ The Bash tool will NEVER execute commands that could destroy your system.
194
195
  If you believe this is a false positive, please:
195
196
  1. Review the command carefully
196
197
  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 Fs(c){let e=Sa(c);if(e.isCatastrophic)return wa(c,e);let t=fa(c);if(t.isPrivileged)return va(c,t.reason||"Privileged command detected");let n=ba(c);return n.isInteractive?Ta(c,n.reason||"Interactive command detected"):null}function _s(c){let e=c.trim();for(let t of Ca)if(t.test(e))return{isDelete:!0,paths:xa(e),category:Ea(e)};return{isDelete:!1,paths:[]}}function xa(c){let e=[],t=c.split(/\s+/),n=!1;for(let o=1;o<t.length;o++){let s=t[o];if(n){n=!1;continue}if(s.startsWith("-")){["-f","-o","-t","--target","--output"].includes(s)&&(n=!0);continue}s.length>0&&!s.startsWith("-")&&e.push(s)}return e}function Ea(c){let e=c.toLowerCase();return/^(rm|rmdir|unlink|del|rd|erase|remove-item)/i.test(e)?"File/Directory Deletion":/^git\s+(rm|clean)/.test(e)?"Git File Deletion":/^docker\s+volume/.test(e)?"Docker Volume Deletion":/^(aws\s+s3|gsutil|az\s+storage|rclone)/.test(e)?"Cloud Storage Deletion":/drop\s+(table|database|schema)/i.test(e)||/^(dropdb|dropuser)/.test(e)?"Database Deletion":/^(dd|mkfs|format|fdisk|parted|gdisk)/.test(e)?"Disk/Filesystem Operation":"Delete Operation"}var ma,ga,_t,go,le,$t,ya,Ca,ft=D(()=>{"use strict";mo();mt();$();ma=pa(ua),ga=8500,_t=new ye({maxResponseTokens:ga});go=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),i.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),i.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 n=this.processes.get(e);return n?(Object.assign(n,t),i.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${n.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],n=Array.from(this.processes.entries());for(let r=0;r<n.length;r++){let[a,l]=n[r];l.status!=="running"&&l.endTime&&t.push({id:a,endTime:l.endTime.getTime()})}let o=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),o++)}o>0&&i.debug(`[BackgroundProcessManager] Cleaned up ${o} old processes by TTL`);let s=t.filter(r=>e-r.endTime<=this.COMPLETED_PROCESS_TTL);if(s.length>this.MAX_COMPLETED_PROCESSES){s.sort((a,l)=>a.endTime-l.endTime);let r=s.slice(0,s.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<r.length;a++){let{id:l}=r[a];this.processes.delete(l)}i.debug(`[BackgroundProcessManager] Cleaned up ${r.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let n=0;n<t.length;n++){let[o,s]=t[n];s.status!=="running"&&(this.processes.delete(o),e++)}return i.debug(`[BackgroundProcessManager] Force cleaned ${e} completed processes`),e}getStats(){let e=this.getAllProcesses(),t=e.filter(n=>n.status==="running").length;return{total:e.length,running:t,completed:e.length-t}}clear(){this.processes.clear(),i.debug("[BackgroundProcessManager] Cleared all processes")}},le=new go;$t=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,n,o,s="new",r){let a=r||Ft(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if(_e())await ma(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let o=Date.now(),s=ho(),r,a;_e()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=la(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!_e()}),u="",d="",p=!1,m="",h=!1,f=!1,y=Date.now(),S=null,b=null,w=null,k=null,v=null,x=null,P=()=>{S&&(clearTimeout(S),S=null),b&&(clearTimeout(b),b=null),w&&(clearTimeout(w),w=null),k&&(clearTimeout(k),k=null),v&&(clearTimeout(v),v=null),x&&(clearTimeout(x),x=null)},A=N=>{h||(h=!0,P(),n(N))},B=async N=>{h||(p=!0,m=N,b&&(clearTimeout(b),b=null),w&&(clearTimeout(w),w=null),l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),this.cleanupStreams(l),k=setTimeout(async()=>{h||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),v=setTimeout(()=>{if(h)return;let C=Date.now()-o;A({output:u+d+`
198
+ 3. Consider breaking down the operation into safer steps`}function js(c){let e=Ra(c);if(e.isCatastrophic)return Ma(c,e);let t=Ia(c);if(t.isPrivileged)return Pa(c,t.reason||"Privileged command detected");let n=Aa(c);return n.isInteractive?Da(c,n.reason||"Interactive command detected"):null}function Xs(c){let e=c.trim();for(let t of _a)if(t.test(e))return{isDelete:!0,paths:Oa(e),category:Fa(e)};return{isDelete:!1,paths:[]}}function Oa(c){let e=[],t=c.split(/\s+/),n=!1;for(let s=1;s<t.length;s++){let o=t[s];if(n){n=!1;continue}if(o.startsWith("-")){["-f","-o","-t","--target","--output"].includes(o)&&(n=!0);continue}o.length>0&&!o.startsWith("-")&&e.push(o)}return e}function Fa(c){let e=c.toLowerCase();return/^(rm|rmdir|unlink|del|rd|erase|remove-item)/i.test(e)?"File/Directory Deletion":/^git\s+(rm|clean)/.test(e)?"Git File Deletion":/^docker\s+volume/.test(e)?"Docker Volume Deletion":/^(aws\s+s3|gsutil|az\s+storage|rclone)/.test(e)?"Cloud Storage Deletion":/drop\s+(table|database|schema)/i.test(e)||/^(dropdb|dropuser)/.test(e)?"Database Deletion":/^(dd|mkfs|format|fdisk|parted|gdisk)/.test(e)?"Disk/Filesystem Operation":"Delete Operation"}var xa,Ea,Ut,Co,ue,Lt,Na,_a,bt=D(()=>{"use strict";So();ht();L();xa=Ca(Sa),Ea=8500,Ut=new Se({maxResponseTokens:Ea});Co=class{processes=new Map;MAX_COMPLETED_PROCESSES=50;COMPLETED_PROCESS_TTL=1800*1e3;addProcess(e){this.processes.set(e.id,e),this.cleanupOldProcesses(),i.debug(`[BackgroundProcessManager] Added process: ${e.id}`)}getProcess(e){return this.processes.get(e)}removeProcess(e){this.processes.delete(e),i.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 n=this.processes.get(e);return n?(Object.assign(n,t),i.debug(`[BackgroundProcessManager] Updated process: ${e}, status: ${n.status}`),!0):!1}cleanupOldProcesses(){let e=Date.now(),t=[],n=Array.from(this.processes.entries());for(let r=0;r<n.length;r++){let[a,l]=n[r];l.status!=="running"&&l.endTime&&t.push({id:a,endTime:l.endTime.getTime()})}let s=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),s++)}s>0&&i.debug(`[BackgroundProcessManager] Cleaned up ${s} old processes by TTL`);let o=t.filter(r=>e-r.endTime<=this.COMPLETED_PROCESS_TTL);if(o.length>this.MAX_COMPLETED_PROCESSES){o.sort((a,l)=>a.endTime-l.endTime);let r=o.slice(0,o.length-this.MAX_COMPLETED_PROCESSES);for(let a=0;a<r.length;a++){let{id:l}=r[a];this.processes.delete(l)}i.debug(`[BackgroundProcessManager] Cleaned up ${r.length} excess processes`)}}forceCleanupCompleted(){let e=0,t=Array.from(this.processes.entries());for(let n=0;n<t.length;n++){let[s,o]=t[n];o.status!=="running"&&(this.processes.delete(s),e++)}return i.debug(`[BackgroundProcessManager] Force cleaned ${e} completed processes`),e}getStats(){let e=this.getAllProcesses(),t=e.filter(n=>n.status==="running").length;return{total:e.length,running:t,completed:e.length-t}}clear(){this.processes.clear(),i.debug("[BackgroundProcessManager] Cleared all processes")}},ue=new Co;Lt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,n,s,o="new",r){let a=r||$t(e);return this.executeInNewProcess(e,a)}async killProcessTree(e,t="SIGTERM"){try{if($e())await xa(`taskkill /PID ${e} /T /F`,{timeout:5e3}).catch(()=>{});else try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}catch{}}cleanupStreams(e){try{e.stdout?.destroy(),e.stderr?.destroy(),e.stdin?.destroy()}catch{}}async executeInNewProcess(e,t){return new Promise(n=>{let s=Date.now(),o=xo(),r,a;$e()?(r="powershell.exe",a=["-ExecutionPolicy","Bypass","-Command",e]):(r="/bin/bash",a=["-c",e]);let l=ya(r,a,{env:process.env,stdio:["ignore","pipe","pipe"],cwd:process.cwd(),detached:!$e()}),u="",d="",p=!1,m="",g="max",h=!1,y=!1,T=Date.now(),S=null,w=null,E=null,b=null,C=null,P=null,R=()=>{S&&(clearTimeout(S),S=null),w&&(clearTimeout(w),w=null),E&&(clearTimeout(E),E=null),b&&(clearTimeout(b),b=null),C&&(clearTimeout(C),C=null),P&&(clearTimeout(P),P=null)},O=N=>{h||(h=!0,R(),n(N))},j=async(N,k="max")=>{h||(p=!0,m=N,g=k,w&&(clearTimeout(w),w=null),E&&(clearTimeout(E),E=null),l.pid&&await this.killProcessTree(l.pid,"SIGTERM"),this.cleanupStreams(l),b=setTimeout(async()=>{h||(l.pid&&await this.killProcessTree(l.pid,"SIGKILL"),C=setTimeout(()=>{if(h)return;let f=Date.now()-s,v=g==="activity"?t.activityTimeout:g==="initial"?t.initialTimeout:t.maxTimeout,x=wo(e,v,g,m);O({output:u+d+x,exitCode:-9,isSuccess:!1,duration:f,platform:o})},500))},1e3))};S=setTimeout(()=>{j(`Max timeout reached (${t.maxTimeout}ms)`,"max")},t.maxTimeout),t.initialTimeout>0&&(E=setTimeout(()=>{!y&&!h&&j(`No output received within initial timeout (${t.initialTimeout}ms)`,"initial")},t.initialTimeout));let q=()=>{T=Date.now(),t.useActivityTimeout&&(w&&clearTimeout(w),w=setTimeout(()=>{if(!h){let N=Date.now()-T;j(`No output for ${N}ms (activity timeout: ${t.activityTimeout}ms)`,"activity")}},t.activityTimeout))};t.useActivityTimeout&&q(),l.stdout?.on("data",N=>{y=!0,q(),E&&(clearTimeout(E),E=null),u+=N.toString()}),l.stderr?.on("data",N=>{y=!0,q(),E&&(clearTimeout(E),E=null),d+=N.toString()}),l.on("exit",(N,k)=>{k&&!p&&(d+=`
199
+ [Process terminated by signal: ${k}]`),P=setTimeout(()=>{if(h)return;R(),this.cleanupStreams(l);let f=Date.now()-s,v=(u+d).trim();if(Ut.exceedsResponseLimit(v)){let x=Ut.truncate(v),U=x.text.split(`
200
+ `);v=x.text+`
198
201
 
199
- Command timed out and was forcefully terminated after `+t.maxTimeout+"ms",exitCode:-9,isSuccess:!1,duration:C,platform:s})},500))},1e3))};S=setTimeout(()=>{B(`Max timeout reached (${t.maxTimeout}ms)`)},t.maxTimeout),t.initialTimeout>0&&(w=setTimeout(()=>{!f&&!h&&B(`No output received within initial timeout (${t.initialTimeout}ms)`)},t.initialTimeout));let _=()=>{y=Date.now(),t.useActivityTimeout&&(b&&clearTimeout(b),b=setTimeout(()=>{if(!h){let N=Date.now()-y;B(`No output for ${N}ms (activity timeout: ${t.activityTimeout}ms)`)}},t.activityTimeout))};t.useActivityTimeout&&_(),l.stdout?.on("data",N=>{f=!0,_(),w&&(clearTimeout(w),w=null),u+=N.toString()}),l.stderr?.on("data",N=>{f=!0,_(),w&&(clearTimeout(w),w=null),d+=N.toString()}),l.on("exit",(N,C)=>{C&&!p&&(d+=`
200
- [Process terminated by signal: ${C}]`),x=setTimeout(()=>{if(h)return;P(),this.cleanupStreams(l);let E=Date.now()-o,g=(u+d).trim();if(_t.exceedsResponseLimit(g)){let T=_t.truncate(g),I=T.text.split(`
201
- `);g=T.text+`
202
+ [Output truncated at `+x.tokens.toLocaleString()+` tokens]
203
+ [Showing first `+U.length+" lines of output]"}if(p){let x=g==="activity"?t.activityTimeout:g==="initial"?t.initialTimeout:t.maxTimeout,U=wo(e,x,g,m);O({output:v+U,exitCode:-15,isSuccess:!1,duration:f,platform:o})}else O({output:v,exitCode:N||0,isSuccess:(N||0)===0,duration:f,platform:o})},100)}),l.on("close",N=>{if(h)return;R();let k=Date.now()-s,f=(u+d).trim();if(Ut.exceedsResponseLimit(f)){let v=Ut.count(f),x=Ut.truncate(f),A=x.text.split(`
204
+ `).length;f=x.text+`
202
205
 
203
- [Output truncated at `+T.tokens.toLocaleString()+` tokens]
204
- [Showing first `+I.length+" lines of output]"}A(p?{output:g+`
205
-
206
- ❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:E,platform:s}:{output:g,exitCode:N||0,isSuccess:(N||0)===0,duration:E,platform:s})},100)}),l.on("close",N=>{if(h)return;P();let C=Date.now()-o,E=(u+d).trim();if(_t.exceedsResponseLimit(E)){let g=_t.count(E),T=_t.truncate(E),M=T.text.split(`
207
- `).length;E=T.text+`
208
-
209
- [Output truncated at `+T.tokens.toLocaleString()+` tokens]
210
- [Showing first `+M+` lines of output]
211
- [Total output was `+g.toLocaleString()+" tokens]"}A(p?{output:E+`
212
-
213
- ❌ Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1,duration:C,platform:s}:{output:E,exitCode:N||0,isSuccess:(N||0)===0,duration:C,platform:s})}),l.on("error",N=>{if(h)return;P();let C=Date.now()-o;A({output:"Process execution failed: "+N.message,exitCode:-1,isSuccess:!1,duration:C,platform:s})})})}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`)}};ya=[{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"}];Ca=[/^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+clean\s+-[fdxXe]+/,/^docker\s+volume\s+rm\s+/,/^docker\s+volume\s+prune/,/^aws\s+s3\s+rm\s+/,/^aws\s+s3\s+rb\s+/,/^gsutil\s+rm\s+/,/^gsutil\s+-m\s+rm/,/^gsutil\s+rb\s+/,/^az\s+storage\s+.*delete/,/^rclone\s+delete/,/^rclone\s+purge/,/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/,/^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+/,/^borg\s+delete/,/^borg\s+prune/,/^duplicity\s+remove/,/^tmutil\s+delete/]});var fo={};Ee(fo,{ToolCallingService:()=>Ut});import{EventEmitter as ka}from"events";import $s from"axios";import{exec as Ia,spawn as Us}from"child_process";import{promisify as Pa}from"util";import re from"fs/promises";import Re from"fs";import vt from"path";import Aa from"os";var tp,pn,Ls,Da,Ut,mn=D(()=>{"use strict";ft();mo();mt();tp=Pa(Ia),pn=5,Ls=20,Da=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Ut=class c extends ka{static instance;tools=new Map;executionHistory=[];tokenCounter=new ye;shellSessionManager=$t.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;backgroundProcesses=new Map;backgroundProcessCounter=0;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<pn&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${pn})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Da.has(e))return t();if(this.activeToolExecutions<pn){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=Ls)throw console.warn(`⚠️ [ToolQueue] Queue full (${Ls}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,o)=>{let s=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${pn})`),this.toolExecutionQueue.push({id:s,toolName:e,execute:t,resolve:n,reject:o,queuedAt:Date.now()})})}static getInstance(){return c.instance||(c.instance=new c),c.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.
206
+ [Output truncated at `+x.tokens.toLocaleString()+` tokens]
207
+ [Showing first `+A+` lines of output]
208
+ [Total output was `+v.toLocaleString()+" tokens]"}if(p){let v=g==="activity"?t.activityTimeout:g==="initial"?t.initialTimeout:t.maxTimeout,x=wo(e,v,g,m);O({output:f+x,exitCode:-15,isSuccess:!1,duration:k,platform:o})}else O({output:f,exitCode:N||0,isSuccess:(N||0)===0,duration:k,platform:o})}),l.on("error",N=>{if(h)return;R();let k=Date.now()-s;O({output:"Process execution failed: "+N.message,exitCode:-1,isSuccess:!1,duration:k,platform:o})})})}formatExitCodeInfo(e){let t;switch(e){case 0:t="Success";break;case 1:t="General error";break;case 2:t="Misuse of shell command";break;case 126:t="Command cannot execute (permission denied)";break;case 127:t="Command not found";break;case 128:t="Invalid exit argument";break;case 130:t="Terminated by Ctrl+C (SIGINT)";break;case 137:t="Killed by SIGKILL";break;case 143:t="Terminated by SIGTERM";break;default:e>128?t=`Terminated by signal ${e-128}`:e<0?t="Terminated by timeout or force kill":t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}};Na=[{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"}];_a=[/^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+clean\s+-[fdxXe]+/,/^docker\s+volume\s+rm\s+/,/^docker\s+volume\s+prune/,/^aws\s+s3\s+rm\s+/,/^aws\s+s3\s+rb\s+/,/^gsutil\s+rm\s+/,/^gsutil\s+-m\s+rm/,/^gsutil\s+rb\s+/,/^az\s+storage\s+.*delete/,/^rclone\s+delete/,/^rclone\s+purge/,/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/,/^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+/,/^borg\s+delete/,/^borg\s+prune/,/^duplicity\s+remove/,/^tmutil\s+delete/]});var Eo={};ke(Eo,{ToolCallingService:()=>Wt});import{EventEmitter as $a}from"events";import Vs from"axios";import{exec as Ua,spawn as Ks}from"child_process";import{promisify as La}from"util";import ie from"fs/promises";import _e from"fs";import Tt from"path";import Wa from"os";var fp,fn,Qs,Ba,Wt,vn=D(()=>{"use strict";bt();So();ht();fp=La(Ua),fn=5,Qs=20,Ba=new Set(["Bash","execute_command","read_file","write_file","Edit","Grep","Glob"]),Wt=class c extends $a{static instance;tools=new Map;executionHistory=[];tokenCounter=new Se;shellSessionManager=Lt.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;backgroundProcesses=new Map;backgroundProcessCounter=0;toolExecutionQueue=[];activeToolExecutions=0;activeToolIds=new Set;constructor(){super(),this.initializeDefaultTools()}generateToolExecId(){return`tool-${Date.now()}-${Math.random().toString(36).substr(2,6)}`}processToolQueue(){for(;this.activeToolExecutions<fn&&this.toolExecutionQueue.length>0;){let e=this.toolExecutionQueue.shift();this.activeToolExecutions++,this.activeToolIds.add(e.id);let t=Date.now()-e.queuedAt;t>100&&console.log(`🔄 [ToolQueue] Dequeued ${e.toolName} (waited ${t}ms, active: ${this.activeToolExecutions}/${fn})`),e.execute().then(n=>{e.resolve(n)}).catch(n=>{e.reject(n)}).finally(()=>{this.activeToolExecutions--,this.activeToolIds.delete(e.id),this.processToolQueue()})}}async queueToolExecution(e,t){if(!Ba.has(e))return t();if(this.activeToolExecutions<fn){let n=this.generateToolExecId();this.activeToolExecutions++,this.activeToolIds.add(n);try{return await t()}finally{this.activeToolExecutions--,this.activeToolIds.delete(n),this.processToolQueue()}}if(this.toolExecutionQueue.length>=Qs)throw console.warn(`⚠️ [ToolQueue] Queue full (${Qs}), rejecting ${e}`),new Error("Tool execution queue full. Please wait for current operations to complete.");return new Promise((n,s)=>{let o=this.generateToolExecId();console.log(`📥 [ToolQueue] Queueing ${e} (queue: ${this.toolExecutionQueue.length+1}, active: ${this.activeToolExecutions}/${fn})`),this.toolExecutionQueue.push({id:o,toolName:e,execute:t,resolve:n,reject:s,queuedAt:Date.now()})})}static getInstance(){return c.instance||(c.instance=new c),c.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
209
 
215
210
  🔧 SESSION MODE SELECTION (REQUIRED):
216
211
  • Use session: "existing" for workflows that need persistent state:
@@ -244,19 +239,19 @@ If you believe this is a false positive, please:
244
239
  4. LLM receives prompt details and makes decision
245
240
  5. LLM uses provide_input to send appropriate response
246
241
  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(e){this.tools.set(e.name,e)}unregisterTool(e){let t=this.tools.delete(e);return t}async executeTool(e){let t=Date.now(),n=e.function.name;this.emit("tool_execution_start",{toolName:n,toolCall:e});let o={};try{o=JSON.parse(e.function.arguments)}catch(r){throw new Error(`Invalid arguments for tool '${n}': ${r}`)}let{ToolDisplay:s}=await Promise.resolve().then(()=>(Ie(),Cs));s.start(n,o.description,o.command||o.file_path);try{let r=this.tools.get(n);if(!r)throw new Error(`Tool '${n}' not found`);if(!r.enabled)throw new Error(`Tool '${n}' is disabled`);let a=await this.queueToolExecution(n,()=>r.handler(o)),l=Date.now()-t,u=this.handleLargeResponse(a,n);return this.executionHistory.push({toolName:n,args:o,result:u,timestamp:new Date,executionTime:l}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:n,result:u,executionTime:l}),s.result({toolName:n,command:o.command,filePath:o.file_path,description:o.description,output:this.extractOutputForDisplay(u),success:u.success,executionTime:l}),await this.captureFrontendToolResult(n,u),u}catch(r){let a=Date.now()-t,l={success:!1,error:r.message};return this.emit("tool_execution_error",{toolName:n,error:r,executionTime:a}),s.error(n,r.message),await this.captureFrontendToolResult(n,l),l}}extractOutputForDisplay(e){return e.success?e.result?typeof e.result=="string"?e.result:typeof e.result=="object"&&"stdout"in e.result?e.result.stdout||e.result.stderr||"":typeof e.result=="object"&&"content"in e.result?e.result.content||"":JSON.stringify(e.result,null,2):"":e.error||"Unknown error"}async captureFrontendToolResult(e,t){let{PersonalAgentService:n}=await Promise.resolve().then(()=>(Pe(),nt)),o=n.getInstance(),s=this.extractOutputForDisplay(t);o.captureFrontendToolResult(e,s,t.success)}async webSearch(e){try{let t=`https://api.duckduckgo.com/?q=${encodeURIComponent(e.query)}&format=json&no_html=1&skip_disambig=1`,o=(await $s.get(t,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,s=[];if(o.AbstractText&&s.push({title:o.Heading||"Instant Answer",content:o.AbstractText,url:o.AbstractURL||"",type:"instant_answer"}),o.RelatedTopics&&o.RelatedTopics.length>0)for(let r of o.RelatedTopics.slice(0,e.num_results||5))r.Text&&s.push({title:r.Text.split(" - ")[0]||"Related Topic",content:r.Text,url:r.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:e.query,results:s,total_results:s.length}}}catch(t){return{success:!1,error:`Web search failed: ${t.message}`}}}async readFile(e){try{let t=await re.readFile(e.file_path,"utf-8");return this.cacheFileState(e.file_path,t),{success:!0,result:{file_path:e.file_path,content:t,size:t.length}}}catch(t){return{success:!1,error:`Failed to read file: ${t.message}`}}}async writeFile(e){try{let{file_path:t,content:n,mode:o="write"}=e;if(t.endsWith(".ipynb")&&Re.existsSync(t)){let r=await re.readFile(t,"utf-8"),a=JSON.parse(r);if(a.cells.length>0&&a.cells[0].id){let l=a.cells.findIndex(u=>u.id===a.cells[0].id);if(l!==-1)return a.cells[l].source=n,await re.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}Re.existsSync(t)&&o!=="append"&&await this.validateFileNotModified(t);let s=vt.dirname(t);return await re.mkdir(s,{recursive:!0}),o==="append"?await re.appendFile(t,n):await re.writeFile(t,n),this.cacheFileState(t,n),{success:!0,result:{file_path:t,bytes_written:n.length,mode:o}}}catch(t){return{success:!1,error:`Failed to write file: ${t.message}`}}}async listDirectory(e){try{let t=await re.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let o of t){if(!e.include_hidden&&o.name.startsWith("."))continue;let s=await re.stat(vt.join(e.directory_path,o.name));n.push({name:o.name,type:o.isDirectory()?"directory":"file",size:s.size,modified:s.mtime.toISOString()})}return{success:!0,result:{directory_path:e.directory_path,entries:n,total_count:n.length}}}catch(t){return{success:!1,error:`Failed to list directory: ${t.message}`}}}async executeCommandWithSession(e){try{let t=$t.parseSessionMode(e.session),n=Ft(e.command),o={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout},s=await this.shellSessionManager.executeCommand(e.command,`tool-${Date.now()}`,this.currentUserId,e.session||"new",t,o);return{success:s.isSuccess,result:{command:e.command,stdout:s.output,stderr:"",exit_code:s.exitCode}}}catch(t){return{success:!1,error:`Command execution failed: ${t.message}`,result:{command:e.command,stdout:"",stderr:t.message||"",exit_code:-1}}}}async provideInput(e){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:e.input}}}async calculate(e){try{let t=e.expression.replace(/[^0-9+\-*/.() ]/g,"");if(t!==e.expression)throw new Error("Invalid characters in expression");let n=new Function("return "+t)();return{success:!0,result:{expression:e.expression,result:n,type:typeof n}}}catch(t){return{success:!1,error:`Calculation failed: ${t.message}`}}}async httpRequest(e){try{let t=await $s({method:e.method||"GET",url:e.url,headers:e.headers,data:e.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:e.url,status:t.status,headers:t.headers,data:typeof t.data=="string"?t.data.substring(0,1e4):t.data}}}catch(t){return{success:!1,error:`HTTP request failed: ${t.message}`,result:{url:e.url,status:t.response?.status||0,error_details:t.response?.data}}}}async getCurrentTime(e){try{let t=new Date,n={};switch(e.format){case"unix":n.timestamp=Math.floor(t.getTime()/1e3);break;case"local":n.datetime=t.toLocaleString();break;case"iso":default:n.datetime=t.toISOString();break}return n.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,n.format=e.format||"iso",{success:!0,result:n}}catch(t){return{success:!1,error:`Failed to get current time: ${t.message}`}}}async bashCommand(e){try{let{command:t,timeout:n,run_in_background:o=!1}=e;if(o){this.backgroundProcessCounter++;let a=`bg-${this.backgroundProcessCounter}`,l=Us("/bin/bash",["-c",t],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),u={process:l,command:t,startTime:new Date,stdout:"",stderr:""};l.stdout.on("data",p=>{let m=p.toString();if(m){let h=this.backgroundProcesses.get(a);h&&(h.stdout+=m,this.backgroundProcesses.set(a,h))}}),l.stderr.on("data",p=>{let m=p.toString();if(m){let h=this.backgroundProcesses.get(a);h&&(h.stderr+=m,this.backgroundProcesses.set(a,h))}}),l.on("close",p=>{let m=this.backgroundProcesses.get(a);m&&(m.exitCode=p||0,this.backgroundProcesses.set(a,m))}),this.backgroundProcesses.set(a,u);let d=`Command started in background with ID: ${a}
242
+ 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(e){this.tools.set(e.name,e)}unregisterTool(e){let t=this.tools.delete(e);return t}async executeTool(e){let t=Date.now(),n=e.function.name;this.emit("tool_execution_start",{toolName:n,toolCall:e});let s={};try{s=JSON.parse(e.function.arguments)}catch(r){throw new Error(`Invalid arguments for tool '${n}': ${r}`)}let{ToolDisplay:o}=await Promise.resolve().then(()=>(Pe(),_s));o.start(n,s.description,s.command||s.file_path);try{let r=this.tools.get(n);if(!r)throw new Error(`Tool '${n}' not found`);if(!r.enabled)throw new Error(`Tool '${n}' is disabled`);let a=await this.queueToolExecution(n,()=>r.handler(s)),l=Date.now()-t,u=this.handleLargeResponse(a,n);return this.executionHistory.push({toolName:n,args:s,result:u,timestamp:new Date,executionTime:l}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:n,result:u,executionTime:l}),o.result({toolName:n,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(u),success:u.success,executionTime:l}),await this.captureFrontendToolResult(n,u),u}catch(r){let a=Date.now()-t,l={success:!1,error:r.message};return this.emit("tool_execution_error",{toolName:n,error:r,executionTime:a}),o.error(n,r.message),await this.captureFrontendToolResult(n,l),l}}extractOutputForDisplay(e){return e.success?e.result?typeof e.result=="string"?e.result:typeof e.result=="object"&&"stdout"in e.result?e.result.stdout||e.result.stderr||"":typeof e.result=="object"&&"content"in e.result?e.result.content||"":JSON.stringify(e.result,null,2):"":e.error||"Unknown error"}async captureFrontendToolResult(e,t){let{PersonalAgentService:n}=await Promise.resolve().then(()=>(Ae(),it)),s=n.getInstance(),o=this.extractOutputForDisplay(t);s.captureFrontendToolResult(e,o,t.success)}async webSearch(e){try{let t=`https://api.duckduckgo.com/?q=${encodeURIComponent(e.query)}&format=json&no_html=1&skip_disambig=1`,s=(await Vs.get(t,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,o=[];if(s.AbstractText&&o.push({title:s.Heading||"Instant Answer",content:s.AbstractText,url:s.AbstractURL||"",type:"instant_answer"}),s.RelatedTopics&&s.RelatedTopics.length>0)for(let r of s.RelatedTopics.slice(0,e.num_results||5))r.Text&&o.push({title:r.Text.split(" - ")[0]||"Related Topic",content:r.Text,url:r.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:e.query,results:o,total_results:o.length}}}catch(t){return{success:!1,error:`Web search failed: ${t.message}`}}}async readFile(e){try{let t=await ie.readFile(e.file_path,"utf-8");return this.cacheFileState(e.file_path,t),{success:!0,result:{file_path:e.file_path,content:t,size:t.length}}}catch(t){return{success:!1,error:`Failed to read file: ${t.message}`}}}async writeFile(e){try{let{file_path:t,content:n,mode:s="write"}=e;if(t.endsWith(".ipynb")&&_e.existsSync(t)){let r=await ie.readFile(t,"utf-8"),a=JSON.parse(r);if(a.cells.length>0&&a.cells[0].id){let l=a.cells.findIndex(u=>u.id===a.cells[0].id);if(l!==-1)return a.cells[l].source=n,await ie.writeFile(t,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{file_path:t,bytes_written:n.length,message:"Notebook cell written successfully"}}}}_e.existsSync(t)&&s!=="append"&&await this.validateFileNotModified(t);let o=Tt.dirname(t);return await ie.mkdir(o,{recursive:!0}),s==="append"?await ie.appendFile(t,n):await ie.writeFile(t,n),this.cacheFileState(t,n),{success:!0,result:{file_path:t,bytes_written:n.length,mode:s}}}catch(t){return{success:!1,error:`Failed to write file: ${t.message}`}}}async listDirectory(e){try{let t=await ie.readdir(e.directory_path,{withFileTypes:!0}),n=[];for(let s of t){if(!e.include_hidden&&s.name.startsWith("."))continue;let o=await ie.stat(Tt.join(e.directory_path,s.name));n.push({name:s.name,type:s.isDirectory()?"directory":"file",size:o.size,modified:o.mtime.toISOString()})}return{success:!0,result:{directory_path:e.directory_path,entries:n,total_count:n.length}}}catch(t){return{success:!1,error:`Failed to list directory: ${t.message}`}}}async executeCommandWithSession(e){try{let t=Lt.parseSessionMode(e.session),n=$t(e.command),s={activityTimeout:e.timeout||n.activityTimeout,maxTimeout:e.timeout||n.maxTimeout,initialTimeout:n.initialTimeout},o=await this.shellSessionManager.executeCommand(e.command,`tool-${Date.now()}`,this.currentUserId,e.session||"new",t,s);return{success:o.isSuccess,result:{command:e.command,stdout:o.output,stderr:"",exit_code:o.exitCode}}}catch(t){return{success:!1,error:`Command execution failed: ${t.message}`,result:{command:e.command,stdout:"",stderr:t.message||"",exit_code:-1}}}}async provideInput(e){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:e.input}}}async calculate(e){try{let t=e.expression.replace(/[^0-9+\-*/.() ]/g,"");if(t!==e.expression)throw new Error("Invalid characters in expression");let n=new Function("return "+t)();return{success:!0,result:{expression:e.expression,result:n,type:typeof n}}}catch(t){return{success:!1,error:`Calculation failed: ${t.message}`}}}async httpRequest(e){try{let t=await Vs({method:e.method||"GET",url:e.url,headers:e.headers,data:e.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:e.url,status:t.status,headers:t.headers,data:typeof t.data=="string"?t.data.substring(0,1e4):t.data}}}catch(t){return{success:!1,error:`HTTP request failed: ${t.message}`,result:{url:e.url,status:t.response?.status||0,error_details:t.response?.data}}}}async getCurrentTime(e){try{let t=new Date,n={};switch(e.format){case"unix":n.timestamp=Math.floor(t.getTime()/1e3);break;case"local":n.datetime=t.toLocaleString();break;case"iso":default:n.datetime=t.toISOString();break}return n.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,n.format=e.format||"iso",{success:!0,result:n}}catch(t){return{success:!1,error:`Failed to get current time: ${t.message}`}}}async bashCommand(e){try{let{command:t,timeout:n,run_in_background:s=!1}=e;if(s){this.backgroundProcessCounter++;let a=`bg-${this.backgroundProcessCounter}`,l=Ks("/bin/bash",["-c",t],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),u={process:l,command:t,startTime:new Date,stdout:"",stderr:""};l.stdout.on("data",p=>{let m=p.toString();if(m){let g=this.backgroundProcesses.get(a);g&&(g.stdout+=m,this.backgroundProcesses.set(a,g))}}),l.stderr.on("data",p=>{let m=p.toString();if(m){let g=this.backgroundProcesses.get(a);g&&(g.stderr+=m,this.backgroundProcesses.set(a,g))}}),l.on("close",p=>{let m=this.backgroundProcesses.get(a);m&&(m.exitCode=p||0,this.backgroundProcesses.set(a,m))}),this.backgroundProcesses.set(a,u);let d=`Command started in background with ID: ${a}
248
243
  PID: ${l.pid}
249
244
  Command: ${t}
250
245
 
251
246
  Note: The process will continue running in the background.
252
- Output will be collected automatically.`;return{success:!0,result:{process_id:a,pid:l.pid,message:d}}}let s=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:Ft(t),r=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",s);return{success:r.isSuccess,result:{command:t,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:o,replace_all:s=!1}=e;if(n===o)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&Re.existsSync(t)){let l=await re.readFile(t,"utf-8"),u=JSON.parse(l);for(let d=0;d<u.cells.length;d++){let p=u.cells[d],m=Array.isArray(p.source)?p.source.join(""):p.source;if(m.includes(n)){let h=s?m.replaceAll(n,o):m.replace(n,o);return u.cells[d].source=h,await re.writeFile(t,JSON.stringify(u,null,2),"utf-8"),{success:!0,result:{file_path:t,replacements:s?m.split(n).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(t);let r=await re.readFile(t,"utf-8");if(!r.includes(n))throw new Error("String not found in file. Check for whitespace/indentation differences.");let a=s?r.replaceAll(n,o):r.replace(n,o);if(a===r)throw new Error("Edit failed: File content unchanged after replacement");return await re.writeFile(t,a,"utf-8"),this.cacheFileState(t,a),{success:!0,result:{file_path:t,replacements:s?r.split(n).length-1:1,message:"File edited successfully"}}}catch(t){return{success:!1,error:`Edit failed: ${t.message}`}}}async grepFiles(e){try{let{pattern:t,path:n=process.cwd(),glob:o,output_mode:s="files_with_matches",case_insensitive:r=!1}=e,a=[];return r&&a.push("-i"),s==="files_with_matches"?a.push("-l"):s==="count"&&a.push("-c"),o&&a.push("--glob",o),a.push(t,n),new Promise(l=>{let u=Us("rg",a,{stdio:["ignore","pipe","pipe"]}),d="",p="";u.stdout.on("data",m=>{d+=m.toString()}),u.stderr.on("data",m=>{p+=m.toString()}),u.on("close",m=>{if(m!==0&&m!==1){l({success:!1,error:`ripgrep failed: ${p||"Unknown error"}`});return}let h=d.trim().split(`
253
- `).filter(y=>y),f=h.length;l({success:!0,result:{pattern:t,num_files:f,files:h,output:d.trim()}})}),u.on("error",m=>{l({success:!1,error:`Failed to execute ripgrep: ${m.message}. Make sure ripgrep is installed.`})})})}catch(t){return{success:!1,error:`Grep failed: ${t.message}`}}}async globFiles(e){try{let{pattern:t,path:n=process.cwd()}=e,s=(l=>{let u=l;return u=u.replace(/[.+^${}()|[\]\\]/g,"\\$&"),u=u.replace(/\*\*/g,"<DOUBLESTAR>"),u=u.replace(/\*/g,"[^/]*"),u=u.replace(/<DOUBLESTAR>/g,".*"),u=u.replace(/\?/g,"."),new RegExp(`^${u}$`)})(t),r=[],a=async l=>{try{let u=await re.readdir(l,{withFileTypes:!0});for(let d of u){if(d.name.startsWith("."))continue;let p=vt.join(l,d.name),m=vt.relative(n,p);d.isDirectory()?await a(p):(s.test(m)||s.test(d.name))&&r.push(p)}}catch{}};return await a(n),{success:!0,result:{pattern:t,num_files:r.length,files:r}}}catch(t){return{success:!1,error:`Glob failed: ${t.message}`}}}async editNotebook(e){try{let{notebook_path:t,cell_id:n,new_source:o,cell_type:s="code",edit_mode:r="replace"}=e;if(!Re.existsSync(t))throw new Error(`Notebook file does not exist: ${t}`);if(!t.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let a=await re.readFile(t,"utf-8"),l=JSON.parse(a);switch(r){case"replace":{if(!n)throw new Error("cell_id is required for replace mode");let u=l.cells.findIndex(d=>d.id===n);if(u===-1)throw new Error(`Cell with id ${n} not found`);l.cells[u].source=o;break}case"insert":{if(!s)throw new Error("cell_type is required for insert mode");let u={id:Math.random().toString(36).substring(2,15),cell_type:s,source:o,metadata:{},execution_count:s==="code"?null:void 0,outputs:s==="code"?[]:void 0};if(n){let d=l.cells.findIndex(p=>p.id===n);l.cells.splice(d+1,0,u)}else l.cells.unshift(u);break}case"delete":{if(!n)throw new Error("cell_id is required for delete mode");let u=l.cells.findIndex(d=>d.id===n);if(u===-1)throw new Error(`Cell with id ${n} not found`);l.cells.splice(u,1);break}default:throw new Error(`Invalid edit_mode: ${r}`)}return await re.writeFile(t,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{notebook_path:t,edit_mode:r,cell_id:n,message:"Notebook edited successfully"}}}catch(t){return{success:!1,error:`NotebookEdit failed: ${t.message}`}}}cacheFileState(e,t){try{let n=Re.statSync(e);this.fileStateCache.set(e,{content:t,modificationDate:n.mtime,filePath:e})}catch{}}async validateFileNotModified(e){let t=this.fileStateCache.get(e);if(!t){if(Re.existsSync(e)){let o=await re.readFile(e,"utf-8");this.cacheFileState(e,o)}return}if(Re.statSync(e).mtime.getTime()!==t.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let e=[];for(let[t,n]of this.tools.entries())n.enabled&&e.push({type:"function",function:{name:t,description:n.description,parameters:n.parameters}});return e}getToolsByCategory(e){return this.getAvailableTools().filter(t=>this.tools.get(t.function.name)?.category===e)}enableTool(e){let t=this.tools.get(e);return t?(t.enabled=!0,!0):!1}disableTool(e){let t=this.tools.get(e);return t?(t.enabled=!1,!0):!1}getExecutionHistory(e=10){return this.executionHistory.slice(-e)}getExecutionStats(){let e=this.executionHistory.length,t=this.executionHistory.filter(a=>a.result.success).length,n=e-t,o=e>0?this.executionHistory.reduce((a,l)=>a+l.executionTime,0)/e:0,s=new Map;this.executionHistory.forEach(a=>{s.set(a.toolName,(s.get(a.toolName)||0)+1)});let r=s.size>0?Array.from(s.entries()).reduce((a,l)=>l[1]>a[1]?l:a)[0]:null;return{total:e,successful:t,failed:n,averageTime:Math.round(o),mostUsed:r}}clearHistory(){this.executionHistory=[]}setUserId(e){this.currentUserId=e}getCurrentUserId(){return this.currentUserId}cleanupUserSession(e){}handleLargeResponse(e,t){if(!e.success||!e.result)return e;let n=typeof e.result=="string"?e.result:JSON.stringify(e.result);if(this.tokenCounter.exceedsResponseLimit(n)){let o=this.createTempFile(n,t);return o?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(n,o)}:{success:!0,result:this.tokenCounter.truncateOutput(n)}}return e}createTempFile(e,t){try{let n=Aa.tmpdir(),o=vt.join(n,"orion_tool_responses");Re.existsSync(o)||Re.mkdirSync(o,{recursive:!0});let s=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${s}_${r}.txt`,l=vt.join(o,a);return Re.writeFileSync(l,e,"utf8"),l}catch{return null}}stopAllRunningTools(){}}});import{spawn as Na}from"child_process";var gn,Ws=D(()=>{"use strict";$();ft();gn=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,o){let s=n.command;if(s==null)throw new Error("Missing command argument");if(typeof s!="string")throw new Error(`Command must be a string. Received: ${typeof s}`);if(s.trim().length===0)throw new Error("Command cannot be empty");let r=n.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(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let f=Number(n.timeout);if(Number.isNaN(f))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=f}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let l=n.description;l!=null&&typeof l!="string"&&i.debug(`[RunCommandTool] Invalid description type: ${typeof l}, ignoring`);let u=!1;if(n.run_in_background!==void 0&&n.run_in_background!==null)if(typeof n.run_in_background=="boolean")u=n.run_in_background;else if(typeof n.run_in_background=="string")u=n.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof n.run_in_background}`);let d=Fs(s);if(d)return i.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let p=_s(s);if(p.isDelete){i.debug("[RunCommandTool] Delete command detected, requesting confirmation"),i.debug(`[RunCommandTool] Affected targets: ${p.paths.join(", ")}`);let{FrontendWebSocketService:f}=await Promise.resolve().then(()=>(bt(),vo)),y=f.getInstance(),S;if(y.hasElectronFrontend())S=await y.requestDeleteConfirmation(s,l);else{let{PersonalAgentService:b}=await Promise.resolve().then(()=>(Pe(),nt)),w=b.getInstance();S=await this.requestCliConfirmation(w,s,p.paths,l)}if(S==="declined")return i.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${s}
247
+ Output will be collected automatically.`;return{success:!0,result:{process_id:a,pid:l.pid,message:d}}}let o=n?{activityTimeout:n,maxTimeout:n,initialTimeout:n}:$t(t),r=await this.shellSessionManager.executeCommand(t,`tool-${Date.now()}`,this.currentUserId,"new","new",o);return{success:r.isSuccess,result:{command:t,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(t){return{success:!1,error:`Bash command failed: ${t.message}`}}}async editFile(e){try{let{file_path:t,old_string:n,new_string:s,replace_all:o=!1}=e;if(n===s)throw new Error("No changes to make: old_string and new_string are identical");if(t.endsWith(".ipynb")&&_e.existsSync(t)){let l=await ie.readFile(t,"utf-8"),u=JSON.parse(l);for(let d=0;d<u.cells.length;d++){let p=u.cells[d],m=Array.isArray(p.source)?p.source.join(""):p.source;if(m.includes(n)){let g=o?m.replaceAll(n,s):m.replace(n,s);return u.cells[d].source=g,await ie.writeFile(t,JSON.stringify(u,null,2),"utf-8"),{success:!0,result:{file_path:t,replacements:o?m.split(n).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(t);let r=await ie.readFile(t,"utf-8");if(!r.includes(n))throw new Error("String not found in file. Check for whitespace/indentation differences.");let a=o?r.replaceAll(n,s):r.replace(n,s);if(a===r)throw new Error("Edit failed: File content unchanged after replacement");return await ie.writeFile(t,a,"utf-8"),this.cacheFileState(t,a),{success:!0,result:{file_path:t,replacements:o?r.split(n).length-1:1,message:"File edited successfully"}}}catch(t){return{success:!1,error:`Edit failed: ${t.message}`}}}async grepFiles(e){try{let{pattern:t,path:n=process.cwd(),glob:s,output_mode:o="files_with_matches",case_insensitive:r=!1}=e,a=[];return r&&a.push("-i"),o==="files_with_matches"?a.push("-l"):o==="count"&&a.push("-c"),s&&a.push("--glob",s),a.push(t,n),new Promise(l=>{let u=Ks("rg",a,{stdio:["ignore","pipe","pipe"]}),d="",p="";u.stdout.on("data",m=>{d+=m.toString()}),u.stderr.on("data",m=>{p+=m.toString()}),u.on("close",m=>{if(m!==0&&m!==1){l({success:!1,error:`ripgrep failed: ${p||"Unknown error"}`});return}let g=d.trim().split(`
248
+ `).filter(y=>y),h=g.length;l({success:!0,result:{pattern:t,num_files:h,files:g,output:d.trim()}})}),u.on("error",m=>{l({success:!1,error:`Failed to execute ripgrep: ${m.message}. Make sure ripgrep is installed.`})})})}catch(t){return{success:!1,error:`Grep failed: ${t.message}`}}}async globFiles(e){try{let{pattern:t,path:n=process.cwd()}=e,o=(l=>{let u=l;return u=u.replace(/[.+^${}()|[\]\\]/g,"\\$&"),u=u.replace(/\*\*/g,"<DOUBLESTAR>"),u=u.replace(/\*/g,"[^/]*"),u=u.replace(/<DOUBLESTAR>/g,".*"),u=u.replace(/\?/g,"."),new RegExp(`^${u}$`)})(t),r=[],a=async l=>{try{let u=await ie.readdir(l,{withFileTypes:!0});for(let d of u){if(d.name.startsWith("."))continue;let p=Tt.join(l,d.name),m=Tt.relative(n,p);d.isDirectory()?await a(p):(o.test(m)||o.test(d.name))&&r.push(p)}}catch{}};return await a(n),{success:!0,result:{pattern:t,num_files:r.length,files:r}}}catch(t){return{success:!1,error:`Glob failed: ${t.message}`}}}async editNotebook(e){try{let{notebook_path:t,cell_id:n,new_source:s,cell_type:o="code",edit_mode:r="replace"}=e;if(!_e.existsSync(t))throw new Error(`Notebook file does not exist: ${t}`);if(!t.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let a=await ie.readFile(t,"utf-8"),l=JSON.parse(a);switch(r){case"replace":{if(!n)throw new Error("cell_id is required for replace mode");let u=l.cells.findIndex(d=>d.id===n);if(u===-1)throw new Error(`Cell with id ${n} not found`);l.cells[u].source=s;break}case"insert":{if(!o)throw new Error("cell_type is required for insert mode");let u={id:Math.random().toString(36).substring(2,15),cell_type:o,source:s,metadata:{},execution_count:o==="code"?null:void 0,outputs:o==="code"?[]:void 0};if(n){let d=l.cells.findIndex(p=>p.id===n);l.cells.splice(d+1,0,u)}else l.cells.unshift(u);break}case"delete":{if(!n)throw new Error("cell_id is required for delete mode");let u=l.cells.findIndex(d=>d.id===n);if(u===-1)throw new Error(`Cell with id ${n} not found`);l.cells.splice(u,1);break}default:throw new Error(`Invalid edit_mode: ${r}`)}return await ie.writeFile(t,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{notebook_path:t,edit_mode:r,cell_id:n,message:"Notebook edited successfully"}}}catch(t){return{success:!1,error:`NotebookEdit failed: ${t.message}`}}}cacheFileState(e,t){try{let n=_e.statSync(e);this.fileStateCache.set(e,{content:t,modificationDate:n.mtime,filePath:e})}catch{}}async validateFileNotModified(e){let t=this.fileStateCache.get(e);if(!t){if(_e.existsSync(e)){let s=await ie.readFile(e,"utf-8");this.cacheFileState(e,s)}return}if(_e.statSync(e).mtime.getTime()!==t.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let e=[];for(let[t,n]of this.tools.entries())n.enabled&&e.push({type:"function",function:{name:t,description:n.description,parameters:n.parameters}});return e}getToolsByCategory(e){return this.getAvailableTools().filter(t=>this.tools.get(t.function.name)?.category===e)}enableTool(e){let t=this.tools.get(e);return t?(t.enabled=!0,!0):!1}disableTool(e){let t=this.tools.get(e);return t?(t.enabled=!1,!0):!1}getExecutionHistory(e=10){return this.executionHistory.slice(-e)}getExecutionStats(){let e=this.executionHistory.length,t=this.executionHistory.filter(a=>a.result.success).length,n=e-t,s=e>0?this.executionHistory.reduce((a,l)=>a+l.executionTime,0)/e:0,o=new Map;this.executionHistory.forEach(a=>{o.set(a.toolName,(o.get(a.toolName)||0)+1)});let r=o.size>0?Array.from(o.entries()).reduce((a,l)=>l[1]>a[1]?l:a)[0]:null;return{total:e,successful:t,failed:n,averageTime:Math.round(s),mostUsed:r}}clearHistory(){this.executionHistory=[]}setUserId(e){this.currentUserId=e}getCurrentUserId(){return this.currentUserId}cleanupUserSession(e){}handleLargeResponse(e,t){if(!e.success||!e.result)return e;let n=typeof e.result=="string"?e.result:JSON.stringify(e.result);if(this.tokenCounter.exceedsResponseLimit(n)){let s=this.createTempFile(n,t);return s?{success:!0,result:this.tokenCounter.formatLargeResponsePreview(n,s)}:{success:!0,result:this.tokenCounter.truncateOutput(n)}}return e}createTempFile(e,t){try{let n=Wa.tmpdir(),s=Tt.join(n,"orion_tool_responses");_e.existsSync(s)||_e.mkdirSync(s,{recursive:!0});let o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=Tt.join(s,a);return _e.writeFileSync(l,e,"utf8"),l}catch{return null}}stopAllRunningTools(){}}});import{spawn as Ha}from"child_process";var bn,Js=D(()=>{"use strict";L();bt();bn=class{toolNames=["bash","Bash","run_command"];async execute(e,t,n,s){let o=n.command;if(o==null)throw new Error("Missing command argument");if(typeof o!="string")throw new Error(`Command must be a string. Received: ${typeof o}`);if(o.trim().length===0)throw new Error("Command cannot be empty");let r=n.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(n.timeout!==void 0&&n.timeout!==null){if(typeof n.timeout=="string"){let h=Number(n.timeout);if(Number.isNaN(h))throw new Error(`Timeout must be a valid number. Received string: "${n.timeout}"`);a=h}else if(typeof n.timeout=="number"){if(Number.isNaN(n.timeout))throw new Error("Timeout cannot be NaN");if(!Number.isFinite(n.timeout))throw new Error(`Timeout must be finite. Received: ${n.timeout}`);a=n.timeout}else throw new Error(`Timeout must be a number. Received: ${typeof n.timeout}`);if(a<=0)throw new Error(`Timeout must be positive. Received: ${a}ms`);if(a>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${a}ms`);a=Math.floor(a)}let l=n.description;l!=null&&typeof l!="string"&&i.debug(`[RunCommandTool] Invalid description type: ${typeof l}, ignoring`);let u=!1;if(n.run_in_background!==void 0&&n.run_in_background!==null)if(typeof n.run_in_background=="boolean")u=n.run_in_background;else if(typeof n.run_in_background=="string")u=n.run_in_background.toLowerCase()==="true";else throw new Error(`run_in_background must be a boolean. Received: ${typeof n.run_in_background}`);let d=js(o);if(d)return i.debug("[RunCommandTool] Command blocked by security check"),[{type:"text",text:d}];let p=Xs(o);if(p.isDelete){i.debug("[RunCommandTool] Delete command detected, requesting confirmation"),i.debug(`[RunCommandTool] Affected targets: ${p.paths.join(", ")}`);let{FrontendWebSocketService:h}=await Promise.resolve().then(()=>(yt(),ko)),y=h.getInstance(),T;if(y.hasElectronFrontend())T=await y.requestDeleteConfirmation(o,l);else{let{PersonalAgentService:S}=await Promise.resolve().then(()=>(Ae(),it)),w=S.getInstance();T=await this.requestCliConfirmation(w,o,p.paths,l)}if(T==="declined")return i.debug("[RunCommandTool] User declined delete command"),[{type:"text",text:`User declined the delete. Command NOT executed: ${o}
254
249
 
255
250
  ALTERNATIVES (choose one):
256
251
  • Rename instead: mv [file] [file].old or mv [file] [file].legacy
257
252
  • Backup first: cp -r [path] [path].backup, then ask again
258
253
  • Skip and continue: If not critical, move on to other tasks
259
- • Ask user: Briefly confirm if they want to keep or remove it`}];if(S==="timeout")return i.debug("[RunCommandTool] Delete confirmation timed out"),[{type:"text",text:`No response (30s timeout). Command NOT executed: ${s}
254
+ • Ask user: Briefly confirm if they want to keep or remove it`}];if(T==="timeout")return i.debug("[RunCommandTool] Delete confirmation timed out"),[{type:"text",text:`No response (30s timeout). Command NOT executed: ${o}
260
255
 
261
256
  User is likely busy or away. DON'T wait - choose an alternative:
262
257
 
@@ -269,23 +264,23 @@ IF CRITICAL (user explicitly asked to delete):
269
264
  • Create backup first: cp -r [path] [path].backup
270
265
  • Then mention you'll need confirmation to delete later
271
266
 
272
- DO NOT keep retrying the same delete command.`}];if(S==="error")return i.debug("[RunCommandTool] Delete confirmation failed"),[{type:"text",text:`Failed to show delete confirmation dialog. The command was NOT executed for safety.
267
+ DO NOT keep retrying the same delete command.`}];if(T==="error")return i.debug("[RunCommandTool] Delete confirmation failed"),[{type:"text",text:`Failed to show delete confirmation dialog. The command was NOT executed for safety.
273
268
 
274
- Please try again or ask the user to confirm the deletion manually.`}];i.debug("[RunCommandTool] User confirmed delete command, proceeding")}let m=a||12e4,h=ho();if(i.debug(`[RunCommandTool] Executing command on platform: ${h}`),i.debug(`[RunCommandTool] Command: ${s.substring(0,50)}${s.length>50?"...":""}`),l&&i.debug(`[RunCommandTool] Description: ${l}`),i.debug(`[RunCommandTool] Session: ${r}, Timeout: ${m}ms, Background: ${u}`),u)return this.executeBackground(e,s,m,o);try{let f=(await Promise.resolve().then(()=>(mn(),fo))).ToolCallingService.getInstance(),y={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:s,session:r,timeout:m})}},S=await f.executeTool(y),b="";if(S.success){let w=(S.result?.stdout||"").trim(),k=S.result?.exitCode??0;if(b=`Command: ${s}
275
- `,b+=`Exit Code: ${k}
269
+ Please try again or ask the user to confirm the deletion manually.`}];i.debug("[RunCommandTool] User confirmed delete command, proceeding")}let m=a||12e4,g=xo();if(i.debug(`[RunCommandTool] Executing command on platform: ${g}`),i.debug(`[RunCommandTool] Command: ${o.substring(0,50)}${o.length>50?"...":""}`),l&&i.debug(`[RunCommandTool] Description: ${l}`),i.debug(`[RunCommandTool] Session: ${r}, Timeout: ${m}ms, Background: ${u}`),u)return this.executeBackground(e,o,m,s);try{let h=(await Promise.resolve().then(()=>(vn(),Eo))).ToolCallingService.getInstance(),y={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:o,session:r,timeout:m})}},T=await h.executeTool(y),S="";if(T.success){let w=(T.result?.stdout||"").trim(),E=T.result?.exitCode??0;if(S=`Command: ${o}
270
+ `,S+=`Exit Code: ${E}
276
271
 
277
- `,w.length>0){let v=w.split(`
278
- `),x=v.slice(0,15);b+=x.join(`
279
- `),v.length>15&&(b+=`
272
+ `,w.length>0){let b=w.split(`
273
+ `),C=b.slice(0,15);S+=C.join(`
274
+ `),b.length>15&&(S+=`
280
275
 
281
- ... (showing first 15 of ${v.length} lines)`)}else b+="(no output)";return[{type:"text",text:b}]}else{let w=S.error||"Unknown error",k=S.result?.exitCode??1;return b=`Command: ${s}
282
- `,b+=`Exit Code: ${k}
276
+ ... (showing first 15 of ${b.length} lines)`)}else S+="(no output)";return[{type:"text",text:S}]}else{let w=T.error||"Unknown error",E=T.result?.exitCode??1;return S=`Command: ${o}
277
+ `,S+=`Exit Code: ${E}
283
278
 
284
- `,b+=`Error:
285
- ${w}`,[{type:"text",text:b}]}}catch(f){return i.debug(`[RunCommandTool] Failed to execute bash command: ${f.message}`),[{type:"text",text:`Command: ${s}
286
- Error: ${f.message}`}]}}async requestCliConfirmation(e,t,n,o){let s=`delete-cli-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=3e4;return i.debug(`[RunCommandTool] Requesting CLI confirmation: ${s}`),new Promise(a=>{let l=setTimeout(()=>{i.debug(`[RunCommandTool] CLI confirmation timed out: ${s}`),e.off("confirmation_response",u),a("timeout")},r),u=d=>{d.confirmationId===s&&(clearTimeout(l),e.off("confirmation_response",u),d.timedOut?a("timeout"):d.confirmed?a("confirmed"):a("declined"))};e.on("confirmation_response",u),e.emit("confirmation_request",{confirmationId:s,type:"confirmation",title:"Confirm Delete",message:"The AI wants to delete files. Continue?",command:t,targets:n,isDestructive:!0,timeout:r}),i.debug(`[RunCommandTool] CLI confirmation request emitted: ${s}`)})}async executeBackground(e,t,n,o){let s=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r=o.workingDirectory||process.cwd();i.debug(`[RunCommandTool] Starting background process: ${s}`);let a,l;_e()?(a="powershell.exe",l=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",l=["-c",t]);let u=Na(a,l,{cwd:r,env:process.env,stdio:["ignore","pipe","pipe"],detached:!_e()});u.unref();let d={id:s,command:t,startTime:new Date,status:"running",output:[],error:[],pid:u.pid};le.addProcess(d);let p=5*1024*1024,m=0,h=0;return u.stdout?.on("data",f=>{if(m<p){let y=f.toString();d.output.push(y),m+=y.length,m>=p&&d.output.push("[Output truncated - buffer limit reached]")}}),u.stderr?.on("data",f=>{if(h<p){let y=f.toString();d.error.push(y),h+=y.length,h>=p&&d.error.push("[Error output truncated - buffer limit reached]")}}),u.on("exit",f=>{i.debug(`[RunCommandTool] Background process ${s} exited with code ${f}`),le.updateProcess(s,{endTime:new Date,exitCode:f??0,status:(f??0)===0?"completed":"failed"})}),u.on("error",f=>{i.debug(`[RunCommandTool] Background process ${s} error: ${f.message}`),d.error.push(f.message),le.updateProcess(s,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let f=le.getProcess(s);f&&f.status==="running"&&(i.debug(`[RunCommandTool] Background process ${s} timed out, killing...`),ht(u.pid,"SIGTERM"),setTimeout(()=>{let y=le.getProcess(s);y&&y.status==="running"&&ht(u.pid,"SIGKILL")},3e3),le.updateProcess(s,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${n}ms`))},n),[{type:"text",text:`Background process started with ID: ${s}
279
+ `,S+=`Error:
280
+ ${w}`,[{type:"text",text:S}]}}catch(h){return i.debug(`[RunCommandTool] Failed to execute bash command: ${h.message}`),[{type:"text",text:`Command: ${o}
281
+ Error: ${h.message}`}]}}async requestCliConfirmation(e,t,n,s){let o=`delete-cli-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=3e4;return i.debug(`[RunCommandTool] Requesting CLI confirmation: ${o}`),new Promise(a=>{let l=setTimeout(()=>{i.debug(`[RunCommandTool] CLI confirmation timed out: ${o}`),e.off("confirmation_response",u),a("timeout")},r),u=d=>{d.confirmationId===o&&(clearTimeout(l),e.off("confirmation_response",u),d.timedOut?a("timeout"):d.confirmed?a("confirmed"):a("declined"))};e.on("confirmation_response",u),e.emit("confirmation_request",{confirmationId:o,type:"confirmation",title:"Confirm Delete",message:"The AI wants to delete files. Continue?",command:t,targets:n,isDestructive:!0,timeout:r}),i.debug(`[RunCommandTool] CLI confirmation request emitted: ${o}`)})}async executeBackground(e,t,n,s){let o=`shell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r=s.workingDirectory||process.cwd();i.debug(`[RunCommandTool] Starting background process: ${o}`);let a,l;$e()?(a="powershell.exe",l=["-ExecutionPolicy","Bypass","-Command",t]):(a="/bin/bash",l=["-c",t]);let u=Ha(a,l,{cwd:r,env:process.env,stdio:["ignore","pipe","pipe"],detached:!$e()});u.unref();let d={id:o,command:t,startTime:new Date,status:"running",output:[],error:[],pid:u.pid};ue.addProcess(d);let p=5*1024*1024,m=0,g=0;return u.stdout?.on("data",h=>{if(m<p){let y=h.toString();d.output.push(y),m+=y.length,m>=p&&d.output.push("[Output truncated - buffer limit reached]")}}),u.stderr?.on("data",h=>{if(g<p){let y=h.toString();d.error.push(y),g+=y.length,g>=p&&d.error.push("[Error output truncated - buffer limit reached]")}}),u.on("exit",h=>{i.debug(`[RunCommandTool] Background process ${o} exited with code ${h}`),ue.updateProcess(o,{endTime:new Date,exitCode:h??0,status:(h??0)===0?"completed":"failed"})}),u.on("error",h=>{i.debug(`[RunCommandTool] Background process ${o} error: ${h.message}`),d.error.push(h.message),ue.updateProcess(o,{endTime:new Date,status:"failed"})}),n&&setTimeout(()=>{let h=ue.getProcess(o);h&&h.status==="running"&&(i.debug(`[RunCommandTool] Background process ${o} timed out, killing...`),vt(u.pid,"SIGTERM"),setTimeout(()=>{let y=ue.getProcess(o);y&&y.status==="running"&&vt(u.pid,"SIGKILL")},3e3),ue.updateProcess(o,{status:"killed",endTime:new Date}),d.error.push(`Process timed out after ${n}ms`))},n),[{type:"text",text:`Background process started with ID: ${o}
287
282
  PID: ${u.pid}
288
- Use BashOutput tool to get output.`}]}ensureMeaningfulOutput(e,t,n){let o=(e||"").trim();return o.length===0?n?`✅ Command '${t}' executed successfully.
283
+ Use BashOutput tool to get output.`}]}ensureMeaningfulOutput(e,t,n){let s=(e||"").trim();return s.length===0?n?`✅ Command '${t}' executed successfully.
289
284
 
290
285
  ℹ️ No output was produced, which may be expected for this operation. This typically means:
291
286
  • The command completed without errors
@@ -302,7 +297,7 @@ If you expected output, the command may need different parameters or the operati
302
297
  Consider:
303
298
  • Checking the command syntax and parameters
304
299
  • Verifying file permissions and paths
305
- • Running the command with verbose flags for more details`:o}}});var hn,Bs=D(()=>{"use strict";$();ft();hn=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,n,o){try{let s=n.bash_id||n.shell_id||n.task_id;if(!s)throw new Error("bash_id is required");if(typeof s!="string")throw new Error(`bash_id must be a string. Received: ${typeof s}`);i.debug(`[BashOutputTool] Retrieving output for process: ${s}`);let r=le.getProcess(s);if(!r)throw new Error(`Background process not found: ${s}`);let a=[...r.output,...r.error].join(""),l=r.status==="running",u=`Process ID: ${s}
300
+ • Running the command with verbose flags for more details`:s}}});var Tn,Ys=D(()=>{"use strict";L();bt();Tn=class{toolNames=["bash_output","BashOutput","TaskOutput"];async execute(e,t,n,s){try{let o=n.bash_id||n.shell_id||n.task_id;if(!o)throw new Error("bash_id is required");if(typeof o!="string")throw new Error(`bash_id must be a string. Received: ${typeof o}`);i.debug(`[BashOutputTool] Retrieving output for process: ${o}`);let r=ue.getProcess(o);if(!r)throw new Error(`Background process not found: ${o}`);let a=[...r.output,...r.error].join(""),l=r.status==="running",u=`Process ID: ${o}
306
301
  `;if(u+=`Status: ${r.status}
307
302
  `,u+=`PID: ${r.pid||"N/A"}
308
303
  `,u+=`Command: ${r.command}
@@ -314,7 +309,7 @@ Consider:
314
309
  --- Output ---
315
310
  `,a?u+=a:l?u+="(no output yet - process still running)":r.exitCode===0?u+=`Process completed successfully with no output.
316
311
 
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(s){return i.debug(`[BashOutputTool] Error: ${s.message}`),[{type:"text",text:`Error: ${s.message}`}]}}}});var fn,Hs=D(()=>{"use strict";$();ft();fn=class{toolNames=["kill_shell","KillShell"];async execute(e,t,n,o){try{let s=n.shell_id||n.bash_id||n.task_id;if(!s)throw new Error("shell_id is required");if(typeof s!="string")throw new Error(`shell_id must be a string. Received: ${typeof s}`);i.debug(`[KillShellTool] Killing process: ${s}`);let r=le.getProcess(s);if(!r)throw new Error(`Background process not found: ${s}`);if(r.status!=="running")throw new Error(`Process is not running (status: ${r.status})`);if(r.pid){ht(r.pid,"SIGTERM"),setTimeout(()=>{r.status==="running"&&ht(r.pid,"SIGKILL")},3e3),le.updateProcess(s,{status:"killed",endTime:new Date});let a=`Process ${s} (PID ${r.pid}) and its children killed successfully`;return i.debug(`[KillShellTool] ${a}`),[{type:"text",text:a}]}else throw new Error("Process has no PID")}catch(s){return i.debug(`[KillShellTool] Error: ${s.message}`),[{type:"text",text:`Error: ${s.message}`}]}}}});var bo,Ra,vn,Gs=D(()=>{"use strict";$();ft();bo=class c{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){i.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.instance}startMonitoring(e,t,n){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let o=le.getProcess(e);if(!o)return{success:!1,error:`Process not found: ${e}`};if(o.status!=="running")return{success:!1,error:`Process already completed with status: ${o.status}`};let s=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:s,onComplete:n}),i.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),i.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let n=le.getProcess(e);if(!n){this.stopMonitoring(e);return}n.status!=="running"&&(i.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${n.status}`),t.onComplete&&t.onComplete(n),this.stopMonitoring(e),this.emitAutoPrompt(e,n,t.reason))}async emitAutoPrompt(e,t,n){try{let{FrontendWebSocketService:o}=await Promise.resolve().then(()=>(bt(),vo)),s=o.getInstance();if(!s.isConnected()){i.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let r,a=t.output.join(`
312
+ Note: Many commands run silently when successful (e.g., file operations, installations). The exit code 0 confirms success.`:u+="(no output)",[{type:"text",text:u}]}catch(o){return i.debug(`[BashOutputTool] Error: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});var yn,Zs=D(()=>{"use strict";L();bt();yn=class{toolNames=["kill_shell","KillShell"];async execute(e,t,n,s){try{let o=n.shell_id||n.bash_id||n.task_id;if(!o)throw new Error("shell_id is required");if(typeof o!="string")throw new Error(`shell_id must be a string. Received: ${typeof o}`);i.debug(`[KillShellTool] Killing process: ${o}`);let r=ue.getProcess(o);if(!r)throw new Error(`Background process not found: ${o}`);if(r.status!=="running")throw new Error(`Process is not running (status: ${r.status})`);if(r.pid){vt(r.pid,"SIGTERM"),setTimeout(()=>{r.status==="running"&&vt(r.pid,"SIGKILL")},3e3),ue.updateProcess(o,{status:"killed",endTime:new Date});let a=`Process ${o} (PID ${r.pid}) and its children killed successfully`;return i.debug(`[KillShellTool] ${a}`),[{type:"text",text:a}]}else throw new Error("Process has no PID")}catch(o){return i.debug(`[KillShellTool] Error: ${o.message}`),[{type:"text",text:`Error: ${o.message}`}]}}}});var Io,Ga,Sn,er=D(()=>{"use strict";L();bt();Io=class c{static instance;monitoredProcesses=new Map;POLL_INTERVAL=1e3;constructor(){i.debug("[ProcessMonitoringService] Initialized")}static getInstance(){return c.instance||(c.instance=new c),c.instance}startMonitoring(e,t,n){if(this.monitoredProcesses.has(e))return{success:!1,error:`Already monitoring process: ${e}`};let s=ue.getProcess(e);if(!s)return{success:!1,error:`Process not found: ${e}`};if(s.status!=="running")return{success:!1,error:`Process already completed with status: ${s.status}`};let o=setInterval(()=>{this.checkProcess(e)},this.POLL_INTERVAL);return this.monitoredProcesses.set(e,{shellId:e,reason:t,startTime:new Date,intervalId:o,onComplete:n}),i.debug(`[ProcessMonitoringService] Started monitoring: ${e}`),{success:!0}}stopMonitoring(e){let t=this.monitoredProcesses.get(e);t&&(clearInterval(t.intervalId),this.monitoredProcesses.delete(e),i.debug(`[ProcessMonitoringService] Stopped monitoring: ${e}`))}checkProcess(e){let t=this.monitoredProcesses.get(e);if(!t)return;let n=ue.getProcess(e);if(!n){this.stopMonitoring(e);return}n.status!=="running"&&(i.debug(`[ProcessMonitoringService] Process ${e} completed with status: ${n.status}`),t.onComplete&&t.onComplete(n),this.stopMonitoring(e),this.emitAutoPrompt(e,n,t.reason))}async emitAutoPrompt(e,t,n){try{let{FrontendWebSocketService:s}=await Promise.resolve().then(()=>(yt(),ko)),o=s.getInstance();if(!o.isConnected()){i.debug("[ProcessMonitoringService] WebSocket not connected, cannot auto-prompt");return}let r,a=t.output.join(`
318
313
  `).substring(0,1e3),l=t.error.join(`
319
314
  `).substring(0,500);t.status==="completed"?r=`Background process completed successfully (ID: ${e}, Exit: ${t.exitCode}).
320
315
 
@@ -336,68 +331,68 @@ Reason for monitoring: ${n}
336
331
 
337
332
  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
333
 
339
- Reason for monitoring: ${n}`,s.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:n,message:r,timestamp:new Date().toISOString()}),i.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(o){i.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${o}`)}}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(),i.debug("[ProcessMonitoringService] Cleared all monitors")}},Ra=bo.getInstance(),vn=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,n,o){let s=n.shell_id,r=n.reason;if(!s||typeof s!="string"||s.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.`}];i.debug(`[MonitorRunningCliTool] Starting monitoring for ${s}`),i.debug(`[MonitorRunningCliTool] Reason: ${r}`);let a=Ra.startMonitoring(s,r);return a.success?(i.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${s}.
334
+ Reason for monitoring: ${n}`,o.emit("auto_prompt",{type:"process_completed",shellId:e,status:t.status,exitCode:t.exitCode,reason:n,message:r,timestamp:new Date().toISOString()}),i.debug(`[ProcessMonitoringService] Emitted auto-prompt for: ${e}`)}catch(s){i.debug(`[ProcessMonitoringService] Failed to emit auto-prompt: ${s}`)}}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(),i.debug("[ProcessMonitoringService] Cleared all monitors")}},Ga=Io.getInstance(),Sn=class{toolNames=["monitor_running_cli","MonitorRunningCli"];async execute(e,t,n,s){let o=n.shell_id,r=n.reason;if(!o||typeof o!="string"||o.trim().length===0)return[{type:"text",text:"Error: shell_id is required and must be a non-empty string"}];if(!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.`}];i.debug(`[MonitorRunningCliTool] Starting monitoring for ${o}`),i.debug(`[MonitorRunningCliTool] Reason: ${r}`);let a=Ga.startMonitoring(o,r);return a.success?(i.debug("[MonitorRunningCliTool] Monitoring started successfully"),[{type:"text",text:`Started monitoring background process ${o}.
340
335
 
341
336
  Reason: ${r}
342
337
 
343
338
  You will be auto-prompted when the process completes. You can continue with other tasks in the meantime.
344
339
 
345
- To check status manually, use BashOutput tool with shell_id: ${s}`}]):(i.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var bn,qs=D(()=>{"use strict";$();bn=class{toolNames=["grep","Grep"];async execute(e,t,n,o){let s=n.pattern,r=n.output_mode||"files_with_matches",a=n.path||process.cwd(),l=n.glob,u=n.type,d=n["-i"]===!0,p=n["-n"]===!0,m=n["-A"],h=n["-B"],f=n["-C"],y=n.multiline===!0,S=n.head_limit;if(!s)throw new Error("Missing pattern argument");if(s.trim().length===0)throw new Error("Pattern cannot be empty");i.debug(`[GrepTool] Grep search: pattern="${s}", path="${a}", output_mode="${r}"`);try{let{exec:b}=await import("child_process"),{promisify:w}=await import("util"),k=w(b),v="rg",x=!0;try{await k("which rg")}catch{i.debug("[GrepTool] ripgrep not found, falling back to grep"),v="grep -r",x=!1}if(x){switch(d&&(v+=" -i"),p&&(v+=" -n"),r){case"files_with_matches":v+=" -l";break;case"count":v+=" -c";break;case"content":default:break}f!==void 0?v+=` -C ${f}`:(m!==void 0&&(v+=` -A ${m}`),h!==void 0&&(v+=` -B ${h}`)),y&&(v+=" -U --multiline-dotall"),v+=` "${s.replace(/"/g,'\\"')}"`,l&&(v+=` --glob="${l}"`),u&&(v+=` --type=${u}`),v+=` "${a}"`}else{switch(d&&(v+=" -i"),p&&(v+=" -n"),r){case"files_with_matches":v+=" -l";break;case"count":v+=" -c";break}f!==void 0?v+=` -C ${f}`:(m!==void 0&&(v+=` -A ${m}`),h!==void 0&&(v+=` -B ${h}`)),v+=` "${s.replace(/"/g,'\\"')}"`,l&&(v+=` --include="${l}"`),v+=` "${a}"`}S!==void 0&&S>0&&(v+=` | head -n ${S}`),i.debug(`[GrepTool] Executing: ${v}`);let{stdout:P,stderr:A}=await k(v,{maxBuffer:10*1024*1024});if(!P&&!A)return[{type:"text",text:"No matches found"}];let B=P||A;if(r==="content"&&B){let N=`
340
+ To check status manually, use BashOutput tool with shell_id: ${o}`}]):(i.debug(`[MonitorRunningCliTool] Failed to start monitoring: ${a.error}`),[{type:"text",text:`Failed to start monitoring: ${a.error}`}])}}});var wn,tr=D(()=>{"use strict";L();wn=class{toolNames=["grep","Grep"];async execute(e,t,n,s){let o=n.pattern,r=n.output_mode||"files_with_matches",a=n.path||process.cwd(),l=n.glob,u=n.type,d=n["-i"]===!0,p=n["-n"]===!0,m=n["-A"],g=n["-B"],h=n["-C"],y=n.multiline===!0,T=n.head_limit;if(!o)throw new Error("Missing pattern argument");if(o.trim().length===0)throw new Error("Pattern cannot be empty");i.debug(`[GrepTool] Grep search: pattern="${o}", path="${a}", output_mode="${r}"`);try{let{exec:S}=await import("child_process"),{promisify:w}=await import("util"),E=w(S),b="rg",C=!0;try{await E("which rg")}catch{i.debug("[GrepTool] ripgrep not found, falling back to grep"),b="grep -r",C=!1}if(C){switch(d&&(b+=" -i"),p&&(b+=" -n"),r){case"files_with_matches":b+=" -l";break;case"count":b+=" -c";break;case"content":default:break}h!==void 0?b+=` -C ${h}`:(m!==void 0&&(b+=` -A ${m}`),g!==void 0&&(b+=` -B ${g}`)),y&&(b+=" -U --multiline-dotall"),b+=` "${o.replace(/"/g,'\\"')}"`,l&&(b+=` --glob="${l}"`),u&&(b+=` --type=${u}`),b+=` "${a}"`}else{switch(d&&(b+=" -i"),p&&(b+=" -n"),r){case"files_with_matches":b+=" -l";break;case"count":b+=" -c";break}h!==void 0?b+=` -C ${h}`:(m!==void 0&&(b+=` -A ${m}`),g!==void 0&&(b+=` -B ${g}`)),b+=` "${o.replace(/"/g,'\\"')}"`,l&&(b+=` --include="${l}"`),b+=` "${a}"`}T!==void 0&&T>0&&(b+=` | head -n ${T}`),i.debug(`[GrepTool] Executing: ${b}`);let{stdout:P,stderr:R}=await E(b,{maxBuffer:10*1024*1024});if(!P&&!R)return[{type:"text",text:"No matches found"}];let O=P||R;if(r==="content"&&O){let q=`
346
341
 
347
- [Found ${B.trim().split(`
348
- `).length} matching line(s)]`;return[{type:"text",text:B+N}]}return[{type:"text",text:B}]}catch(b){return b.code===1?[{type:"text",text:"No matches found"}]:(i.debug(`[GrepTool] Grep failed: ${b.message}`),b.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 Tn,zs=D(()=>{"use strict";$();Tn=class{toolNames=["glob","Glob"];async execute(e,t,n,o){let s=n.pattern,r=n.path||process.cwd();if(!s)throw new Error("Missing pattern argument");i.debug(`[GlobTool] Glob search: pattern="${s}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),d=s.replace(/\*\*/g,"*"),p=process.platform==="win32"?`dir /s /b "${r}\\${d}"`:`find "${r}" -name "${d}" 2>/dev/null`,{stdout:m}=await u(p);if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let h=m.trim().split(`
349
- `);return[{type:"text",text:`Found ${h.length} file(s):
350
- ${h.join(`
351
- `)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var yn,Xs=D(()=>{"use strict";$();yn=class{toolNames=["open_url"];async execute(e,t,n,o){let s=n.url;if(!s)throw new Error("Missing url argument");i.debug(`[OpenUrlTool] Opening URL: ${s}`),o.activeWebViewURLs.includes(s)||(o.activeWebViewURLs.push(s),i.debug(`[OpenUrlTool] Added to active URLs: ${s}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${s}"`,l=>{l?i.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):i.debug(`[OpenUrlTool] URL opened in default browser: ${s}`)}),[{type:"text",text:`✅ URL opened in default browser: ${s}`}]}catch(r){return i.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});import{exec as Ma,execSync as Dp}from"child_process";import{promisify as Oa}from"util";function Tt(){return process.platform==="win32"}function Sn(){return process.platform==="darwin"}function wn(){return process.platform==="linux"}function To(){return Tt()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var Rp,js=D(()=>{"use strict";Rp=Oa(Ma)});import*as U from"fs";import*as te from"path";import*as W from"os";import{exec as Vs}from"child_process";import{promisify as Fa}from"util";var Cn,yo,ge,Ks=D(()=>{"use strict";js();Cn=Fa(Vs),yo=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 te.join(W.homedir(),".orion")}getKnowledgeFilePath(){return te.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!U.existsSync(this.orionDirectory))try{U.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),Tt()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{Vs(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return U.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return U.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),U.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
342
+ [Found ${O.trim().split(`
343
+ `).length} matching line(s)]`;return[{type:"text",text:O+q}]}return[{type:"text",text:O}]}catch(S){return S.code===1?[{type:"text",text:"No matches found"}]:(i.debug(`[GrepTool] Grep failed: ${S.message}`),S.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 Cn,nr=D(()=>{"use strict";L();Cn=class{toolNames=["glob","Glob"];async execute(e,t,n,s){let o=n.pattern,r=n.path||process.cwd();if(!o)throw new Error("Missing pattern argument");i.debug(`[GlobTool] Glob search: pattern="${o}", path="${r}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),d=o.replace(/\*\*/g,"*"),p=process.platform==="win32"?`dir /s /b "${r}\\${d}"`:`find "${r}" -name "${d}" 2>/dev/null`,{stdout:m}=await u(p);if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let g=m.trim().split(`
344
+ `);return[{type:"text",text:`Found ${g.length} file(s):
345
+ ${g.join(`
346
+ `)}`}]}catch(a){return i.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var xn,or=D(()=>{"use strict";L();xn=class{toolNames=["open_url"];async execute(e,t,n,s){let o=n.url;if(!o)throw new Error("Missing url argument");i.debug(`[OpenUrlTool] Opening URL: ${o}`),s.activeWebViewURLs.includes(o)||(s.activeWebViewURLs.push(o),i.debug(`[OpenUrlTool] Added to active URLs: ${o}`));try{let{exec:r}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return r(`${a} "${o}"`,l=>{l?i.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):i.debug(`[OpenUrlTool] URL opened in default browser: ${o}`)}),[{type:"text",text:`✅ URL opened in default browser: ${o}`}]}catch(r){return i.debug(`[OpenUrlTool] Failed to open URL: ${r.message}`),[{type:"text",text:`❌ Failed to open URL: ${r.message}`}]}}}});import{exec as qa,execSync as zp}from"child_process";import{promisify as za}from"util";function St(){return process.platform==="win32"}function En(){return process.platform==="darwin"}function kn(){return process.platform==="linux"}function Po(){return St()?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash"}var Xp,sr=D(()=>{"use strict";Xp=za(qa)});import*as W from"fs";import*as ne from"path";import*as G from"os";import{exec as rr}from"child_process";import{promisify as ja}from"util";var In,Ao,ge,ir=D(()=>{"use strict";sr();In=ja(rr),Ao=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(G.homedir(),".orion")}getKnowledgeFilePath(){return ne.join(this.orionDirectory,this.fileName)}ensureDirectoryExists(){if(!W.existsSync(this.orionDirectory))try{W.mkdirSync(this.orionDirectory,{recursive:!0}),console.log(`Created .orion directory: ${this.orionDirectory}`),St()&&this.hideDirectoryOnWindows()}catch(e){console.error("Failed to create .orion directory:",e)}}hideDirectoryOnWindows(){try{rr(`attrib +h "${this.orionDirectory}"`,e=>{e?console.warn("Failed to hide .orion directory on Windows:",e.message):console.log("Set hidden attribute on .orion directory (Windows)")})}catch(e){console.warn("Error hiding directory on Windows:",e)}}hasDeviceKnowledge(){return W.existsSync(this.getKnowledgeFilePath())}readDeviceKnowledge(){try{return W.readFileSync(this.getKnowledgeFilePath(),"utf8")}catch(e){return e.code!=="ENOENT"&&console.error("Error reading device knowledge:",e),null}}writeDeviceKnowledge(e){try{return this.ensureDirectoryExists(),W.writeFileSync(this.getKnowledgeFilePath(),e,"utf8"),!0}catch(t){return console.error("Error writing device knowledge:",t),!1}}appendDeviceKnowledge(e){let n=(this.readDeviceKnowledge()||"")+`
352
347
 
353
- `+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return U.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
348
+ `+e;return this.writeDeviceKnowledge(n)}getKnowledgeFileSize(){try{return W.statSync(this.getKnowledgeFilePath()).size}catch{return 0}}async initializeDeviceKnowledge(){let e=`# Orion Device Knowledge
354
349
 
355
350
  `;e+=`**File Location**: \`${this.getKnowledgeFilePath()}\`
356
351
 
357
352
  `,e+=`## System Information
358
- `,e+=`- **OS**: ${W.type()} ${W.release()}
359
- `,e+=`- **Platform**: ${W.platform()}
360
- `,e+=`- **Hostname**: ${W.hostname()}
361
- `,e+=`- **Architecture**: ${W.arch()}
362
- `,e+=`- **CPU Cores**: ${W.cpus().length}
363
- `,e+=`- **Memory**: ${this.formatBytes(W.totalmem())}
364
- `,e+=`- **Username**: ${W.userInfo().username}
365
- `,e+=`- **Home Directory**: ${W.homedir()}
366
-
367
- `;let t=To();e+=`## Shell Environment
353
+ `,e+=`- **OS**: ${G.type()} ${G.release()}
354
+ `,e+=`- **Platform**: ${G.platform()}
355
+ `,e+=`- **Hostname**: ${G.hostname()}
356
+ `,e+=`- **Architecture**: ${G.arch()}
357
+ `,e+=`- **CPU Cores**: ${G.cpus().length}
358
+ `,e+=`- **Memory**: ${this.formatBytes(G.totalmem())}
359
+ `,e+=`- **Username**: ${G.userInfo().username}
360
+ `,e+=`- **Home Directory**: ${G.homedir()}
361
+
362
+ `;let t=Po();e+=`## Shell Environment
368
363
  `,e+=`- **Default Shell**: ${t}
369
364
  `,process.env.PATH&&(e+=`- **PATH**: ${process.env.PATH}
370
365
  `),e+=`
371
- `;let n=[{command:"python3 --version",name:"Python 3"},{command:"python --version",name:"Python"},{command:"node --version",name:"Node.js"},{command:"npm --version",name:"npm"},{command:"pnpm --version",name:"pnpm"},{command:"yarn --version",name:"Yarn"},{command:"brew --version",name:"Homebrew"},{command:"git --version",name:"Git"},{command:"docker --version",name:"Docker"},{command:"java -version",name:"Java"},{command:"ruby --version",name:"Ruby"},{command:"php --version",name:"PHP"},{command:"go version",name:"Go"},{command:"rustc --version",name:"Rust"},{command:"cargo --version",name:"Cargo"},{command:"apt --version",name:"APT"},{command:"snap --version",name:"Snap"},{command:"flatpak --version",name:"Flatpak"},{command:"dnf --version",name:"DNF"},{command:"yum --version",name:"YUM"},{command:"pacman --version",name:"Pacman"},{command:"kubectl version --client",name:"kubectl"},{command:"podman --version",name:"Podman"},{command:"vagrant --version",name:"Vagrant"}],o=[];for(let u of n){let d=await this.getCommandVersion(u.command);d&&o.push(`- **${u.name}**: ${d}`)}o.length>0&&(e+=`## Development Tools
372
- `,e+=o.join(`
366
+ `;let n=[{command:"python3 --version",name:"Python 3"},{command:"python --version",name:"Python"},{command:"node --version",name:"Node.js"},{command:"npm --version",name:"npm"},{command:"pnpm --version",name:"pnpm"},{command:"yarn --version",name:"Yarn"},{command:"brew --version",name:"Homebrew"},{command:"git --version",name:"Git"},{command:"docker --version",name:"Docker"},{command:"java -version",name:"Java"},{command:"ruby --version",name:"Ruby"},{command:"php --version",name:"PHP"},{command:"go version",name:"Go"},{command:"rustc --version",name:"Rust"},{command:"cargo --version",name:"Cargo"},{command:"apt --version",name:"APT"},{command:"snap --version",name:"Snap"},{command:"flatpak --version",name:"Flatpak"},{command:"dnf --version",name:"DNF"},{command:"yum --version",name:"YUM"},{command:"pacman --version",name:"Pacman"},{command:"kubectl version --client",name:"kubectl"},{command:"podman --version",name:"Podman"},{command:"vagrant --version",name:"Vagrant"}],s=[];for(let u of n){let d=await this.getCommandVersion(u.command);d&&s.push(`- **${u.name}**: ${d}`)}s.length>0&&(e+=`## Development Tools
367
+ `,e+=s.join(`
373
368
  `),e+=`
374
369
 
375
- `);let s=[];if(Sn()){let u=["/Applications/Xcode.app","/Applications/Visual Studio Code.app","/Applications/Sublime Text.app","/Applications/Atom.app","/Applications/IntelliJ IDEA.app","/Applications/PyCharm.app","/Applications/Android Studio.app","/Applications/Docker.app","/Applications/Postman.app","/Applications/Terminal.app","/Applications/iTerm.app"];for(let d of u)if(U.existsSync(d)){let p=te.basename(d,".app");s.push(`- ${p}`)}}else if(Tt()){let u=["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe","C:\\Program Files\\Microsoft VS Code\\Code.exe","C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe",te.join(process.env.LOCALAPPDATA||"","Programs\\Microsoft VS Code\\Code.exe"),"C:\\Program Files\\Sublime Text\\sublime_text.exe","C:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition","C:\\Program Files\\JetBrains\\PyCharm Community Edition","C:\\Program Files\\Android\\Android Studio","C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe","C:\\Program Files\\Postman\\Postman.exe",te.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let d of u)if(U.existsSync(d)){let p=te.basename(d).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");s.push(`- ${p}`)}}else if(wn()){let u=[{path:"/snap/bin/code",name:"VS Code (snap)"},{path:"/snap/bin/sublime-text",name:"Sublime Text (snap)"},{path:"/snap/bin/postman",name:"Postman (snap)"},{path:"/snap/bin/intellij-idea-community",name:"IntelliJ IDEA (snap)"},{path:"/snap/bin/pycharm-community",name:"PyCharm (snap)"},{path:"/usr/bin/code",name:"VS Code"},{path:"/usr/share/code/code",name:"VS Code"},{path:"/opt/visual-studio-code/code",name:"VS Code"},{path:"/usr/bin/sublime_text",name:"Sublime Text"},{path:"/opt/sublime_text/sublime_text",name:"Sublime Text"},{path:"/usr/bin/docker",name:"Docker"},{path:"/usr/bin/vim",name:"Vim"},{path:"/usr/bin/nvim",name:"Neovim"},{path:"/usr/bin/emacs",name:"Emacs"},{path:"/usr/bin/nano",name:"Nano"},{path:te.join(W.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let m of u)U.existsSync(m.path)&&s.push(`- ${m.name}`);let d=["/usr/share/applications",te.join(W.homedir(),".local/share/applications")],p=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let m of d)if(U.existsSync(m))try{let h=U.readdirSync(m);for(let f of h){let y=f.toLowerCase();for(let S of p)y.includes(S)&&!s.some(b=>b.toLowerCase().includes(S))&&s.push(`- ${f.replace(".desktop","")}`)}}catch{}}s.length>0&&(e+=`## Installed Applications
376
- `,e+=s.join(`
370
+ `);let o=[];if(En()){let u=["/Applications/Xcode.app","/Applications/Visual Studio Code.app","/Applications/Sublime Text.app","/Applications/Atom.app","/Applications/IntelliJ IDEA.app","/Applications/PyCharm.app","/Applications/Android Studio.app","/Applications/Docker.app","/Applications/Postman.app","/Applications/Terminal.app","/Applications/iTerm.app"];for(let d of u)if(W.existsSync(d)){let p=ne.basename(d,".app");o.push(`- ${p}`)}}else if(St()){let u=["C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe","C:\\Program Files\\Microsoft VS Code\\Code.exe","C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe",ne.join(process.env.LOCALAPPDATA||"","Programs\\Microsoft VS Code\\Code.exe"),"C:\\Program Files\\Sublime Text\\sublime_text.exe","C:\\Program Files\\JetBrains\\IntelliJ IDEA Community Edition","C:\\Program Files\\JetBrains\\PyCharm Community Edition","C:\\Program Files\\Android\\Android Studio","C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe","C:\\Program Files\\Postman\\Postman.exe",ne.join(process.env.LOCALAPPDATA||"","Postman\\Postman.exe")];for(let d of u)if(W.existsSync(d)){let p=ne.basename(d).replace(".exe","").replace(/^(.+?)( Community Edition)?$/,"$1");o.push(`- ${p}`)}}else if(kn()){let u=[{path:"/snap/bin/code",name:"VS Code (snap)"},{path:"/snap/bin/sublime-text",name:"Sublime Text (snap)"},{path:"/snap/bin/postman",name:"Postman (snap)"},{path:"/snap/bin/intellij-idea-community",name:"IntelliJ IDEA (snap)"},{path:"/snap/bin/pycharm-community",name:"PyCharm (snap)"},{path:"/usr/bin/code",name:"VS Code"},{path:"/usr/share/code/code",name:"VS Code"},{path:"/opt/visual-studio-code/code",name:"VS Code"},{path:"/usr/bin/sublime_text",name:"Sublime Text"},{path:"/opt/sublime_text/sublime_text",name:"Sublime Text"},{path:"/usr/bin/docker",name:"Docker"},{path:"/usr/bin/vim",name:"Vim"},{path:"/usr/bin/nvim",name:"Neovim"},{path:"/usr/bin/emacs",name:"Emacs"},{path:"/usr/bin/nano",name:"Nano"},{path:ne.join(G.homedir(),".local/share/JetBrains/Toolbox"),name:"JetBrains Toolbox"},{path:"/var/lib/flatpak",name:"Flatpak (installed)"}];for(let m of u)W.existsSync(m.path)&&o.push(`- ${m.name}`);let d=["/usr/share/applications",ne.join(G.homedir(),".local/share/applications")],p=["android-studio","jetbrains","postman","slack","discord","zoom"];for(let m of d)if(W.existsSync(m))try{let g=W.readdirSync(m);for(let h of g){let y=h.toLowerCase();for(let T of p)y.includes(T)&&!o.some(S=>S.toLowerCase().includes(T))&&o.push(`- ${h.replace(".desktop","")}`)}}catch{}}o.length>0&&(e+=`## Installed Applications
371
+ `,e+=o.join(`
377
372
  `),e+=`
378
373
 
379
374
  `),e+=`## Important Directories
380
- `,e+=`- **Home**: ${W.homedir()}
381
- `,e+=`- **Desktop**: ${te.join(W.homedir(),"Desktop")}
382
- `,e+=`- **Documents**: ${te.join(W.homedir(),"Documents")}
383
- `,e+=`- **Downloads**: ${te.join(W.homedir(),"Downloads")}
384
- `,Sn()?(e+=`- **Applications**: /Applications
375
+ `,e+=`- **Home**: ${G.homedir()}
376
+ `,e+=`- **Desktop**: ${ne.join(G.homedir(),"Desktop")}
377
+ `,e+=`- **Documents**: ${ne.join(G.homedir(),"Documents")}
378
+ `,e+=`- **Downloads**: ${ne.join(G.homedir(),"Downloads")}
379
+ `,En()?(e+=`- **Applications**: /Applications
385
380
  `,e+=`- **usr/local/bin**: /usr/local/bin
386
- `):Tt()?(e+=`- **Program Files**: C:\\Program Files
381
+ `):St()?(e+=`- **Program Files**: C:\\Program Files
387
382
  `,e+=`- **Program Files (x86)**: C:\\Program Files (x86)
388
- `,e+=`- **AppData**: ${te.join(W.homedir(),"AppData")}
389
- `,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||te.join(W.homedir(),"AppData","Local")}
390
- `):wn()&&(e+=`- **/usr/bin**: /usr/bin
383
+ `,e+=`- **AppData**: ${ne.join(G.homedir(),"AppData")}
384
+ `,e+=`- **Local AppData**: ${process.env.LOCALAPPDATA||ne.join(G.homedir(),"AppData","Local")}
385
+ `):kn()&&(e+=`- **/usr/bin**: /usr/bin
391
386
  `,e+=`- **/usr/local/bin**: /usr/local/bin
392
387
  `,e+=`- **/opt**: /opt
393
- `,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||te.join(W.homedir(),".config")}
394
- `,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||te.join(W.homedir(),".local/share")}
395
- `,U.existsSync("/snap")&&(e+=`- **Snap**: /snap
396
- `),U.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
388
+ `,e+=`- **Config**: ${process.env.XDG_CONFIG_HOME||ne.join(G.homedir(),".config")}
389
+ `,e+=`- **Local Data**: ${process.env.XDG_DATA_HOME||ne.join(G.homedir(),".local/share")}
390
+ `,W.existsSync("/snap")&&(e+=`- **Snap**: /snap
391
+ `),W.existsSync("/var/lib/flatpak")&&(e+=`- **Flatpak**: /var/lib/flatpak
397
392
  `)),e+=`
398
393
  `,e+=`## Network
399
- `,e+=`- **Hostname**: ${W.hostname()}
400
- `;let r=W.networkInterfaces(),a=Object.values(r).flat().find(u=>u&&!u.internal&&u.family==="IPv4");a&&(e+=`- **IP Address**: ${a.address}
394
+ `,e+=`- **Hostname**: ${G.hostname()}
395
+ `;let r=G.networkInterfaces(),a=Object.values(r).flat().find(u=>u&&!u.internal&&u.family==="IPv4");a&&(e+=`- **IP Address**: ${a.address}
401
396
  `),e+=`
402
397
  `;let l=await this.detectEnvironment();return l&&(e+=`## Environment
403
398
  `,e+=l,e+=`
@@ -405,42 +400,42 @@ ${h.join(`
405
400
  `,e+=`- **Redirect URLs**: Any shortened URL should be resolved to get the actual destination URL.
406
401
  `,e+=`- **File Downloads**: Always follow redirects to ensure proper file access and downloads.
407
402
 
408
- `,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let o=(this.readDeviceKnowledge()||"").split(`
409
- `),s=[],r=!1,a=!1;for(let u of o)u.startsWith(`## ${e}`)?(r=!0,a=!0,s.push(u),s.push(t)):u.startsWith("## ")&&r?(r=!1,s.push(u)):r||s.push(u);a||(s.push(""),s.push(`## ${e}`),s.push(t));let l=s.join(`
410
- `);return this.writeDeviceKnowledge(l)}addNote(e,t,n="Notes"){let o=new Date().toLocaleString(),s=`### ${e} (${o})
403
+ `,this.writeDeviceKnowledge(e)}updateKnowledgeSection(e,t){let s=(this.readDeviceKnowledge()||"").split(`
404
+ `),o=[],r=!1,a=!1;for(let u of s)u.startsWith(`## ${e}`)?(r=!0,a=!0,o.push(u),o.push(t)):u.startsWith("## ")&&r?(r=!1,o.push(u)):r||o.push(u);a||(o.push(""),o.push(`## ${e}`),o.push(t));let l=o.join(`
405
+ `);return this.writeDeviceKnowledge(l)}addNote(e,t,n="Notes"){let s=new Date().toLocaleString(),o=`### ${e} (${s})
411
406
  ${t}`,r=this.readDeviceKnowledge()||"";if(r.includes(`## ${n}`)){let a=r.split(`
412
- `),l=[],u=!1,d=!1;for(let m of a)m.startsWith(`## ${n}`)?(u=!0,l.push(m)):m.startsWith("## ")&&u&&!d?(l.push(""),l.push(s),l.push(""),l.push(m),u=!1,d=!0):l.push(m);u&&!d&&(l.push(""),l.push(s));let p=l.join(`
413
- `);return this.writeDeviceKnowledge(p)}else return this.updateKnowledgeSection(n,s)}deleteDeviceKnowledge(){try{return U.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return U.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=U.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(wn()){try{let{stdout:n}=await Cn("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),o=n.trim();o&&o!=="none"&&e.push(`- **Virtualization**: ${o}`)}catch{}if(U.existsSync("/proc/cpuinfo"))try{U.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(o=>o.includes("Virtualization"))||e.push("- **Virtualization**: VM detected (hypervisor flag)"))}catch{}let t=["/sys/class/dmi/id/product_name","/sys/class/dmi/id/sys_vendor","/sys/class/dmi/id/board_vendor"];for(let n of t)if(U.existsSync(n))try{let o=U.readFileSync(n,"utf8").trim().toLowerCase();if(o.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(o.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(o.includes("kvm")||o.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(o.includes("hyper-v")||o.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(o.includes("xen")){e.push("- **VM Type**: Xen");break}else if(o.includes("amazon")||o.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(o.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(o.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(U.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),U.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),U.existsSync("/proc/version"))try{let n=U.readFileSync("/proc/version","utf8");(n.toLowerCase().includes("microsoft")||n.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(U.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),U.existsSync("/etc/os-release"))try{let o=U.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);o&&e.push(`- **Distribution**: ${o[1]}`)}catch{}}else if(Sn())try{let{stdout:t}=await Cn('sysctl -n machdep.cpu.features 2>/dev/null || echo ""',{timeout:3e3});t.toLowerCase().includes("vmm")&&e.push("- **Environment**: Virtual Machine")}catch{}else if(Tt())try{let{stdout:t}=await Cn('systeminfo | findstr /i "System Model"',{timeout:5e3}),n=t.toLowerCase();(n.includes("virtual")||n.includes("vmware")||n.includes("virtualbox"))&&e.push(`- **Environment**: ${t.split(":")[1]?.trim()||"Virtual Machine"}`)}catch{}(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)&&e.push("- **Access**: SSH Session"),process.env.TMUX&&e.push("- **Terminal Multiplexer**: tmux"),process.env.STY&&e.push("- **Terminal Multiplexer**: screen")}catch{}return e.length>0?e.join(`
414
- `):null}async getCommandVersion(e){try{let t=To(),{stdout:n,stderr:o}=await Cn(e,{timeout:5e3,shell:t,windowsHide:!0});return(n+o).trim().split(`
415
- `)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}},ge=yo.shared()});var xn,Qs=D(()=>{"use strict";$();Ie();Ks();xn=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,o){let s=n.action,r=Date.now();i.debug(`[ManageDeviceKnowledgeTool] Executing action: ${s}`),F.start("ManageDeviceKnowledge",s);try{let a,l=!0;switch(s){case"read":{let d=ge.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await ge.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${ge.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let d=n.content;d?ge.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=n.content;d?ge.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=n.section,p=n.content;!d||!p?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):ge.updateKnowledgeSection(d,p)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,l=!1);break}case"add_note":{let d=n.title,p=n.content,m=n.category||"Notes";!d||!p?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):ge.addNote(d,p,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,l=!1);break}case"delete":{ge.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=ge.getKnowledgeFilePath();break}case"exists":{a=ge.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${ge.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?ge.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=n.source;d?ge.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: ${s}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-r;return F.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){i.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-r;return F.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var En,Js=D(()=>{"use strict";$();En=class{toolNames=["operator_status"];async execute(e,t,n,o){let s=n.taskId,r=n.status,a=n.message;return i.debug(`[OperatorStatusTool] Operator status - Task ${s}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var kn,Ys=D(()=>{"use strict";$();kn=class{toolNames=["provide_input"];async execute(e,t,n,o){let s=n.input;if(!s)throw new Error("Missing input argument");i.debug(`[ProvideInputTool] Delegating provide_input to backend: ${s.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>(mn(),fo))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:s})}},l=await r.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(r){return i.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});import{exec as _a}from"child_process";import{promisify as $a}from"util";import*as In from"fs/promises";import*as Zs from"path";import*as er from"os";var Ua,yt,So=D(()=>{"use strict";$();Ua=$a(_a),yt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=Zs.join(er.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;
407
+ `),l=[],u=!1,d=!1;for(let m of a)m.startsWith(`## ${n}`)?(u=!0,l.push(m)):m.startsWith("## ")&&u&&!d?(l.push(""),l.push(o),l.push(""),l.push(m),u=!1,d=!0):l.push(m);u&&!d&&(l.push(""),l.push(o));let p=l.join(`
408
+ `);return this.writeDeviceKnowledge(p)}else return this.updateKnowledgeSection(n,o)}deleteDeviceKnowledge(){try{return W.unlinkSync(this.getKnowledgeFilePath()),!0}catch(e){return console.error("Error deleting device knowledge:",e),!1}}exportDeviceKnowledge(e){try{let t=this.readDeviceKnowledge()||"";return W.writeFileSync(e,t,"utf8"),!0}catch(t){return console.error("Error exporting device knowledge:",t),!1}}importDeviceKnowledge(e){try{let t=W.readFileSync(e,"utf8");return this.writeDeviceKnowledge(t)}catch(t){return console.error("Error importing device knowledge:",t),!1}}async detectEnvironment(){let e=[];try{if(kn()){try{let{stdout:n}=await In("systemd-detect-virt 2>/dev/null || echo none",{timeout:3e3}),s=n.trim();s&&s!=="none"&&e.push(`- **Virtualization**: ${s}`)}catch{}if(W.existsSync("/proc/cpuinfo"))try{W.readFileSync("/proc/cpuinfo","utf8").includes("hypervisor")&&(e.some(s=>s.includes("Virtualization"))||e.push("- **Virtualization**: VM detected (hypervisor flag)"))}catch{}let t=["/sys/class/dmi/id/product_name","/sys/class/dmi/id/sys_vendor","/sys/class/dmi/id/board_vendor"];for(let n of t)if(W.existsSync(n))try{let s=W.readFileSync(n,"utf8").trim().toLowerCase();if(s.includes("virtualbox")){e.push("- **VM Type**: VirtualBox");break}else if(s.includes("vmware")){e.push("- **VM Type**: VMware");break}else if(s.includes("kvm")||s.includes("qemu")){e.push("- **VM Type**: KVM/QEMU");break}else if(s.includes("hyper-v")||s.includes("microsoft")){e.push("- **VM Type**: Hyper-V");break}else if(s.includes("xen")){e.push("- **VM Type**: Xen");break}else if(s.includes("amazon")||s.includes("aws")){e.push("- **VM Type**: AWS EC2");break}else if(s.includes("google")){e.push("- **VM Type**: Google Cloud");break}else if(s.includes("digitalocean")){e.push("- **VM Type**: DigitalOcean");break}}catch{}if(W.existsSync("/.dockerenv")&&e.push("- **Container**: Docker"),W.existsSync("/run/.containerenv")&&e.push("- **Container**: Podman"),process.env.KUBERNETES_SERVICE_HOST&&e.push("- **Container**: Kubernetes Pod"),W.existsSync("/proc/version"))try{let n=W.readFileSync("/proc/version","utf8");(n.toLowerCase().includes("microsoft")||n.toLowerCase().includes("wsl"))&&e.push("- **Environment**: Windows Subsystem for Linux (WSL)")}catch{}if(W.existsSync("/var/lib/cloud")&&e.push("- **Cloud Init**: Present (likely cloud VM)"),W.existsSync("/etc/os-release"))try{let s=W.readFileSync("/etc/os-release","utf8").match(/^PRETTY_NAME="?([^"\n]+)"?/m);s&&e.push(`- **Distribution**: ${s[1]}`)}catch{}}else if(En())try{let{stdout:t}=await In('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 In('systeminfo | findstr /i "System Model"',{timeout:5e3}),n=t.toLowerCase();(n.includes("virtual")||n.includes("vmware")||n.includes("virtualbox"))&&e.push(`- **Environment**: ${t.split(":")[1]?.trim()||"Virtual Machine"}`)}catch{}(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)&&e.push("- **Access**: SSH Session"),process.env.TMUX&&e.push("- **Terminal Multiplexer**: tmux"),process.env.STY&&e.push("- **Terminal Multiplexer**: screen")}catch{}return e.length>0?e.join(`
409
+ `):null}async getCommandVersion(e){try{let t=Po(),{stdout:n,stderr:s}=await In(e,{timeout:5e3,shell:t,windowsHide:!0});return(n+s).trim().split(`
410
+ `)[0]||"Installed"}catch{return null}}formatBytes(e){let t=["Bytes","KB","MB","GB","TB"];if(e===0)return"0 Bytes";let n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]}},ge=Ao.shared()});var Pn,ar=D(()=>{"use strict";L();Pe();ir();Pn=class{toolNames=["manage_device_knowledge"];async execute(e,t,n,s){let o=n.action,r=Date.now();i.debug(`[ManageDeviceKnowledgeTool] Executing action: ${o}`),F.start("ManageDeviceKnowledge",o);try{let a,l=!0;switch(o){case"read":{let d=ge.readDeviceKnowledge();d?a=d:a='No device knowledge file found. Use action "initialize" to create one.';break}case"initialize":{await ge.initializeDeviceKnowledge()?a=`Device knowledge initialized successfully at: ${ge.getKnowledgeFilePath()}`:(a="Failed to initialize device knowledge.",l=!1);break}case"write":{let d=n.content;d?ge.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=n.content;d?ge.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=n.section,p=n.content;!d||!p?(a='Error: Missing "section" or "content" argument for update_section action.',l=!1):ge.updateKnowledgeSection(d,p)?a=`Section "${d}" updated successfully.`:(a=`Failed to update section "${d}".`,l=!1);break}case"add_note":{let d=n.title,p=n.content,m=n.category||"Notes";!d||!p?(a='Error: Missing "title" or "content" argument for add_note action.',l=!1):ge.addNote(d,p,m)?a=`Note "${d}" added to ${m} successfully.`:(a=`Failed to add note "${d}".`,l=!1);break}case"delete":{ge.deleteDeviceKnowledge()?a="Device knowledge deleted successfully.":(a="Failed to delete device knowledge.",l=!1);break}case"path":{a=ge.getKnowledgeFilePath();break}case"exists":{a=ge.hasDeviceKnowledge()?"Device knowledge file exists.":"Device knowledge file does not exist.";break}case"size":{a=`Device knowledge file size: ${ge.getKnowledgeFileSize()} bytes`;break}case"export":{let d=n.destination;d?ge.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=n.source;d?ge.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: ${o}. Valid actions: read, initialize, write, append, update_section, add_note, delete, path, exists, size, export, import`,l=!1}let u=Date.now()-r;return F.result({toolName:"ManageDeviceKnowledge",output:a.substring(0,200)+(a.length>200?"...":""),success:l,executionTime:u}),[{type:"text",text:a}]}catch(a){i.debug(`[ManageDeviceKnowledgeTool] Error: ${a.message}`);let l=`Error managing device knowledge: ${a.message}`,u=Date.now()-r;return F.result({toolName:"ManageDeviceKnowledge",output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}}});var An,cr=D(()=>{"use strict";L();An=class{toolNames=["operator_status"];async execute(e,t,n,s){let o=n.taskId,r=n.status,a=n.message;return i.debug(`[OperatorStatusTool] Operator status - Task ${o}: ${r} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var Dn,lr=D(()=>{"use strict";L();Dn=class{toolNames=["provide_input"];async execute(e,t,n,s){let o=n.input;if(!o)throw new Error("Missing input argument");i.debug(`[ProvideInputTool] Delegating provide_input to backend: ${o.substring(0,20)}...`);try{let r=(await Promise.resolve().then(()=>(vn(),Eo))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:o})}},l=await r.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(r){return i.debug(`[ProvideInputTool] Failed to delegate provide_input: ${r.message}`),[{type:"text",text:`Error: ${r.message}`}]}}}});import{exec as Xa}from"child_process";import{promisify as Va}from"util";import*as Nn from"fs/promises";import*as ur from"path";import*as dr from"os";var Ka,wt,Do=D(()=>{"use strict";L();Ka=Va(Xa),wt=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=ur.join(dr.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
411
  [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
417
412
  Start-Sleep -Milliseconds 100;
418
413
  $img = [System.Windows.Forms.Clipboard]::GetImage();
419
- $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return i.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await Ua(t);let n=await In.readFile(e),o=n.toString("base64");return await In.unlink(e).catch(()=>{}),i.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${o}`}catch(e){return i.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
414
+ $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return i.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await Ka(t);let n=await Nn.readFile(e),s=n.toString("base64");return await Nn.unlink(e).catch(()=>{}),i.debug(`[SCREENSHOT] Captured screenshot: ${n.length} bytes`),`data:image/jpeg;base64,${s}`}catch(e){return i.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
420
415
  ⚠️ 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
416
  `)):process.platform==="darwin"&&(console.log(`
422
417
  ⚠️ 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 Pn,tr=D(()=>{"use strict";$();So();Pn=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,o){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await yt.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return i.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(s){return i.error(`[TakeScreenshotTool] Failed to capture screenshot: ${s.message}`),[{type:"text",text:`Failed to capture screenshot: ${s.message}`}]}}}});function nr(c){c.register(new on),c.register(new rn),c.register(new an),c.register(new cn),c.register(new ln),c.register(new un),c.register(new dn),c.register(new gn),c.register(new hn),c.register(new fn),c.register(new vn),c.register(new bn),c.register(new Tn),c.register(new yn),c.register(new xn),c.register(new En),c.register(new kn),c.register(new Pn)}var or=D(()=>{"use strict";ks();Is();Ps();As();Ds();Ns();Rs();Ws();Bs();Hs();Gs();qs();zs();Xs();Qs();Js();Ys();tr()});var An,sr=D(()=>{"use strict";An=class{constructor(e,t,n,o,s){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=o;this.activeWebViewURLs=s}}});var vo={};Ee(vo,{FrontendWebSocketService:()=>Y});import{EventEmitter as La}from"events";import{io as Wa}from"socket.io-client";import Ba from"os";var Y,bt=D(()=>{"use strict";$();ze();ce();dt();mt();io();ws();or();sr();Y=class c extends La{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 ye;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=me.getInstance(),this.authService=H.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new en,nr(this.toolRegistry),i.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?i.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):i.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{i.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}hasElectronFrontend(){return this._hasElectronFrontend}setElectronFrontendAvailable(e){this._hasElectronFrontend=e,i.debug(`[FRONTEND WS] Electron frontend availability set to: ${e}`)}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return i.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return i.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(i.debug("[FRONTEND WS] connectForConversation called"),i.debug(`[FRONTEND WS] New sessionId: ${t}`),i.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),i.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t){let n=this.sessionId;this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0?(i.debug("[FRONTEND WS] Session ID changing but active work exists"),i.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),i.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),i.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(n)):(i.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 n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)i.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return i.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(i.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){i.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],i.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){i.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(i.debug("[FRONTEND WS] connect() called"),this.socket?.connected){i.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(i.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),i.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;i.debug(`[FRONTEND WS] Connecting to ${t}`),i.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),i.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),i.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Wa(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){i.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){i.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,i.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(i.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),i.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let o=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:s=>{clearTimeout(o),this.connectionPromise=null,t(s)},reject:s=>{clearTimeout(o),this.connectionPromise=null,n(s)},timeoutId:o}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{i.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{i.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{i.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,i.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{i.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{i.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{i.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{i.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{i.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{i.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{i.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{i.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{i.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{i.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=>{i.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{i.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("get_image_for_annotation",e=>{i.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(){i.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();i.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else i.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.flushPendingToolResults(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){i.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||i.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){i.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(i.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:i.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(i.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){i.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){i.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),i.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),i.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),i.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(i.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(i.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),i.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}handleCheckpointRequest(e){i.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,o=t.session_id,s=t.iteration;if(!n||!o||s===void 0){i.warn("[FRONTEND WS] Invalid checkpoint request format");return}i.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${o}, Iteration: ${s}`);let r=ke.getInstance(),a=r.getQueuedMessages(),l=a.map(d=>({content:d.content,timestamp:Math.floor(d.timestamp.getTime())})),u=l.length>0;i.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:o,has_feedback:u,feedback:l}),u&&(i.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){i.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){i.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}i.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),i.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(i.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),i.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){i.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){i.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){i.debug("[FRONTEND WS] Initiating forced reconnection...");let o=this.sessionId,s=this.userId,r=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(s,o)?(i.debug("[FRONTEND WS] Reconnection successful!"),i.debug(`[FRONTEND WS] Composite key: ${r}_${o}`)):i.error("[FRONTEND WS] Reconnection failed")}catch(a){i.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else i.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:n}=e;i.debug(`[FRONTEND WS] Sub-agent event: ${t}`,n);try{Ss.handleEvent({type:t,...n}),i.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(o){i.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${o}`)}this.emit("subAgentEvent",{type:t,...n,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:o=3e4}=e;i.debug(`[FRONTEND WS] Processing image for annotation: ${n}`);try{let s=await import("fs/promises"),r=await import("path");try{await s.access(n)}catch{i.error(`[FRONTEND WS] Image file not found: ${n}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Image file not found: ${n}`});return}let l=(await s.readFile(n)).toString("base64"),u=r.extname(n).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:n}),i.debug(`[FRONTEND WS] Image sent for annotation: ${n}`)}catch(s){i.error(`[FRONTEND WS] Failed to read image for annotation: ${s.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${s.message}`})}}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(i.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){i.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();i.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t){this.activeToolCount++;let n=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),i.debug("[FRONTEND WS] === EXECUTING TOOL ==="),i.debug(`[FRONTEND WS] Tool name: ${e.name}`),i.debug(`[FRONTEND WS] Tool ID: ${e.id}`),i.debug(`[FRONTEND WS] Tool call ID: ${t}`),i.debug("[FRONTEND WS] Tool arguments:",JSON.stringify(e.arguments).substring(0,200)),this.emit("toolExecuting",{toolCallId:e.id,name:e.name,arguments:e.arguments,startTime:new Date}),i.debug(`[FRONTEND WS] Emitted toolExecuting for ${e.name}`);let o=new An(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let s=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,o);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:s.output,success:s.success,arguments:e.arguments});let r=typeof s=="string"?!0:s?.success??!0;await this.handleLargeResponse(e.id,t,e.name,s,r,e.arguments)}catch(s){i.error(`[FRONTEND WS] Tool execution failed: ${s.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:s.message,success:!1,error:s.message,arguments:e.arguments}),this.sendToolError(e.id,t,e.name,s)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let s=((Date.now()-n)/1e3).toFixed(2);i.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${s}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(i.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),i.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}i.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(n){i.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;i.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),i.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){i.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,n,o,s){let r;typeof o=="string"?r=o:o&&typeof o=="object"&&"output"in o?r=o.output||o.error||"":r=JSON.stringify(o);let a=this.createContentBlocks(r,s,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,o){let s=this.createContentBlocks(o.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:s,success:!0,error:null})}createContentBlocks(e,t,n){let o=e.trim();o.length===0&&(t?o=`Command '${n}' executed successfully.
418
+ `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}}});var Rn,pr=D(()=>{"use strict";L();Do();Rn=class{toolNames=["take_screenshot","take_current_screenshot"];async execute(e,t,n,s){i.debug("[TakeScreenshotTool] Capturing screenshot...");try{let r=await wt.getInstance().captureScreen();if(!r)throw new Error("Failed to capture screenshot - no image data returned");return i.debug("[TakeScreenshotTool] Screenshot captured successfully"),[{type:"image_url",image_url:{url:r}}]}catch(o){return i.error(`[TakeScreenshotTool] Failed to capture screenshot: ${o.message}`),[{type:"text",text:`Failed to capture screenshot: ${o.message}`}]}}}});function mr(c){c.register(new cn),c.register(new un),c.register(new dn),c.register(new pn),c.register(new mn),c.register(new gn),c.register(new hn),c.register(new bn),c.register(new Tn),c.register(new yn),c.register(new Sn),c.register(new wn),c.register(new Cn),c.register(new xn),c.register(new Pn),c.register(new An),c.register(new Dn),c.register(new Rn)}var gr=D(()=>{"use strict";$s();Us();Ls();Ws();Bs();Hs();Gs();Js();Ys();Zs();er();tr();nr();or();ar();cr();lr();pr()});var Mn,hr=D(()=>{"use strict";Mn=class{constructor(e,t,n,s,o){this.userId=e;this.sessionId=t;this.toolCallId=n;this.runningProcesses=s;this.activeWebViewURLs=o}}});var ko={};ke(ko,{FrontendWebSocketService:()=>Z});import{EventEmitter as Qa}from"events";import{io as Ja}from"socket.io-client";import Ya from"os";var Z,yt=D(()=>{"use strict";L();Xe();le();mt();ht();ho();Ms();gr();hr();Z=class c extends Qa{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 Se;wsConnectionStartTime=null;pendingDeleteConfirmations=new Map;DELETE_CONFIRMATION_TIMEOUT=5e4;_hasElectronFrontend=!1;onConnectionStateChangeCallbacks=new Set;connectionPromise=null;constructor(e="ws.snowx.ai",t,n="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=me.getInstance(),this.authService=z.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,n),this.toolRegistry=new sn,mr(this.toolRegistry),i.debug(`[FRONTEND WS] Tool registry initialized with ${this.toolRegistry.getToolCount()} frontend tools`),this.deviceId?i.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):i.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication"),process.on("beforeExit",()=>{i.debug("[FRONTEND WS] Process exiting - cleaning up resources"),this.forceCleanup()}),process.on("SIGINT",()=>{this.forceCleanup()}),process.on("SIGTERM",()=>{this.forceCleanup()})}static getInstance(){return c.instance||(c.instance=new c),c.instance}isConnected(){return this._connectionState==="connected"&&this.socket?.connected===!0}hasElectronFrontend(){return this._hasElectronFrontend}setElectronFrontendAvailable(e){this._hasElectronFrontend=e,i.debug(`[FRONTEND WS] Electron frontend availability set to: ${e}`)}isWebSocketConnected(){return this.isConnected()}getConnectionState(){return this._connectionState}isConversationInProgress(){return this.isConversationActive&&this.isConnected()}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected(),isConnecting:this._connectionState==="connecting",error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}get currentDeviceId(){return this.deviceId}onConnectionStateChange(e){return this.onConnectionStateChangeCallbacks.add(e),e(this._connectionState),()=>{this.onConnectionStateChangeCallbacks.delete(e)}}notifyConnectionStateChange(){for(let e of this.onConnectionStateChangeCallbacks)e(this._connectionState);this.emit("connectionStateChange",this._connectionState)}generateUniqueDeviceId(e,t="node"){if(e){let n=this.deviceRegistrationService.getCurrentDeviceId();if(n)return n}return i.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(!t)return i.error("[FRONTEND WS] No sessionId provided! Connection will fail."),!1;if(i.debug("[FRONTEND WS] connectForConversation called"),i.debug(`[FRONTEND WS] New sessionId: ${t}`),i.debug(`[FRONTEND WS] Old sessionId: ${this.sessionId}`),i.debug(`[FRONTEND WS] isConnected(): ${this.isConnected()}`),this.sessionId&&this.sessionId!==t){let n=this.sessionId;this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0?(i.debug("[FRONTEND WS] Session ID changing but active work exists"),i.debug(`[FRONTEND WS] Active tools: ${this.activeToolExecutions.size}`),i.debug(`[FRONTEND WS] Queued tools: ${this.toolExecutionQueue.length}`),i.debug(`[FRONTEND WS] Pending results: ${this.pendingToolResults.length}`),this.scheduleOldSessionCleanup(n)):(i.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 n=this.generateUniqueDeviceId(this.userId,"node");if(n&&this.deviceId!==n)i.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${n}`),this.deviceId=n;else if(!n)return i.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}return this.isConversationActive=!0,this.isConnected()?(i.debug("[FRONTEND WS] Already connected with same sessionId, reusing connection"),!0):(await this.connect(),await this.waitForConnection(3e4))}disconnectAfterConversation(){i.debug("[FRONTEND WS] Disconnecting after conversation (permanent)"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],i.debug("[FRONTEND WS] Cleared active WebView URLs"),(this.isConnected()||this.socket)&&this.disconnect("conversation_ended",!0)}handleConversationComplete(){i.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}async connect(){if(i.debug("[FRONTEND WS] connect() called"),this.socket?.connected){i.debug("[FRONTEND WS] Socket.IO already connected, skipping");return}this.socket&&(i.debug("[FRONTEND WS] Cleaning up old socket"),this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._connectionState="connecting",this.notifyConnectionStateChange(),i.debug("[FRONTEND WS] Creating Socket.IO connection...");try{let e="";try{e=await this.authService.getFirebaseIdToken()||""}catch(n){throw new Error(`Failed to get authentication token: ${n}`)}let t=`wss://${this.serverHost}`;i.debug(`[FRONTEND WS] Connecting to ${t}`),i.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),i.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),i.debug(`[FRONTEND WS] User ID: ${this.userId||"anonymous"}`),this.wsConnectionStartTime=new Date,this.socket=Ja(t,{path:"/frontend-tools",query:{deviceId:this.deviceId||"",sessionId:this.sessionId||"",token:e},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.1,timeout:45e3,autoConnect:!0,forceNew:!0}),this.setupSocketEventHandlers()}catch(e){i.error(`[FRONTEND WS] Connection error: ${e.message}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.rejectConnectionPromise(new Error(`Connection failed: ${e}`))}}disconnect(e="unknown",t=!1){i.debug(`[FRONTEND WS] DISCONNECT - Reason: ${e}, Permanent: ${t}`),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null,i.debug("[FRONTEND WS] Socket.IO disconnected")),this.connectionError=null,this._connectionState="disconnected",this.notifyConnectionStateChange(),t&&(this.isConversationActive=!1,this.reconnectAttempts=0,this.pendingToolResults.length>0&&(i.warn(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending tool results (permanent disconnect)`),this.pendingToolResults=[]),i.debug("[FRONTEND WS] Connection state FULLY reset (permanent disconnect)")),this.emit("disconnected")}async waitForConnection(e){return this.isConnected()?!0:new Promise((t,n)=>{let s=setTimeout(()=>{this.connectionPromise=null,n(new Error("WebSocket connection timeout"))},e);this.connectionPromise={resolve:o=>{clearTimeout(s),this.connectionPromise=null,t(o)},reject:o=>{clearTimeout(s),this.connectionPromise=null,n(o)},timeoutId:s}})}resolveConnectionPromise(e){this.connectionPromise&&this.connectionPromise.resolve(e)}rejectConnectionPromise(e){this.connectionPromise&&this.connectionPromise.reject(e)}setupSocketEventHandlers(){this.socket&&(this.socket.on("connect",()=>{i.debug("[FRONTEND WS] Socket.IO connected"),this.handleConnect()}),this.socket.on("disconnect",e=>{i.debug(`[FRONTEND WS] Socket.IO disconnected: ${e}`),this.handleDisconnect(e)}),this.socket.on("connect_error",e=>{i.error(`[FRONTEND WS] Socket.IO connect_error: ${e.message}`),this.connectionError=e.message,this.rejectConnectionPromise(e)}),this.socket.io.on("reconnect_attempt",e=>{this.reconnectAttempts=e,i.debug(`[FRONTEND WS] Reconnection attempt ${e}`),this._connectionState="reconnecting",this.notifyConnectionStateChange()}),this.socket.io.on("reconnect",e=>{i.debug(`[FRONTEND WS] Reconnected after ${e} attempts`),this.reconnectAttempts=0}),this.socket.io.on("reconnect_error",e=>{i.error(`[FRONTEND WS] Reconnection error: ${e.message}`)}),this.socket.io.on("reconnect_failed",()=>{i.error("[FRONTEND WS] All reconnection attempts failed"),this.connectionError="Connection failed after multiple attempts.",this._connectionState="disconnected",this.notifyConnectionStateChange()}),this.socket.on("connection_established",e=>{this.handleConnectionEstablished(e)}),this.socket.on("tool_execution_request",e=>{i.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e)}),this.socket.on("pong",e=>{i.debug("[FRONTEND WS] Pong received"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("heartbeat_ack",e=>{i.debug("[FRONTEND WS] Heartbeat acknowledged"),this.lastPongReceived=new Date,this.updateConnectionQuality()}),this.socket.on("tool_progress_ack",e=>{i.debug("[FRONTEND WS] Tool progress acknowledged")}),this.socket.on("long_operation_start",e=>{i.debug("[FRONTEND WS] Backend requested long operation mode"),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat()}),this.socket.on("stop_signal",e=>{this.handleStopSignal(e)}),this.socket.on("stop_all_tools",e=>{i.debug("[FRONTEND WS] Stop all tools request received"),this.handleStopAllTools(e)}),this.socket.on("stop_acknowledged",e=>{}),this.socket.on("shell_cleanup",e=>{i.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=>{i.debug(`[FRONTEND WS] Reconnection requested by server: ${e.reason||"unknown"}`),this.handleReconnectionRequest(e)}),this.socket.on("sub_agent_event",e=>{i.debug(`[FRONTEND WS] Sub-agent event received: ${e.type}`),this.handleSubAgentEvent(e)}),this.socket.on("get_image_for_annotation",e=>{i.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(){i.debug("[FRONTEND WS] TCP connection opened"),this.connectionError=null,this.reconnectAttempts=0,this.startHeartbeat(),this.startKeepaliveWatchdog(),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Restarting aggressive heartbeat - ${this.activeToolExecutions.size} tools still active`),this.startAggressiveHeartbeat())}handleConnectionEstablished(e){if(this.wsConnectionStartTime){let t=Date.now()-this.wsConnectionStartTime.getTime();i.debug(`[FRONTEND WS] Connection established in ${t.toFixed(2)}ms!`)}else i.debug("[FRONTEND WS] Connection established!");this.registerDevice(),this._connectionState="connected",this.notifyConnectionStateChange(),this.isConversationActive=!0,this.flushPendingToolResults(),this.resolveConnectionPromise(!0),this.emit("connected")}handleDisconnect(e){i.debug(`[FRONTEND WS] Handling disconnect: ${e}`),this._connectionState="disconnected",this.notifyConnectionStateChange(),this.stopHeartbeat(),this.stopAggressiveHeartbeat(),this.stopKeepaliveWatchdog(),this.rejectConnectionPromise(new Error(`WebSocket disconnected: ${e}`)),this.isConversationActive||i.debug("[FRONTEND WS] Conversation not active, not reconnecting")}handleStopSignal(e){i.debug("[FRONTEND WS] Processing stop signal...");let t=e.data||e,n=t?.type||t?.stop_type||"all";switch(i.debug(`[FRONTEND WS] Stop type: ${n}`),n){case"all":this.terminateAllRunningProcesses();break;case"tools":this.terminateAllRunningProcesses();break;default:i.debug(`[FRONTEND WS] Unknown stop type: ${n}`)}}handleStopAllTools(e){let t=e.session_id,n=e.reason||"backend_stop";if(i.debug(`[FRONTEND WS] Stopping all tools - Session: ${t}, Reason: ${n}`),t&&this.sessionId&&t!==this.sessionId){i.debug(`[FRONTEND WS] Ignoring stop_all_tools for different session (theirs: ${t}, ours: ${this.sessionId})`);return}this.stopAllActiveTools(n)}stopAllActiveTools(e){i.debug(`[FRONTEND WS] Stopping all active tools - Reason: ${e}`),i.debug(`[FRONTEND WS] - Active tools: ${this.activeToolExecutions.size}`),i.debug(`[FRONTEND WS] - Queued tools: ${this.toolExecutionQueue.length}`),i.debug(`[FRONTEND WS] - Pending results: ${this.pendingToolResults.length}`),this.toolExecutionQueue.length>0&&(i.debug(`[FRONTEND WS] Clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]),this.activeToolExecutions.size>0&&(i.debug(`[FRONTEND WS] Marking ${this.activeToolExecutions.size} active tools as cancelled`),this.activeToolExecutions.clear(),this.activeToolCount=0),this.pendingToolResults.length>0&&(i.debug(`[FRONTEND WS] Clearing ${this.pendingToolResults.length} pending results`),this.pendingToolResults=[]),this.stopAggressiveHeartbeat(),this.terminateAllRunningProcesses(),i.debug(`[FRONTEND WS] All tools stopped for reason: ${e}`)}handleCheckpointRequest(e){i.debug("[FRONTEND WS] Handling checkpoint request");let t=e.data||e,n=t.checkpoint_id,s=t.session_id,o=t.iteration;if(!n||!s||o===void 0){i.warn("[FRONTEND WS] Invalid checkpoint request format");return}i.debug(`[FRONTEND WS] Checkpoint request - ID: ${n}, Session: ${s}, Iteration: ${o}`);let r=Ie.getInstance(),a=r.getQueuedMessages(),l=a.map(d=>({content:d.content,timestamp:Math.floor(d.timestamp.getTime())})),u=l.length>0;i.debug(`[FRONTEND WS] Sending checkpoint response with ${l.length} feedback messages`),this.socket?.emit("checkpoint_response",{checkpoint_id:n,session_id:s,has_feedback:u,feedback:l}),u&&(i.info(`Sent ${l.length} feedback message(s) to AI`),this.emit("feedback:sent",a),r.clearQueue())}handleMessagesSaved(e){let t=e.conversationId,n=e.isNew;if(!t||n===void 0){console.error("[FRONTEND WS] Invalid messages_saved event format");return}this.emit("messagesSaved",{conversationId:t,isNew:n})}handleAutoPrompt(e){this.emit("autoPrompt",{taskId:e.taskId,prompt:e.prompt,mode:e.mode,source:e.source,triggerReason:e.triggerReason})}handleShellCleanup(e){i.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){i.info("[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring");return}i.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),i.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}async handleReconnectionRequest(e){let t=e.reason||"unknown",n=e.lastPingAge||0;if(i.debug(`[FRONTEND WS] Server requested reconnection - Reason: ${t}`),i.debug(`[FRONTEND WS] Connection was degraded (last ping: ${Math.round(n/1e3)}s ago)`),this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0){i.debug(`[FRONTEND WS] Deferring reconnection - ${this.activeToolExecutions.size} active, ${this.toolExecutionQueue.length} queued tools`),this.sendAggressiveHeartbeat();return}if(this.pendingToolResults.length>0){i.debug(`[FRONTEND WS] Deferring reconnection - ${this.pendingToolResults.length} pending results to send`),this.sendAggressiveHeartbeat();return}if(this.socket&&this.isConversationActive&&this.sessionId&&this.userId){i.debug("[FRONTEND WS] Initiating forced reconnection...");let s=this.sessionId,o=this.userId,r=this.deviceId;this.disconnect("reconnection_requested",!1),await new Promise(a=>setTimeout(a,500));try{await this.connectForConversation(o,s)?(i.debug("[FRONTEND WS] Reconnection successful!"),i.debug(`[FRONTEND WS] Composite key: ${r}_${s}`)):i.error("[FRONTEND WS] Reconnection failed")}catch(a){i.error(`[FRONTEND WS] Reconnection error: ${a}`)}}else i.debug("[FRONTEND WS] Cannot reconnect - missing session info or conversation not active")}handleSubAgentEvent(e){let{type:t,data:n}=e;i.debug(`[FRONTEND WS] Sub-agent event: ${t}`,n);try{Rs.handleEvent({type:t,...n}),i.debug("[FRONTEND WS] Sub-agent event forwarded to SubAgentManager")}catch(s){i.debug(`[FRONTEND WS] Failed to forward to SubAgentManager: ${s}`)}this.emit("subAgentEvent",{type:t,...n,timestamp:new Date().toISOString()})}async handleImageForAnnotationRequest(e){let{id:t,image_path:n,timeout:s=3e4}=e;i.debug(`[FRONTEND WS] Processing image for annotation: ${n}`);try{let o=await import("fs/promises"),r=await import("path");try{await o.access(n)}catch{i.error(`[FRONTEND WS] Image file not found: ${n}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Image file not found: ${n}`});return}let l=(await o.readFile(n)).toString("base64"),u=r.extname(n).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:n}),i.debug(`[FRONTEND WS] Image sent for annotation: ${n}`)}catch(o){i.error(`[FRONTEND WS] Failed to read image for annotation: ${o.message}`),this.socket?.emit("image_for_annotation_response",{id:t,success:!1,error:`Failed to read image: ${o.message}`})}}async handleToolExecutionRequest(e){let t={id:e.data?.id||"",name:e.data?.tool_name||"",arguments:e.data?.arguments||{},timestamp:e.metadata?.timestamp||new Date().toISOString()},n=e.metadata?.tool_call_id||t.id;this.toolExecutionQueue.length>=this.MAX_QUEUED_TOOLS&&(i.warn("[FRONTEND WS] Tool execution queue full, dropping oldest tool"),this.toolExecutionQueue.shift()),this.toolExecutionQueue.push(async()=>{await this.executeToolWithTracking(t,n)}),this.processNextTool()}processNextTool(){if(this.activeToolCount>=this.MAX_CONCURRENT_TOOLS){i.debug(`[FRONTEND WS] Max concurrent tools reached (${this.activeToolCount}/${this.MAX_CONCURRENT_TOOLS}), queuing...`);return}if(this.toolExecutionQueue.length===0)return;let e=this.toolExecutionQueue.shift();i.debug(`[FRONTEND WS] Starting tool (${this.activeToolCount+1}/${this.MAX_CONCURRENT_TOOLS} active)`),e()}async executeToolWithTracking(e,t){this.activeToolCount++;let n=Date.now();this.activeToolExecutions.add(e.id),this.aggressiveHeartbeatTimer===null&&this.startAggressiveHeartbeat(),i.debug("[FRONTEND WS] === EXECUTING TOOL ==="),i.debug(`[FRONTEND WS] Tool name: ${e.name}`),i.debug(`[FRONTEND WS] Tool ID: ${e.id}`),i.debug(`[FRONTEND WS] Tool call ID: ${t}`),i.debug("[FRONTEND WS] Tool arguments:",JSON.stringify(e.arguments).substring(0,200)),this.emit("toolExecuting",{toolCallId:e.id,name:e.name,arguments:e.arguments,startTime:new Date}),i.debug(`[FRONTEND WS] Emitted toolExecuting for ${e.name}`);let s=new Mn(this.userId,this.sessionId,t,this.runningProcesses,this.activeWebViewURLs);try{let o=await this.toolRegistry.executeTool(e.name,e.id,e.arguments,s);this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:o.output,success:o.success,arguments:e.arguments});let r=typeof o=="string"?!0:o?.success??!0;await this.handleLargeResponse(e.id,t,e.name,o,r,e.arguments)}catch(o){i.error(`[FRONTEND WS] Tool execution failed: ${o.message}`),this.emit("tool_completed",{toolName:e.name,toolId:e.id,result:o.message,success:!1,error:o.message,arguments:e.arguments}),this.sendToolError(e.id,t,e.name,o)}finally{this.activeToolCount--,this.activeToolExecutions.delete(e.id),this.activeToolExecutions.size===0&&this.stopAggressiveHeartbeat();let o=((Date.now()-n)/1e3).toFixed(2);i.debug(`[FRONTEND WS] Tool completed for ${e.id} (took ${o}s)`),this.processNextTool(),await this.captureFrontendToolResultForHistory(e.name,[],!0,void 0)}}sendMessage(e,t){if(!this.isConnected()){if(e==="tool_execution_response"){this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&(i.warn("[FRONTEND WS] Pending results queue full, dropping oldest"),this.pendingToolResults.shift()),i.debug("[FRONTEND WS] Queuing tool result for later delivery"),this.pendingToolResults.push({type:e,data:t});return}i.warn("[FRONTEND WS] Not connected, cannot send message");return}try{this.socket?.emit(e,t)}catch(n){i.error(`[FRONTEND WS] Failed to send message: ${n}`),e==="tool_execution_response"&&(this.pendingToolResults.length>=this.MAX_PENDING_RESULTS&&this.pendingToolResults.shift(),this.pendingToolResults.push({type:e,data:t}))}}flushPendingToolResults(){if(this.pendingToolResults.length===0)return;i.debug(`[FRONTEND WS] Flushing ${this.pendingToolResults.length} queued tool results`);let e=[...this.pendingToolResults];this.pendingToolResults=[];for(let t of e)try{this.socket?.connected?(this.socket.emit(t.type,t.data),i.debug(`[FRONTEND WS] Sent queued tool result: ${t.data?.id}`)):this.pendingToolResults.push(t)}catch(n){i.error(`[FRONTEND WS] Failed to send queued tool result: ${n}`),this.pendingToolResults.push(t)}}registerDevice(){if(!this.userId||!this.deviceId){console.warn("[FRONTEND WS] Cannot register device - missing userId or deviceId");return}let e=["bash","read","write","edit","grep","glob","upload_file","take_screenshot","open_url"];this.socket?.emit("device_registration",{deviceId:this.deviceId,userId:this.userId,deviceType:this.getDeviceType(),timestamp:new Date().toISOString(),supportedTools:e})}getDeviceType(){let e=process.platform;return e==="darwin"?"macOS":e==="win32"?"Windows":e==="linux"?"Linux":"Unknown"}async sendToolResult(e,t,n,s,o){let r;typeof s=="string"?r=s:s&&typeof s=="object"&&"output"in s?r=s.output||s.error||"":r=JSON.stringify(s);let a=this.createContentBlocks(r,o,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:a,success:!0,error:null})}sendToolError(e,t,n,s){let o=this.createContentBlocks(s.message,!1,n);this.sendMessage("tool_execution_response",{id:e,tool_call_id:t,tool_name:n,content:o,success:!0,error:null})}createContentBlocks(e,t,n){let s=e.trim();s.length===0&&(t?s=`Command '${n}' executed successfully.
424
419
 
425
- No output was produced, which may be expected for this operation.`:o=`Command '${n}' failed but no error message was provided.`);try{let s=JSON.parse(o);if(Array.isArray(s)){let r=[];for(let a of s)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:o}]}async handleLargeResponse(e,t,n,o,s,r){let a;if(typeof o=="string"?a=o:o&&typeof o=="object"&&"output"in o?a=o.output||o.error||"":a=JSON.stringify(o),n==="take_screenshot"||n==="take_current_screenshot"){await this.sendToolResult(e,t,n,o,s);return}if(["read","read_special_file","read_file","readspecialfile"].includes(n.toLowerCase())&&o?.metadata?.isImage===!0){i.debug(`[FRONTEND WS] Image file detected from ${n} tool, bypassing token limit`),await this.sendToolResult(e,t,n,o,s);return}if(this.tokenCounter.exceedsResponseLimit(a)){let u=this.tokenCounter.count(a);if(i.debug(`[FRONTEND WS] Response too large (${u} tokens), creating temp file`),n.toLowerCase()==="read"&&r?.file_path){let h=r.file_path,f=this.tokenCounter.formatLargeFileMessage(a,h);await this.sendToolResult(e,t,n,f,s);return}let p=await this.createTempFile(a,n);if(!p){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.tokenCounter.truncateOutput(a),s);return}let m=this.tokenCounter.formatLargeResponsePreview(a,p);await this.sendToolResult(e,t,n,m,s)}else await this.sendToolResult(e,t,n,a,s)}async createTempFile(e,t){try{let n=await import("fs/promises"),o=await import("path"),s=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${s}_${r}.txt`,l=Ba.homedir(),u=o.join(l,".orion","tool_outputs");await n.mkdir(u,{recursive:!0});let d=o.join(u,a);return await n.writeFile(d,e,"utf-8"),i.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(n){return i.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),i.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},this.baseAggressiveHeartbeatInterval),i.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),i.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}sendAggressiveHeartbeat(){this.lastHeartbeatSent=new Date,this.socket?.connected&&(this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size}),i.debug(`[FRONTEND WS] Sent aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)),this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3;e<10?this.connectionQuality="excellent":e<30?this.connectionQuality="good":e<60?this.connectionQuality="fair":this.connectionQuality="poor"}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),i.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),i.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});i.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}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();i.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(i.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),i.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){i.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(i.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}terminateAllRunningProcesses(){i.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),i.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){i.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){i.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){i.debug("[FRONTEND WS] Not connected, cannot register session");return}i.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw i.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};i.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return i.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let n=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return i.debug(`[FRONTEND WS] Requesting delete confirmation: ${n}`),i.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(o=>{let s=setTimeout(()=>{this.pendingDeleteConfirmations.get(n)&&(i.debug(`[FRONTEND WS] Delete confirmation timed out: ${n}`),this.pendingDeleteConfirmations.delete(n),o("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(n,{resolve:o,timeoutId:s}),this.socket?.emit("delete_confirmation_request",{confirmationId:n,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Delete confirmation request sent: ${n}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:n}=e;i.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${n}`);let o=this.pendingDeleteConfirmations.get(t);if(!o){i.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(o.timeoutId),this.pendingDeleteConfirmations.delete(t);let s=n;o.resolve(["confirmed","declined","timeout","error"].includes(n)?s:"error")}async captureFrontendToolResultForHistory(e,t,n,o){let s=t.map(r=>r.text||"").join(`
426
- `);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(Pe(),nt)),a=r.getInstance(),l=o?`Error: ${o}`:s;a.captureFrontendToolResult(e,l,n),i.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){i.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}scheduleOldSessionCleanup(e){let o=Date.now(),s=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){i.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-o>6e4){i.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(i.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(s,2e3)};i.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(s,2e3)}forceCleanup(){if(i.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null),this.socket){try{this.socket.disconnect()}catch{}this.socket=null}i.debug("[FRONTEND WS] Force cleanup complete")}destroy(){i.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var je,rr=D(()=>{"use strict";je=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 n=Math.floor(t/2);return`${t}:${e.charCodeAt(0)}:${e.charCodeAt(n)}:${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 n=this.quickHash(e),o=this.cache.get(n);if(o!==void 0)return this.lastInput=e,this.lastOutput=o,o;let s=e;if(e.includes("<context>")&&(s=s.replace(this.contextRegex,"")),e.includes("<agent_system_reminder>")&&(s=s.replace(this.agentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(s=s.replace(this.systemReminderRegex,"")),s=s.replace(this.multipleNewlinesRegex,`
420
+ No output was produced, which may be expected for this operation.`:s=`Command '${n}' failed but no error message was provided.`);try{let o=JSON.parse(s);if(Array.isArray(o)){let r=[];for(let a of o)a&&typeof a=="object"&&a.type&&(a.type==="text"&&typeof a.text=="string"?r.push({type:"text",text:a.text}):a.type==="image_url"&&a.image_url?.url&&r.push({type:"image_url",image_url:{url:String(a.image_url.url)}}));if(r.length>0)return r}}catch{}return[{type:"text",text:s}]}async handleLargeResponse(e,t,n,s,o,r){let a;if(typeof s=="string"?a=s:s&&typeof s=="object"&&"output"in s?a=s.output||s.error||"":a=JSON.stringify(s),n==="take_screenshot"||n==="take_current_screenshot"){await this.sendToolResult(e,t,n,s,o);return}if(["read","read_special_file","read_file","readspecialfile"].includes(n.toLowerCase())&&s?.metadata?.isImage===!0){i.debug(`[FRONTEND WS] Image file detected from ${n} tool, bypassing token limit`),await this.sendToolResult(e,t,n,s,o);return}if(this.tokenCounter.exceedsResponseLimit(a)){let u=this.tokenCounter.count(a);if(i.debug(`[FRONTEND WS] Response too large (${u} tokens), creating temp file`),n.toLowerCase()==="read"&&r?.file_path){let g=r.file_path,h=this.tokenCounter.formatLargeFileMessage(a,g);await this.sendToolResult(e,t,n,h,o);return}let p=await this.createTempFile(a,n);if(!p){i.error("[FRONTEND WS] Failed to create temp file, using truncated response"),await this.sendToolResult(e,t,n,this.tokenCounter.truncateOutput(a),o);return}let m=this.tokenCounter.formatLargeResponsePreview(a,p);await this.sendToolResult(e,t,n,m,o)}else await this.sendToolResult(e,t,n,a,o)}async createTempFile(e,t){try{let n=await import("fs/promises"),s=await import("path"),o=Math.floor(Date.now()/1e3),r=Math.random().toString(36).substring(2,10),a=`${t}_${o}_${r}.txt`,l=Ya.homedir(),u=s.join(l,".orion","tool_outputs");await n.mkdir(u,{recursive:!0});let d=s.join(u,a);return await n.writeFile(d,e,"utf-8"),i.debug(`[FRONTEND WS] Created temp file: ${d}`),d}catch(n){return i.error(`[FRONTEND WS] Failed to create temp file: ${n}`),null}}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeatPing()},this.baseHeartbeatInterval),i.debug(`[FRONTEND WS] Started heartbeat (${this.baseHeartbeatInterval/1e3}s interval)`)}sendHeartbeatPing(){this.socket?.connected&&(this.socket.emit("ping",{timestamp:new Date().toISOString()}),this.lastHeartbeat=new Date)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}startAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=setInterval(()=>{this.sendAggressiveHeartbeat()},this.baseAggressiveHeartbeatInterval),i.debug(`[FRONTEND WS] Started aggressive heartbeat (${this.baseAggressiveHeartbeatInterval/1e3}s interval)`),this.startToolProgressReporting()}stopAggressiveHeartbeat(){this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),i.debug("[FRONTEND WS] Stopped aggressive heartbeat"),this.stopToolProgressReporting()}sendAggressiveHeartbeat(){this.lastHeartbeatSent=new Date,this.socket?.connected&&(this.socket.emit("heartbeat",{timestamp:new Date().toISOString(),hasActiveTools:this.activeToolExecutions.size>0,activeToolCount:this.activeToolExecutions.size}),i.debug(`[FRONTEND WS] Sent aggressive heartbeat (${this.activeToolExecutions.size} active tools)`)),this.updateConnectionQuality()}updateConnectionQuality(){let e=(Date.now()-this.lastPongReceived.getTime())/1e3;e<10?this.connectionQuality="excellent":e<30?this.connectionQuality="good":e<60?this.connectionQuality="fair":this.connectionQuality="poor"}startToolProgressReporting(){this.toolProgressTimer&&clearInterval(this.toolProgressTimer),this.toolProgressTimer=setInterval(()=>{this.sendToolProgress()},this.baseToolProgressInterval),i.debug(`[FRONTEND WS] Started tool progress reporting (${this.baseToolProgressInterval/1e3}s interval)`)}stopToolProgressReporting(){this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),i.debug("[FRONTEND WS] Stopped tool progress reporting")}sendToolProgress(){if(this.activeToolExecutions.size!==0&&this.socket?.connected){for(let e of this.activeToolExecutions)this.socket.emit("tool_progress",{toolId:e,status:"running",timestamp:new Date().toISOString()});i.debug(`[FRONTEND WS] Sent progress update for ${this.activeToolExecutions.size} active tools`)}}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();i.debug(`[FRONTEND WS] Keepalive check - ${Math.round(t/1e3)}s since last, timeout: ${e/1e3}s, active tools: ${this.activeToolExecutions.size}`),t>e&&(i.error(`[FRONTEND WS] KEEPALIVE TIMEOUT - No activity for ${Math.round(t/1e3)}s`),this.handleKeepaliveTimeout())},1e4),i.debug("[FRONTEND WS] Started keepalive watchdog (check every 10s)")}stopKeepaliveWatchdog(){this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null)}handleKeepaliveTimeout(){i.debug("[FRONTEND WS] Handling keepalive timeout"),this.emit("keepalive_timeout",{lastKeepaliveTime:this.lastKeepaliveTime,activeTools:this.activeToolExecutions.size}),this.activeToolExecutions.size>0&&(i.debug("[FRONTEND WS] Tools still active, not disconnecting"),this.sendAggressiveHeartbeat())}updateKeepalive(){this.lastKeepaliveTime=new Date}terminateAllRunningProcesses(){i.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),i.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(n){i.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${n.message}`)}this.runningProcesses.clear()}async sendStopSignal(e,t="all"){if(!this.isConnected()){i.warn("[FRONTEND WS] Not connected, cannot send stop signal");return}this.socket?.emit("stop_request",{user_id:e,stop_type:t,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async registerSession(e,t){if(!this.isConnected()){i.debug("[FRONTEND WS] Not connected, cannot register session");return}i.debug(`[FRONTEND WS] Registering session: ${e}`),this.socket?.emit("register",{traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Session registered: ${e}`)}async sendToolRequest(e){if(!this.isConnected())throw i.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};i.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),this.socket?.emit("tool_execution_request",t)}async requestDeleteConfirmation(e,t){if(!this.isConnected())return i.debug("[FRONTEND WS] Not connected, cannot request delete confirmation"),"error";let n=`delete-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return i.debug(`[FRONTEND WS] Requesting delete confirmation: ${n}`),i.debug(`[FRONTEND WS] Command: ${e.substring(0,100)}${e.length>100?"...":""}`),new Promise(s=>{let o=setTimeout(()=>{this.pendingDeleteConfirmations.get(n)&&(i.debug(`[FRONTEND WS] Delete confirmation timed out: ${n}`),this.pendingDeleteConfirmations.delete(n),s("timeout"))},this.DELETE_CONFIRMATION_TIMEOUT);this.pendingDeleteConfirmations.set(n,{resolve:s,timeoutId:o}),this.socket?.emit("delete_confirmation_request",{confirmationId:n,command:e,description:t,timeout:this.DELETE_CONFIRMATION_TIMEOUT,timestamp:new Date().toISOString()}),i.debug(`[FRONTEND WS] Delete confirmation request sent: ${n}`)})}handleDeleteConfirmationResponse(e){let{confirmationId:t,response:n}=e;i.debug(`[FRONTEND WS] Delete confirmation response received: ${t} = ${n}`);let s=this.pendingDeleteConfirmations.get(t);if(!s){i.debug(`[FRONTEND WS] No pending confirmation for: ${t}`);return}clearTimeout(s.timeoutId),this.pendingDeleteConfirmations.delete(t);let o=n;s.resolve(["confirmed","declined","timeout","error"].includes(n)?o:"error")}async captureFrontendToolResultForHistory(e,t,n,s){let o=t.map(r=>r.text||"").join(`
421
+ `);try{let{PersonalAgentService:r}=await Promise.resolve().then(()=>(Ae(),it)),a=r.getInstance(),l=s?`Error: ${s}`:o;a.captureFrontendToolResult(e,l,n),i.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}catch(r){i.debug(`[FRONTEND WS] Could not capture tool result: ${r}`)}}scheduleOldSessionCleanup(e){let s=Date.now(),o=()=>{if(!(this.activeToolExecutions.size>0||this.toolExecutionQueue.length>0||this.pendingToolResults.length>0)){i.debug(`[FRONTEND WS] Old session ${e} work completed, cleanup done`);return}if(Date.now()-s>6e4){i.debug(`[FRONTEND WS] Cleanup timeout exceeded for session ${e}, forcing clear`),this.toolExecutionQueue.length>0&&(i.debug(`[FRONTEND WS] Force clearing ${this.toolExecutionQueue.length} queued tools`),this.toolExecutionQueue=[]);return}setTimeout(o,2e3)};i.debug(`[FRONTEND WS] Scheduling cleanup for old session ${e}`),setTimeout(o,2e3)}forceCleanup(){if(i.debug("[FRONTEND WS] Force cleanup"),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.aggressiveHeartbeatTimer&&(clearInterval(this.aggressiveHeartbeatTimer),this.aggressiveHeartbeatTimer=null),this.toolProgressTimer&&(clearInterval(this.toolProgressTimer),this.toolProgressTimer=null),this.keepaliveWatchdog&&(clearInterval(this.keepaliveWatchdog),this.keepaliveWatchdog=null),this.socket){try{this.socket.disconnect()}catch{}this.socket=null}i.debug("[FRONTEND WS] Force cleanup complete")}destroy(){i.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.forceCleanup(),this.removeAllListeners()}}});var Ke,fr=D(()=>{"use strict";Ke=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 n=Math.floor(t/2);return`${t}:${e.charCodeAt(0)}:${e.charCodeAt(n)}:${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 n=this.quickHash(e),s=this.cache.get(n);if(s!==void 0)return this.lastInput=e,this.lastOutput=s,s;let o=e;if(e.includes("<context>")&&(o=o.replace(this.contextRegex,"")),e.includes("<agent_system_reminder>")&&(o=o.replace(this.agentSystemReminderRegex,"")),e.includes("<system-reminder>")&&(o=o.replace(this.systemReminderRegex,"")),o=o.replace(this.multipleNewlinesRegex,`
427
422
 
428
- `),s=s.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(n,s),this.lastInput=e,this.lastOutput=s,s}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Ha}from"events";import{promises as Dn}from"fs";import{join as ir}from"path";import{homedir as Ga}from"os";var wo,Nn,Co=D(()=>{"use strict";wo=class c extends Ha{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=ir(Ga(),".orion-cli"),this.configPath=ir(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 Dn.mkdir(this.configDir,{recursive:!0});try{let e=await Dn.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 Dn.mkdir(this.configDir,{recursive:!0}),await Dn.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()?"":`
423
+ `),o=o.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(n,o),this.lastInput=e,this.lastOutput=o,o}static hasContextBlocks(e){return e.includes("<context>")||e.includes("<agent_system_reminder>")||e.includes("<system-reminder>")}}});import{EventEmitter as Za}from"events";import{promises as _n}from"fs";import{join as vr}from"path";import{homedir as ec}from"os";var No,On,Ro=D(()=>{"use strict";No=class c extends Za{static instance;settings;configDir;configPath;constructor(){super(),this.configDir=vr(ec(),".orion-cli"),this.configPath=vr(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 _n.mkdir(this.configDir,{recursive:!0});try{let e=await _n.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 _n.mkdir(this.configDir,{recursive:!0}),await _n.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()?"":`
429
424
  --- User Instructions ---
430
425
  ${e.instructions}
431
426
  --- End Instructions ---
432
- `}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")}}},Nn=wo});var nt={};Ee(nt,{PersonalAgentService:()=>ue});import{EventEmitter as qa}from"events";import xo from"axios";import za from"http";import Xa from"https";import{v4 as Ve}from"uuid";import Ae from"fs";import Lt from"path";import St from"os";var Wt,ue,Pe=D(()=>{"use strict";He();ce();bt();dt();ze();$();rr();Co();Wt=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,o=e?.status||e?.statusCode||e?.response?.status,s=String(n||""),r=Number(o);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(s)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||r===401||r===403||s==="401"||s==="403"?"critical":"parsing"}},ue=class c extends qa{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;toolArgumentsCache=new Map;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;constructor(){super(),this.authService=H.getInstance(),this.httpAgent=new za.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Xa.Agent({keepAlive:!0,timeout:36e5}),i.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=Y.getInstance();e.on("toolExecuting",t=>{i.debug("[PERSONAL AGENT] Forwarding toolExecuting:",t.name,"args:",t.arguments?Object.keys(t.arguments):"none"),this.emit("toolExecuting",t)}),e.on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(i.warn("[PersonalAgent] No auth token available - user may not be authenticated"),"")}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform;if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"){try{let t=Ii("fs");if(t.existsSync("/etc/os-release")){let o=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(o)return o[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return Ae.existsSync(e)?t=Ae.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
427
+ `}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")}}},On=No});var it={};ke(it,{PersonalAgentService:()=>de});import{EventEmitter as tc}from"events";import Mo from"axios";import nc from"http";import oc from"https";import{v4 as Qe}from"uuid";import De from"fs";import Bt from"path";import Ct from"os";var Ht,de,Ae=D(()=>{"use strict";qe();le();yt();mt();Xe();L();fr();Ro();Ht=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",n=e?.code,s=e?.status||e?.statusCode||e?.response?.status,o=String(n||""),r=Number(s);return t.includes("json")||t.includes("parsing")||t.includes("decode")||t.includes("format")||t.includes("invalid response")||t.includes("malformed")||t.includes("serialization")||t.includes("unexpected token")?"parsing":["ECONNREFUSED","ENOTFOUND","ETIMEDOUT","ECONNRESET","ERR_NETWORK","EPIPE","EHOSTUNREACH"].includes(o)||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||r===401||r===403||o==="401"||o==="403"?"critical":"parsing"}},de=class c extends tc{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;toolArgumentsCache=new Map;lastRequestHash=null;lastRequestTime=0;inflightRequests=new Set;constructor(){super(),this.authService=z.getInstance(),this.httpAgent=new nc.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new oc.Agent({keepAlive:!0,timeout:36e5}),i.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout");let e=Z.getInstance();e.on("toolExecuting",t=>{i.debug("[PERSONAL AGENT] Forwarding toolExecuting:",t.name,"args:",t.arguments?Object.keys(t.arguments):"none"),this.emit("toolExecuting",t)}),e.on("tool_completed",t=>{this.emit("tool_completed",t)})}getAuthToken(){let e=this.authService.getAuthToken();return e?.token?e.token:(i.warn("[PersonalAgent] No auth token available - user may not be authenticated"),"")}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform;if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"){try{let t=Fi("fs");if(t.existsSync("/etc/os-release")){let s=t.readFileSync("/etc/os-release","utf8").match(/^ID=["']?([^"'\n]+)["']?/m);if(s)return s[1].toLowerCase()}}catch{}return"linux"}return(e||"unknown").toLowerCase()}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return De.existsSync(e)?t=De.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge (${e}): ${t}
433
428
 
434
429
  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.
435
430
 
436
431
  Remember to update memory about device if any new information is learned during conversation.`}}getProjectPathContext(){return`<context>
437
- Current project path in this session: ${Nn.getInstance().getWorkingDirectory()||process.cwd()}
438
- </context>`}getDeviceKnowledgePath(){let e=Lt.join(St.homedir(),".orion");return Lt.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(Ae.existsSync(e))return;let t=Lt.join(St.homedir(),"Documents","orion","orion-device-knowledge.md");if(Ae.existsSync(t)){i.info("📦 Migrating device knowledge to cross-platform location...");let n=Lt.dirname(e);Ae.existsSync(n)||Ae.mkdirSync(n,{recursive:!0});let o=Ae.readFileSync(t,"utf8");Ae.writeFileSync(e,o,"utf8"),i.info(`✅ Device knowledge migrated to: ${e}`),i.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){i.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=Lt.dirname(e);Ae.existsSync(t)||Ae.mkdirSync(t,{recursive:!0});let n=St.platform(),o=St.arch(),s=St.hostname(),r=St.userInfo(),a=`# Device Knowledge
432
+ Current project path in this session: ${On.getInstance().getWorkingDirectory()||process.cwd()}
433
+ </context>`}getDeviceKnowledgePath(){let e=Bt.join(Ct.homedir(),".orion");return Bt.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(De.existsSync(e))return;let t=Bt.join(Ct.homedir(),"Documents","orion","orion-device-knowledge.md");if(De.existsSync(t)){i.info("📦 Migrating device knowledge to cross-platform location...");let n=Bt.dirname(e);De.existsSync(n)||De.mkdirSync(n,{recursive:!0});let s=De.readFileSync(t,"utf8");De.writeFileSync(e,s,"utf8"),i.info(`✅ Device knowledge migrated to: ${e}`),i.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){i.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=Bt.dirname(e);De.existsSync(t)||De.mkdirSync(t,{recursive:!0});let n=Ct.platform(),s=Ct.arch(),o=Ct.hostname(),r=Ct.userInfo(),a=`# Device Knowledge
439
434
 
440
435
  ## System Information
441
436
  - **Platform**: ${n}
442
- - **Architecture**: ${o}
443
- - **Hostname**: ${s}
437
+ - **Architecture**: ${s}
438
+ - **Hostname**: ${o}
444
439
  - **Username**: ${r.username}
445
440
  - **Home Directory**: ${r.homedir}
446
441
 
@@ -455,69 +450,70 @@ Current project path in this session: ${Nn.getInstance().getWorkingDirectory()||
455
450
 
456
451
  ---
457
452
  *Last updated: ${new Date().toISOString()}*
458
- `;return Ae.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 n=`${e}:${t}:${Date.now()}`,o=0;for(let s=0;s<n.length;s++){let r=n.charCodeAt(s);o=(o<<5)-o+r,o=o&o}return o.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,n,o=.7,s=!0,r,a,l){let u=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(u))return i.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(u),this.lastRequestHash=u,this.lastRequestTime=Date.now(),this.currentPromptId=Ve(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let d=l?.crossDeviceTaskId;d&&i.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),l?.mode==="new"&&(t=[],i.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let p=r||this.authService.getUserId();i.debug("🔌 WebSocket will connect after receiving sessionId from API...");let m=me.getInstance().getCurrentDeviceId();if(!m)throw i.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let f=`${this.getProjectPathContext()}
459
-
460
- My main prompt: ${e}`,y={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:f},...a.map(S=>({type:"image_url",image_url:{url:S}}))]:[{type:"text",text:f}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(this.currentSessionId?(y.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] 🔗 Including existing session_id in request: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] 🆕 No existing session_id - backend will generate new one"),l?.conversationId)y.conversationId=l.conversationId,i.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),i.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let S=t.map(b=>{let w,k=b;k.metadata?.toolResults?w=k.metadata.toolResults:k.originalContent?w=k.originalContent:w=typeof b.content=="string"?b.content:JSON.stringify(b.content);let v=[{type:"text",text:w}];return k.imageUrls&&k.imageUrls.length>0&&v.push(...k.imageUrls.map(x=>({type:"image_url",image_url:{url:x}}))),{role:b.role,content:v}});for(let b=0;b<S.length;b++)S[b].role;y.messages=S,i.debug(`[PERSONAL AGENT] Sending request with ${S.length} messages (new conversation)`)}else i.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return s?this.performStreamingToolCall(y,u):this.performNonStreamingToolCall(y,u)}async performStreamingToolCall(e,t){let n=await this.getFirebaseIdToken();return n||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((o,s)=>{this.currentAbortController=new AbortController;let r="",a=Buffer.alloc(0),l="",u="",d=[],p=null,m=!1,h="";this.currentOutput="",this.completeOutputWithToolResults="";let f=new Map,y=new Set,S=this.authService.getUserId();xo.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 ${n||this.getAuthToken()}`}}).then(async b=>{let w=b.data,k=b.headers["x-session-id"]||b.headers["session-id"];if(k){p=k,this.currentSessionId=k,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${k}`);let v=Y.getInstance();i.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await v.connectForConversation(S||void 0,k)?i.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):i.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else i.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");w.on("data",v=>{try{a=Buffer.concat([a,v]);let B="",_=0;for(let N=0;N<a.length;N++)try{B=a.slice(0,N+1).toString("utf8"),_=N+1}catch{break}if(_>0){let N=a.slice(0,_);a=a.slice(_),r+=N.toString("utf8")}}catch{r+=v.toString()}let x=[/\r?\n/,/\r/],P=[],A=r;P=A.split(/\r?\n/),A=P.pop()||"",r=A;for(let B of P){let _=B.trim();if(!(!_||_.startsWith(":"))){if(_.startsWith("event: keepalive")){i.debug("[PERSONAL AGENT] Received keepalive event"),this.emit("keepalive");continue}if(_.startsWith("data: ")){let N=_.slice(6).trim();if(N==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",l),o(l);return}try{let C=JSON.parse(N);if(C.type==="session_start"&&C.conversationId){let E=C.conversationId,g=C.isNewConversation||!1,T=C.title;i.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),i.debug(`[PERSONAL AGENT] conversationId: ${E}`),i.debug(`[PERSONAL AGENT] isNewConversation: ${g}`),T&&i.debug(`[PERSONAL AGENT] title: "${T}"`),this.emit("conversation_id_received",{conversationId:E,isNew:g,title:T||void 0});continue}if(C.type==="title_generated"&&C.title&&C.conversationId){let E=C.title,g=C.conversationId;i.debug("[PERSONAL AGENT] Received title_generated event!"),i.debug(`[PERSONAL AGENT] conversationId: ${g}`),i.debug(`[PERSONAL AGENT] title: "${E}"`),this.emit("conversation_title_updated",{conversationId:g,title:E});continue}if(C.type==="error"||C.error){let E=C.error||C,g=E.message||"Unknown error occurred",T=E.status||500,I=E.provider||"unknown";i.debug(`[PERSONAL AGENT] API Error - Status: ${T}, Provider: ${I}`),i.debug(`[PERSONAL AGENT] Error Message: ${g}`);let M=g;try{let z=JSON.parse(g);z.error?.message&&(M=z.error.message)}catch{}let O;T===503?O=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
461
-
462
- Details: ${M}`:T>=500?O=`Server Error (${T}): The AI service encountered an internal error. Please try again.
463
-
464
- Details: ${M}`:T===429?O="Rate Limit Exceeded: You've made too many requests. Please wait a moment before trying again.":O=`Error: ${M}`,this.emit("api_error",{status:T,provider:I,message:O,originalMessage:g}),u+=O+`
465
- `,this.currentOutput+=O+`
466
- `;continue}if(C.tool_response&&C.tool_response.content){let E=C.tool_response.content,g=C.tool_response.id||"unknown",T=C.tool_response.name||"unknown",I=this.toolArgumentsCache.get(g);if(this.emit("tool_completed",{toolName:T,toolId:g,result:E,todos:C.tool_response.todos||null,arguments:I}),this.emit("toolComplete",T),i.debug("[TODO-DEBUG] Checking tool_response for todos..."),i.debug("[TODO-DEBUG] Tool name:",T),i.debug("[TODO-DEBUG] tool_response keys:",Object.keys(C.tool_response).sort()),C.tool_response.todos&&Array.isArray(C.tool_response.todos))i.debug("[TODO-DEBUG] ✅ Found todos in tool_response:",C.tool_response.todos.length,"items"),this.handleTodoUpdate({items:C.tool_response.todos});else if(i.debug("[TODO-DEBUG] ❌ No todos key in tool_response"),T.toLowerCase()==="todowrite"||T.toLowerCase()==="todo_write"){i.debug("[TODO-DEBUG] This is a TodoWrite tool, checking content for todos...");try{let z=null;if(typeof E=="string"){let K=JSON.parse(E);z=K.todos||K}else if(Array.isArray(E)){let K=E[0];K&&(K.content||K.text||K.status)&&(z=E)}z&&Array.isArray(z)&&(i.debug("[TODO-DEBUG] ✅ Extracted todos from content:",z.length,"items"),this.handleTodoUpdate({items:z}))}catch(z){i.debug("[TODO-DEBUG] Could not parse todos from content:",z)}}let M="";Array.isArray(E)?M=E.map(z=>typeof z=="string"?z:z&&typeof z=="object"&&(z.text||z.content)||"").join(""):typeof E=="string"?M=E:M=JSON.stringify(E),(!M||M.trim().length===0)&&(M="(empty tool result)");let O=`<context>
467
- ${M}
468
- </context>`;d.push(O),l+=O+`
469
- `,this.completeOutputWithToolResults+=O+`
470
- `,this.currentOutput+=O+`
471
- `;continue}if(C.tool_calls){i.debug("Processing tool calls:",C.tool_calls.length,"items");for(let[E,g]of C.tool_calls.entries())if(i.debug("Tool call ["+E+"]:"),g.id){i.debug("Processing tool call ID:",g.id);let T=f.get(g.id)||{};for(let[I,M]of Object.entries(g))if(I==="function"&&typeof M=="object"&&M!==null){let O=T.function||{},z=M;for(let[K,J]of Object.entries(z))if(K==="arguments"&&typeof J=="string"){let Te=O.arguments||"";O.arguments=Te+J}else O[K]=J;T.function=O}else T[I]=M;if(f.set(g.id,T),T.function?.name&&!y.has(g.id)){let I=T.function.name;y.add(g.id),this.activeToolNames.add(I),i.debug("[TOOL-DISPLAY] Tool started:",I,"ID:",g.id);let M;if(T.function?.arguments)try{M=JSON.parse(T.function.arguments),this.toolArgumentsCache.set(g.id,M)}catch{}this.emit("toolExecuting",{toolCallId:g.id,name:I,arguments:M,startTime:new Date})}if(T.function?.name&&T.function?.arguments){let I=T.function.arguments,M=`args-${g.id}`;if((I.endsWith("}")||I.endsWith('"}'))&&!y.has(M))try{let O=JSON.parse(I);y.add(M),this.toolArgumentsCache.set(g.id,O),i.debug("[TOOL-DISPLAY] Args complete for:",T.function.name,"ID:",g.id),this.emit("tool_args_update",{toolCallId:g.id,arguments:O})}catch{}}if(T.function?.arguments&&T.function?.name){let I=T.function.arguments;I.endsWith("}")||I.endsWith('"}')?(i.debug("Complete tool call accumulated:",g.id,"-",T.function.name),i.debug("Arguments:",I.substring(0,100)+(I.length>100?"...":"")),y.has(g.id)||(y.add(g.id),this.handleCompleteToolCall(T))):i.debug("Partial tool call:",g.id,"-",T.function.name)}}}else if(C.tool_response&&C.tool_response.content){let E=C.tool_response.content,g=C.tool_response.id||"unknown",T=C.tool_response.name||"unknown",I=C.tool_response.role||"unknown";i.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),i.debug(" Tool ID:",g),i.debug(" Tool Name:",T),i.debug(" Tool Role:",I),i.debug(" Content Length:",E.length),i.debug(" Content Preview:",E.substring(0,200)+"..."),this.activeToolNames.delete(T);let M=this.toolArgumentsCache.get(g);this.emit("tool_completed",{toolName:T,toolId:g,result:E,todos:C.tool_response.todos||null,arguments:M}),this.emit("toolComplete",T),C.tool_response.todos&&Array.isArray(C.tool_response.todos)&&(i.debug("[PERSONAL AGENT] Tool response contains",C.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:C.tool_response.todos}));let O=`<context>
472
- ${E}
473
- </context>`;d.push(O),l+=O+`
474
- `,this.completeOutputWithToolResults+=O+`
475
- `,this.currentOutput+=O+`
476
- `,i.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",d.length)}else if(C.content!==void 0){let E=C.content;if(E&&E.length>0&&i.debug(`[STREAMING] Received content chunk: "${E}" (length: ${E.length})`),E&&E.includes('{"tool_response"'))try{let g,T=!1;try{g=JSON.parse(E),T=!0}catch{let I=E.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(I){let M=I[0];g=JSON.parse(M),T=!1}}if(g&&g.tool_response&&g.tool_response.content){let I=g.tool_response.content,M=g.tool_response.id||"unknown",O=g.tool_response.name||"unknown",z=this.toolArgumentsCache.get(M);this.emit("tool_completed",{toolName:O,toolId:M,result:I,todos:g.tool_response.todos||null,arguments:z}),this.emit("toolComplete",O),g.tool_response.todos&&Array.isArray(g.tool_response.todos)&&this.handleTodoUpdate({items:g.tool_response.todos});let K="";Array.isArray(I)?K=I.map(Te=>Te.text||"").join(""):typeof I=="string"?K=I:K=JSON.stringify(I);let J=`<context>
477
- ${K}
478
- </context>`;if(d.push(J),l+=J+`
479
- `,this.completeOutputWithToolResults+=J+`
480
- `,this.currentOutput+=J+`
481
- `,!T){let Te=E.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(Te){let ut=E.replace(Te[0],"").trim();if(ut.length>0){l+=ut,u+=ut,this.currentOutput+=ut,this.completeOutputWithToolResults+=ut;let Ci=je.remove(ut);this.emit("data",Ci)}}}continue}}catch{}if(E.includes("<think>")){m=!0;let g=E.split("<think>")[0];if(g){l+=g,u+=g,this.currentOutput+=g,this.completeOutputWithToolResults+=g;let T=je.remove(g);this.emit("data",T)}}else if(E.includes("</think>")){m=!1,h+=E.split("</think>")[0],this.emit("thinking",h),h="";let g=E.split("</think>")[1]||"";if(g){l+=g,u+=g,this.currentOutput+=g,this.completeOutputWithToolResults+=g;let T=je.remove(g);this.emit("data",T)}}else if(m)h+=E,this.emit("thinking",h);else{l+=E,u+=E,this.currentOutput+=E,this.completeOutputWithToolResults+=E;let g=je.remove(E);this.emit("data",g)}}else if(C.type==="checkpoint_reached"||C.event==="checkpoint_reached")i.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(C.type==="todo_update")this.handleTodoUpdate(C.data);else if(C.type==="todo_list")this.handleTodoUpdate({items:C.todos});else if(C.type==="webview_update")this.handleWebViewUpdate(C.data);else if(C.type==="operator_progress")this.handleOperatorProgress(C.data);else if(C.type==="stop"){this.handleStop(C.data),o(l);return}}catch{i.debug("Treating as plain text"),l+=N,u+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let E=je.remove(N);this.emit("data",E)}}}}}),w.on("end",()=>{this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),o(l)}),w.on("error",v=>{switch(i.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),Wt.classify(v)){case"parsing":let P={type:"tool_result",tool_call_id:`error_${Ve()}`,error:!0,content:`Streaming parsing error occurred: ${v.message}. Please check response format and retry.`};i.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(P)),Y.getInstance().handleConversationComplete(),o(l);return;case"critical":Y.getInstance().handleConversationComplete(),this.emit("error",v),s(v);break}})}).catch(b=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),b.code==="ERR_CANCELED")i.debug("Task was cancelled, disconnecting WebSocket"),Y.getInstance().handleConversationComplete(),this.emit("canceled"),o(l);else switch(Wt.classify(b)){case"parsing":let k={type:"tool_result",tool_call_id:`error_${Ve()}`,error:!0,content:`Request parsing error: ${b.message}. Please check request format and retry.`};i.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(k)),Y.getInstance().handleConversationComplete(),o(l);break;case"critical":i.debug("Request failed, disconnecting WebSocket"),Y.getInstance().handleConversationComplete(),s(b);break}})})}async performNonStreamingToolCall(e,t){try{let n=await this.getFirebaseIdToken();n||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let o=await xo.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),o.data?.content){if(this.currentOutput=o.data.content,this.completeOutputWithToolResults=o.data.completeOutput||o.data.content,o.data.toolResults)for(let s of o.data.toolResults)this.handleToolResult(s.tool,s.result);return o.data.content}throw new Error("No response content received")}catch(n){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),Wt.classify(n)){case"parsing":let s={type:"tool_result",tool_call_id:`error_${Ve()}`,error:!0,content:`Non-streaming API parsing error: ${n.message}. Please check request format and retry.`};return i.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(s)),"";case"critical":throw this.emit("error",n),new Error(`Tool calling API Error: ${n.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{i.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}n&&this.toolArgumentsCache.set(e.id,n),this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:n,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let o=Y.getInstance(),s={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await o.sendToolRequest(s)}catch(o){i.debug(`Failed to execute tool via WebSocket: ${o.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),i.debug(`Tool Result: ${e.name}`),t&&i.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:o,error:s}=e;if(i.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",o),o&&n){let a=`<context>
453
+ `;return De.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 n=`${e}:${t}:${Date.now()}`,s=0;for(let o=0;o<n.length;o++){let r=n.charCodeAt(o);s=(s<<5)-s+r,s=s&s}return s.toString(16)}isDuplicateRequest(e){let t=Date.now();return!!(this.lastRequestHash===e&&t-this.lastRequestTime<2e3||this.inflightRequests.has(e))}async sendMessageWithToolCalling(e,t,n,s=.7,o=!0,r,a,l){let u=this.generateRequestHash(e,t.length);if(this.isDuplicateRequest(u))return i.debug("[PERSONAL AGENT] Duplicate request detected, ignoring"),"";this.inflightRequests.add(u),this.lastRequestHash=u,this.lastRequestTime=Date.now(),this.currentPromptId=Qe(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=n;let d=l?.crossDeviceTaskId;d&&i.debug(`[PERSONAL AGENT] Executing cross-device task: ${d}`),l?.mode==="new"&&(t=[],i.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let p=r||this.authService.getUserId();i.debug("🔌 WebSocket will connect after receiving sessionId from API...");let m=me.getInstance().getCurrentDeviceId();if(!m)throw i.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let h=`${this.getProjectPathContext()}
454
+
455
+ My main prompt: ${e}`,y={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:h},...a.map(T=>({type:"image_url",image_url:{url:T}}))]:[{type:"text",text:h}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:n.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction(),shell_timeout_config:{activity_timeout:300,max_timeout:18e3,initial_timeout:60}};if(this.currentSessionId?(y.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] 🔗 Including existing session_id in request: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] 🆕 No existing session_id - backend will generate new one"),l?.conversationId)y.conversationId=l.conversationId,i.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),i.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let T=t.map(S=>{let w,E=S;E.metadata?.toolResults?w=E.metadata.toolResults:E.originalContent?w=E.originalContent:w=typeof S.content=="string"?S.content:JSON.stringify(S.content);let b=[{type:"text",text:w}];return E.imageUrls&&E.imageUrls.length>0&&b.push(...E.imageUrls.map(C=>({type:"image_url",image_url:{url:C}}))),{role:S.role,content:b}});for(let S=0;S<T.length;S++)T[S].role;y.messages=T,i.debug(`[PERSONAL AGENT] Sending request with ${T.length} messages (new conversation)`)}else i.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return o?this.performStreamingToolCall(y,u):this.performNonStreamingToolCall(y,u)}async performStreamingToolCall(e,t){let n=await this.getFirebaseIdToken();return n||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401"),new Promise((s,o)=>{this.currentAbortController=new AbortController;let r="",a=Buffer.alloc(0),l="",u="",d=[],p=null,m=!1,g="";this.currentOutput="",this.completeOutputWithToolResults="";let h=new Map,y=new Set,T=new Map,S=this.authService.getUserId();Mo.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 ${n||this.getAuthToken()}`}}).then(async w=>{let E=w.data,b=w.headers["x-session-id"]||w.headers["session-id"];if(b){p=b,this.currentSessionId=b,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CAPTURED: ${b}`);let C=Z.getInstance();i.debug("[PERSONAL AGENT] 🔌 Connecting WebSocket with sessionId..."),await C.connectForConversation(S||void 0,b)?i.debug("[PERSONAL AGENT] ✅ WebSocket connected with deviceId_sessionId composite key"):i.debug("[PERSONAL AGENT] ⚠️ WebSocket connection failed, continuing without frontend tool support")}else i.debug("[PERSONAL AGENT] ⚠️ No X-Session-Id header found in response - WebSocket will not connect");E.on("data",C=>{try{a=Buffer.concat([a,C]);let j="",q=0;for(let N=0;N<a.length;N++)try{j=a.slice(0,N+1).toString("utf8"),q=N+1}catch{break}if(q>0){let N=a.slice(0,q);a=a.slice(q),r+=N.toString("utf8")}}catch{r+=C.toString()}let P=[/\r?\n/,/\r/],R=[],O=r;R=O.split(/\r?\n/),O=R.pop()||"",r=O;for(let j of R){let q=j.trim();if(!(!q||q.startsWith(":"))){if(q.startsWith("event: keepalive")){i.debug("[PERSONAL AGENT] Received keepalive event"),this.emit("keepalive");continue}if(q.startsWith("data: ")){let N=q.slice(6).trim();if(N==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",l),s(l);return}try{let k=JSON.parse(N);if(k.type==="session_start"&&k.conversationId){let f=k.conversationId,v=k.isNewConversation||!1,x=k.title;i.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),i.debug(`[PERSONAL AGENT] conversationId: ${f}`),i.debug(`[PERSONAL AGENT] isNewConversation: ${v}`),x&&i.debug(`[PERSONAL AGENT] title: "${x}"`),this.emit("conversation_id_received",{conversationId:f,isNew:v,title:x||void 0});continue}if(k.type==="title_generated"&&k.title&&k.conversationId){let f=k.title,v=k.conversationId;i.debug("[PERSONAL AGENT] Received title_generated event!"),i.debug(`[PERSONAL AGENT] conversationId: ${v}`),i.debug(`[PERSONAL AGENT] title: "${f}"`),this.emit("conversation_title_updated",{conversationId:v,title:f});continue}if(k.type==="error"||k.error){let f=k.error||k,v=f.message||"Unknown error occurred",x=f.status||500,U=f.provider||"unknown";i.debug(`[PERSONAL AGENT] API Error - Status: ${x}, Provider: ${U}`),i.debug(`[PERSONAL AGENT] Error Message: ${v}`);let A=v;try{let _=JSON.parse(v);_.error?.message&&(A=_.error.message)}catch{}let M;x===503?M=`Service Temporarily Unavailable: The AI model is currently experiencing high demand. Please try again in a few moments.
456
+
457
+ Details: ${A}`:x>=500?M=`Server Error (${x}): The AI service encountered an internal error. Please try again.
458
+
459
+ Details: ${A}`:x===429?M="Rate Limit Exceeded: You've made too many requests. Please wait a moment before trying again.":M=`Error: ${A}`,this.emit("api_error",{status:x,provider:U,message:M,originalMessage:v}),u+=M+`
460
+ `,this.currentOutput+=M+`
461
+ `;continue}if(k.tool_response&&k.tool_response.content){let f=k.tool_response.content,v=k.tool_response.id||"unknown",x=k.tool_response.name||"unknown",U=this.toolArgumentsCache.get(v);if(this.emit("tool_completed",{toolName:x,toolId:v,result:f,todos:k.tool_response.todos||null,arguments:U}),this.emit("toolComplete",x),i.debug("[TODO-DEBUG] Checking tool_response for todos..."),i.debug("[TODO-DEBUG] Tool name:",x),i.debug("[TODO-DEBUG] tool_response keys:",Object.keys(k.tool_response).sort()),k.tool_response.todos&&Array.isArray(k.tool_response.todos))i.debug("[TODO-DEBUG] ✅ Found todos in tool_response:",k.tool_response.todos.length,"items"),this.handleTodoUpdate({items:k.tool_response.todos});else if(i.debug("[TODO-DEBUG] ❌ No todos key in tool_response"),x.toLowerCase()==="todowrite"||x.toLowerCase()==="todo_write"){i.debug("[TODO-DEBUG] This is a TodoWrite tool, checking content for todos...");try{let _=null;if(typeof f=="string"){let B=JSON.parse(f);_=B.todos||B}else if(Array.isArray(f)){let B=f[0];B&&(B.content||B.text||B.status)&&(_=f)}_&&Array.isArray(_)&&(i.debug("[TODO-DEBUG] ✅ Extracted todos from content:",_.length,"items"),this.handleTodoUpdate({items:_}))}catch(_){i.debug("[TODO-DEBUG] Could not parse todos from content:",_)}}let A="";Array.isArray(f)?A=f.map(_=>typeof _=="string"?_:_&&typeof _=="object"&&(_.text||_.content)||"").join(""):typeof f=="string"?A=f:A=JSON.stringify(f),(!A||A.trim().length===0)&&(A="(empty tool result)");let M=`<context>
462
+ ${A}
463
+ </context>`;d.push(M),l+=M+`
464
+ `,this.completeOutputWithToolResults+=M+`
465
+ `,this.currentOutput+=M+`
466
+ `;continue}if(k.tool_calls){i.debug("Processing tool calls:",k.tool_calls.length,"items");for(let[f,v]of k.tool_calls.entries()){i.debug("Tool call ["+f+"]:");let x=v.id,U=v.index??f;if(x&&U!==void 0?(T.set(U,x),i.debug(`Mapped index ${U} -> id ${x}`)):!x&&U!==void 0&&(x=T.get(U),x&&i.debug(`Resolved index ${U} -> id ${x}`)),x){i.debug("Processing tool call ID:",x);let A=h.get(x)||{};for(let[M,_]of Object.entries(v))if(M==="function"&&typeof _=="object"&&_!==null){let B=A.function||{},ye=_;for(let[st,Re]of Object.entries(ye))if(st==="arguments"&&typeof Re=="string"){let io=B.arguments||"";B.arguments=io+Re}else B[st]=Re;A.function=B}else A[M]=_;if(h.set(x,A),A.function?.name&&!y.has(x)){let M=A.function.name;y.add(x),this.activeToolNames.add(M),i.debug("[TOOL-DISPLAY] Tool started:",M,"ID:",x);let _;if(A.function?.arguments)try{_=JSON.parse(A.function.arguments),this.toolArgumentsCache.set(x,_)}catch{}this.emit("toolExecuting",{toolCallId:x,name:M,arguments:_,startTime:new Date})}if(A.function?.name&&A.function?.arguments){let M=A.function.arguments,_=`args-${x}`;if((M.endsWith("}")||M.endsWith('"}'))&&!y.has(_))try{let B=JSON.parse(M);y.add(_),this.toolArgumentsCache.set(x,B),i.debug("[TOOL-DISPLAY] Args complete for:",A.function.name,"ID:",x),this.emit("tool_args_update",{toolCallId:x,arguments:B})}catch{}}if(A.function?.arguments&&A.function?.name){let M=A.function.arguments;M.endsWith("}")||M.endsWith('"}')?(i.debug("Complete tool call accumulated:",x,"-",A.function.name),i.debug("Arguments:",M.substring(0,100)+(M.length>100?"...":"")),y.has(x)||(y.add(x),this.handleCompleteToolCall(A))):i.debug("Partial tool call:",x,"-",A.function.name)}}}}else if(k.tool_response&&k.tool_response.content){let f=k.tool_response.content,v=k.tool_response.id||"unknown",x=k.tool_response.name||"unknown",U=k.tool_response.role||"unknown";i.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),i.debug(" Tool ID:",v),i.debug(" Tool Name:",x),i.debug(" Tool Role:",U),i.debug(" Content Length:",f.length),i.debug(" Content Preview:",f.substring(0,200)+"..."),this.activeToolNames.delete(x);let A=this.toolArgumentsCache.get(v);this.emit("tool_completed",{toolName:x,toolId:v,result:f,todos:k.tool_response.todos||null,arguments:A}),this.emit("toolComplete",x),k.tool_response.todos&&Array.isArray(k.tool_response.todos)&&(i.debug("[PERSONAL AGENT] Tool response contains",k.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:k.tool_response.todos}));let M=`<context>
467
+ ${f}
468
+ </context>`;d.push(M),l+=M+`
469
+ `,this.completeOutputWithToolResults+=M+`
470
+ `,this.currentOutput+=M+`
471
+ `,i.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",d.length)}else if(k.content!==void 0){let f=k.content;if(f&&f.length>0&&i.debug(`[STREAMING] Received content chunk: "${f}" (length: ${f.length})`),f&&f.includes('{"tool_response"'))try{let v,x=!1;try{v=JSON.parse(f),x=!0}catch{let U=f.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(U){let A=U[0];v=JSON.parse(A),x=!1}}if(v&&v.tool_response&&v.tool_response.content){let U=v.tool_response.content,A=v.tool_response.id||"unknown",M=v.tool_response.name||"unknown",_=this.toolArgumentsCache.get(A);this.emit("tool_completed",{toolName:M,toolId:A,result:U,todos:v.tool_response.todos||null,arguments:_}),this.emit("toolComplete",M),v.tool_response.todos&&Array.isArray(v.tool_response.todos)&&this.handleTodoUpdate({items:v.tool_response.todos});let B="";Array.isArray(U)?B=U.map(st=>st.text||"").join(""):typeof U=="string"?B=U:B=JSON.stringify(U);let ye=`<context>
472
+ ${B}
473
+ </context>`;if(d.push(ye),l+=ye+`
474
+ `,this.completeOutputWithToolResults+=ye+`
475
+ `,this.currentOutput+=ye+`
476
+ `,!x){let st=f.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(st){let Re=f.replace(st[0],"").trim();if(Re.length>0){l+=Re,u+=Re,this.currentOutput+=Re,this.completeOutputWithToolResults+=Re;let io=Ke.remove(Re);this.emit("data",io)}}}continue}}catch{}if(f.includes("<think>")){m=!0;let v=f.split("<think>")[0];if(v){l+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let x=Ke.remove(v);this.emit("data",x)}}else if(f.includes("</think>")){m=!1,g+=f.split("</think>")[0],this.emit("thinking",g),g="";let v=f.split("</think>")[1]||"";if(v){l+=v,u+=v,this.currentOutput+=v,this.completeOutputWithToolResults+=v;let x=Ke.remove(v);this.emit("data",x)}}else if(m)g+=f,this.emit("thinking",g);else{l+=f,u+=f,this.currentOutput+=f,this.completeOutputWithToolResults+=f;let v=Ke.remove(f);this.emit("data",v)}}else if(k.type==="checkpoint_reached"||k.event==="checkpoint_reached")i.debug("[CHECKPOINT] Backend reached checkpoint, processing queued messages as feedback"),this.handleCheckpointReached();else if(k.type==="todo_update")this.handleTodoUpdate(k.data);else if(k.type==="todo_list")this.handleTodoUpdate({items:k.todos});else if(k.type==="webview_update")this.handleWebViewUpdate(k.data);else if(k.type==="operator_progress")this.handleOperatorProgress(k.data);else if(k.type==="stop"){this.handleStop(k.data),s(l);return}}catch{i.debug("Treating as plain text"),l+=N,u+=N,this.currentOutput+=N,this.completeOutputWithToolResults+=N;let f=Ke.remove(N);this.emit("data",f)}}}}}),E.on("end",()=>{this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),this.emit("done"),s(l)}),E.on("error",C=>{switch(i.debug("Streaming error, disconnecting WebSocket and cleaning up"),this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),Ht.classify(C)){case"parsing":let R={type:"tool_result",tool_call_id:`error_${Qe()}`,error:!0,content:`Streaming parsing error occurred: ${C.message}. Please check response format and retry.`};i.debug("🔄 [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(R)),Z.getInstance().handleConversationComplete(),s(l);return;case"critical":Z.getInstance().handleConversationComplete(),this.emit("error",C),o(C);break}})}).catch(w=>{if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),w.code==="ERR_CANCELED")i.debug("Task was cancelled, disconnecting WebSocket"),Z.getInstance().handleConversationComplete(),this.emit("canceled"),s(l);else switch(Ht.classify(w)){case"parsing":let b={type:"tool_result",tool_call_id:`error_${Qe()}`,error:!0,content:`Request parsing error: ${w.message}. Please check request format and retry.`};i.debug("🔄 [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(b)),Z.getInstance().handleConversationComplete(),s(l);break;case"critical":i.debug("Request failed, disconnecting WebSocket"),Z.getInstance().handleConversationComplete(),o(w);break}})})}async performNonStreamingToolCall(e,t){try{let n=await this.getFirebaseIdToken();n||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available - request may fail with 401");let s=await Mo.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||this.getAuthToken()}`}});if(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let o of s.data.toolResults)this.handleToolResult(o.tool,o.result);return s.data.content}throw new Error("No response content received")}catch(n){switch(this.inflightRequests.delete(t),this.activeToolNames.clear(),this.toolArgumentsCache.clear(),Ht.classify(n)){case"parsing":let o={type:"tool_result",tool_call_id:`error_${Qe()}`,error:!0,content:`Non-streaming API parsing error: ${n.message}. Please check request format and retry.`};return i.debug("🔄 [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(o)),"";case"critical":throw this.emit("error",n),new Error(`Tool calling API Error: ${n.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",n=null;if(e.function?.arguments)try{n=JSON.parse(e.function.arguments)}catch{i.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}n&&this.toolArgumentsCache.set(e.id,n),this.emit("toolExecuting",{toolCallId:e.id,name:t,arguments:n,startTime:new Date}),this.executeToolViaWebSocket(e.id,t,n)}async executeToolViaWebSocket(e,t,n){try{let s=Z.getInstance(),o={id:e,tool_name:t,arguments:n||{},tool_call_id:e};await s.sendToolRequest(o)}catch(s){i.debug(`Failed to execute tool via WebSocket: ${s.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),i.debug(`Tool Result: ${e.name}`),t&&i.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:n,success:s,error:o}=e;if(i.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",s),s&&n){let a=`<context>
482
477
  ${n.map(l=>l.text||"").join("")}
483
478
  </context>`;this.completeOutputWithToolResults+=a+`
484
479
  `,this.currentOutput+=a+`
485
- `,i.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(s){i.debug("[PERSONAL AGENT] WebSocket tool error:",s);let r=`<context>
486
- Error: ${s}
480
+ `,i.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(o){i.debug("[PERSONAL AGENT] WebSocket tool error:",o);let r=`<context>
481
+ Error: ${o}
487
482
  </context>`;this.completeOutputWithToolResults+=r+`
488
- `}}captureFrontendToolResult(e,t,n,o){let s=`<context>
483
+ `}}captureFrontendToolResult(e,t,n,s){let o=`<context>
489
484
  Tool: ${e}
490
485
  Success: ${n}
491
486
  Output:
492
487
  ${t}
493
- </context>`;this.completeOutputWithToolResults+=s+`
494
- `,this.currentOutput+=s+`
495
- `,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),i.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:o,wrappedContent:s})}handleCheckpointReached(){let e=ke.getInstance(),t=e.getQueuedMessages();if(t.length===0){i.debug("[CHECKPOINT] No queued messages to convert");return}let n=t.filter(s=>!s.isCrossDeviceTask),o=t.filter(s=>s.isCrossDeviceTask);if(i.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),i.debug(` - ${n.length} user messages -> convert to feedback`),i.debug(` - ${o.length} cross-device tasks -> keep in queue`),n.length>0){let s=n.map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",s),i.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(r=>{e.removeFromQueueById(r.id)})}o.length>0&&i.debug(`[CHECKPOINT] Kept ${o.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){i.debug("[TODO-DEBUG] handleTodoUpdate called with:",JSON.stringify(e).substring(0,500));let t=e.items||e.todos||[];i.debug("[TODO-DEBUG] Extracted items count:",t.length),this.currentTodoList={todos:t.map(n=>{let o=n.content||n.text||"";return i.debug("[TODO-DEBUG] Processing todo item:",{id:n.id,text:o,status:n.status}),{id:n.id||Ve(),content:o,text:o,completed:n.completed||!1,priority:n.priority,status:n.status||(n.completed?"completed":"pending"),activeForm:n.activeForm||o}}),timestamp:new Date(e.timestamp||Date.now())},i.debug("[TODO-DEBUG] Emitting todo_update with",this.currentTodoList.todos.length,"todos"),this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||Ve(),taskId:e.taskId||e.id||Ve(),sessionId:e.sessionId||Ve(),status:e.status||"pending",task:e.task||e.description||"",llm:e.llm,currentStep:e.currentStep,totalSteps:e.totalSteps||0,steps:e.steps||[],result:e.result,error:e.error,startTime:e.startTime||new Date},this.emit("operator_progress",this.operatorTaskState)}handleStop(e){e.reason==="CONVERSATION_COMPLETE"&&this.handleConversationComplete(),this.emit("BotResponseStopped",{reason:e.reason||"user_manual_stop"}),this.emit("stop",e)}async handleConversationComplete(){if(i.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),Y.getInstance().handleConversationComplete(),i.debug("[PERSONAL AGENT] WebSocket disconnected after conversation completion"),this.currentOutput.trim().length>0){let t={conversationId:null,content:this.currentOutput,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};i.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),i.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),i.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",o=Q.find(r=>r.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},s=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,s,o,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){i.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),Y.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
496
-
497
- [STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{i.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(o){i.debug("[PERSONAL AGENT] Firebase update failed for STOP:",o)}await this.completeConversation(n,"STOP"),i.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),i.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let o=me.getInstance().getCurrentDeviceId();o?(n.device_id=o,i.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${o}`)):i.debug("[PERSONAL AGENT] No device_id available for stop request"),i.debug("[PERSONAL AGENT] Sending backend stop request");let s=await this.getFirebaseIdToken();s||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let r=await xo.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s||this.getAuthToken()}`}});r.status===200&&(i.debug("[PERSONAL AGENT] Backend stop successful:",r.data),r.data.stopped_sessions&&i.debug("[PERSONAL AGENT] Stopped sessions:",r.data.stopped_sessions),r.data.stopped_tools&&i.debug("[PERSONAL AGENT] Stopped tools:",r.data.stopped_tools))}catch(e){i.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){i.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`);let n=this.currentSessionId;this.currentSessionId=null,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CLEARED FIRST on conversation completion (was: ${n})`),Y.getInstance().handleConversationComplete();let s={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",s),this.resetState(),i.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),this.activeToolNames.clear(),this.toolArgumentsCache.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 ar={};Ee(ar,{FirebaseNativeService:()=>Bt,TaskMode:()=>Io,TaskStatus:()=>Po});import{getDatabase as Ka,ref as ko,onChildAdded as Qa,update as Ja,set as Ya,serverTimestamp as Za}from"firebase/database";import{EventEmitter as ec}from"events";var Io,Po,Bt,Ao=D(()=>{"use strict";$();Zt();Io=(t=>(t.NEW="new",t.EXISTING="existing",t))(Io||{}),Po=(o=>(o.PENDING="pending",o.PROCESSING="processing",o.COMPLETED="completed",o.QUEUE_FULL="queue_full",o))(Po||{}),Bt=class c extends ec{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),i.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=Ge.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=Ka(e),i.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(i.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(i.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){i.error("[Firebase Native] Firebase not initialized properly");return}i.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;i.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let o=ko(this.database,n),s=this.auth?.currentUser;i.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!s,uid:s?.uid||"none",email:s?.email||"none"}),this.listenerHandle=Qa(o,r=>{let a=r.key,l=r.val();if(i.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){i.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){i.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){i.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:l.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let u=Array.from(this.processedTaskIds);u.slice(0,u.length-this.MAX_PROCESSED_IDS).forEach(p=>this.processedTaskIds.delete(p))}i.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{i.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),i.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){i.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,i.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),i.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),i.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){i.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){i.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),i.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),i.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(Pe(),nt))).PersonalAgentService.getInstance()){i.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}i.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?i.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):i.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),i.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),i.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(o){i.error("[FIREBASE-NATIVE] Task execution failed:",o.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Pe(),nt)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=o=>{this.currentTaskId===e&&(i.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=o=>{if(this.currentTaskId!==e)return;let s=o?.message||o||"Unknown error occurred";i.debug(`[RESULT MONITOR] Task ${e} failed: ${s}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=o=>{if(this.currentTaskId!==e)return;let s=o?.reason;i.debug(`[RESULT MONITOR] Task ${e} stopped: ${s}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),i.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(Pe(),nt)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),i.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){i.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let o=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};n&&(s.result=n),i.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:o,status:t,hasResult:!!n});try{i.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(o,s),i.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){i.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:o,error:r.message}),i.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=ko(this.database,o),l={status:t,updatedAt:Za()};n&&(l.result=n),await Ja(a,l),i.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else i.error("[Firebase Native] Database not available for fallback")}catch(a){i.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,o){let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;i.debug("[Firebase Native] Sending task to device",{taskId:s,targetDeviceId:t,mode:o});try{let r=ko(this.database,`users/${e}/devices/${t}/tasks/${s}`),a={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:o,timestamp:Date.now(),status:"pending"};return await Ya(r,a),i.debug("[Firebase Native] Task sent successfully",{taskId:s,targetDeviceId:t}),s}catch(r){throw r}}stopListening(){if(i.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,i.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){i.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),i.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as tc}from"events";var wt,Do=D(()=>{"use strict";ze();ce();Zt();Ao();Pe();$();wt=class c extends tc{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=me.getInstance(),this.authService=H.getInstance(),this.firebaseAPI=Ge.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=ue.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){i.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(i.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(i.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){i.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(ue.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){i.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();i.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){i.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,i.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let o=this.authService.getFirebaseAuth();if(!o?.currentUser){i.error("No authenticated Firebase user - cannot start listeners");return}if(o.currentUser.uid!==e){i.error("SECURITY: User ID mismatch! Firebase UID:",o.currentUser.uid,"Requested:",e),i.error("Refusing to start listener for different user");return}i.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(o){throw i.error("Failed to start listener:",o.message),o}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),i.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){i.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){i.error("No stored user ID found - cannot authenticate Firebase for listeners");return}i.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let o=await this.authService.signInWithCustomToken(n);i.debug("Firebase authenticated successfully - UID:",o.user.uid)}}catch(n){i.warn("Firebase authentication failed:",n.message),i.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){i.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e.taskId),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}i.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,i.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),i.debug("Cross-device task UI flow triggered successfully")}catch(t){i.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){i.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){i.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),i.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let o=n[1],s=n[2];return o.length!==13||!Number.isInteger(Number(o))||s.length!==9?!1:/^[a-z0-9]+$/.test(s)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,o=t.prompt,s=t.status;if(!n||!o){i.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(s!=="pending"){i.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",s);return}this.incomingTaskQueue.push({taskId:n,prompt:o,snapshot:e}),i.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),i.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){i.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();i.debug(`🔵 [CrossDevice] Processing task: ${e}`),i.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let o=n.val();if(i.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(i.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){i.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}i.debug("✅ [CrossDevice] Task accepted:",e),i.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(ue.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let o=(dt(),Ai(hs)).MessageQueueManager.getInstance(),s=o.getQueueCount(),r=o.canAddToQueue();if(i.debug(`🔍 [CrossDevice] Queue capacity check: ${s}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(i.debug(`Executing task: ${e} with mode: ${n}`),i.debug(`Prompt to execute: ${t}`),ue.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(r),i.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}i.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{i.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(o){i.error("Task execution failed:",o.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,o)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=s=>{this.currentTaskId===e&&this.cleanupObservers()},o=s=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",o)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:qe,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${o}`;try{await this.firebaseAPI.writeRealtimeData(r,s),i.debug("Task submitted to device:",e)}catch(a){throw i.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,o])=>({id:n,...o})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return i.error("Failed to get available devices:",e.message),[]}}enable(){i.debug("[CROSS DEVICE] Service enabled")}disable(){i.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){i.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var di={};Ee(di,{SnowXStreamHandlerService:()=>ss});import{EventEmitter as vl}from"events";var ss,pi=D(()=>{"use strict";ss=class extends vl{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,n,o,s){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(n,o,s)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,o,s),this.printFinalStatistics(),!this.fullResponse&&!s){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let o,s=this.buffer.indexOf(`\r
498
- `);if(s!==-1)o=s;else{let r=this.buffer.indexOf(`
499
- `);if(r!==-1)o=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)o=a;else return}}for(;o!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,o);this.linesProcessed++,this.buffer.substring(o,o+2)===`\r
500
- `?this.buffer=this.buffer.substring(o+2):this.buffer=this.buffer.substring(o+1);let a=r.trim();if(!a){o=this.findNextLineEnd();continue}if(a.startsWith(":")){o=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,n),o=this.findNextLineEnd()}}processDataLine(e,t,n,o){if(this.isCancelled)return;this.dataLinesFound++;let s=e.substring(6).trim();if(s==="[DONE]"){this.emit("streamEnd");return}if(s)try{let r=JSON.parse(s);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)o?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,n))}}catch{}}processThinkingContent(e,t,n){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let o=this.thinkingBuffer.indexOf("</think>");if(o!==-1){let s=this.thinkingBuffer.substring(0,o);s&&(this.thinkingContent+=s,n?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(o+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",n?.(this.thinkingContent));break}else{let o=this.thinkingBuffer.indexOf("<think>");if(o!==-1){let s=this.thinkingBuffer.substring(0,o);s&&(this.regularContent+=s,this.fullResponse+=s,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(o+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,n){if(this.rawDataReceived.startsWith("data: ")){let o=this.rawDataReceived.substring(6).trim();try{let s=JSON.parse(o);s.choices&&s.choices.length>0&&s.choices[0].delta.content&&this.processThinkingContent(s.choices[0].delta.content,e,t)}catch{}}else try{let o=JSON.parse(this.rawDataReceived);o.choices?.[0]?.message?.content&&this.processThinkingContent(o.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
488
+ </context>`;this.completeOutputWithToolResults+=o+`
489
+ `,this.currentOutput+=o+`
490
+ `,i.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${n}`),i.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:n,toolId:s,wrappedContent:o})}handleCheckpointReached(){let e=Ie.getInstance(),t=e.getQueuedMessages();if(t.length===0){i.debug("[CHECKPOINT] No queued messages to convert");return}let n=t.filter(o=>!o.isCrossDeviceTask),s=t.filter(o=>o.isCrossDeviceTask);if(i.debug(`[CHECKPOINT] Found ${t.length} queued messages:`),i.debug(` - ${n.length} user messages -> convert to feedback`),i.debug(` - ${s.length} cross-device tasks -> keep in queue`),n.length>0){let o=n.map(r=>({id:r.id,content:r.content,timestamp:r.timestamp,isFeedbackMessage:!0}));this.emit("feedback:messages",o),i.info(`[CHECKPOINT] Converted ${n.length} user messages to feedback`),n.forEach(r=>{e.removeFromQueueById(r.id)})}s.length>0&&i.debug(`[CHECKPOINT] Kept ${s.length} cross-device tasks in queue for execution`)}handleTodoUpdate(e){i.debug("[TODO-DEBUG] handleTodoUpdate called with:",JSON.stringify(e).substring(0,500));let t=e.items||e.todos||[];i.debug("[TODO-DEBUG] Extracted items count:",t.length),this.currentTodoList={todos:t.map(n=>{let s=n.content||n.text||"";return i.debug("[TODO-DEBUG] Processing todo item:",{id:n.id,text:s,status:n.status}),{id:n.id||Qe(),content:s,text:s,completed:n.completed||!1,priority:n.priority,status:n.status||(n.completed?"completed":"pending"),activeForm:n.activeForm||s}}),timestamp:new Date(e.timestamp||Date.now())},i.debug("[TODO-DEBUG] Emitting todo_update with",this.currentTodoList.todos.length,"todos"),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||Qe(),taskId:e.taskId||e.id||Qe(),sessionId:e.sessionId||Qe(),status:e.status||"pending",task:e.task||e.description||"",llm:e.llm,currentStep:e.currentStep,totalSteps:e.totalSteps||0,steps:e.steps||[],result:e.result,error:e.error,startTime:e.startTime||new Date},this.emit("operator_progress",this.operatorTaskState)}handleStop(e){e.reason==="CONVERSATION_COMPLETE"&&this.handleConversationComplete(),this.emit("BotResponseStopped",{reason:e.reason||"user_manual_stop"}),this.emit("stop",e)}async handleConversationComplete(){if(i.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),Z.getInstance().handleConversationComplete(),i.debug("[PERSONAL AGENT] WebSocket disconnected after conversation completion"),this.currentOutput.trim().length>0){let t={conversationId:null,content:this.currentOutput,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};i.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),i.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),i.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,n)=>typeof n.content=="string"?t+Math.ceil(n.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let n=t?.selectedPersonalModel||this.currentModel?.name||"snowx-c5",s=Y.find(r=>r.name===n)||{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},o=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,o,s,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){i.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),Z.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,n;if(t&&t.trim().length>0?n=t+`
491
+
492
+ [STOPPED] - Task was stopped by user`:n="Task was stopped by user before any response was generated.",this.currentPromptId)try{i.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(s){i.debug("[PERSONAL AGENT] Firebase update failed for STOP:",s)}await this.completeConversation(n,"STOP"),i.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),i.debug("[PERSONAL AGENT] Local operations stopped (sessionId preserved for backend stop)")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",n={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(n.session_id=this.currentSessionId,i.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):i.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let s=me.getInstance().getCurrentDeviceId();s?(n.device_id=s,i.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${s}`)):i.debug("[PERSONAL AGENT] No device_id available for stop request"),i.debug("[PERSONAL AGENT] Sending backend stop request");let o=await this.getFirebaseIdToken();o||i.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let r=await Mo.post(t,n,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o||this.getAuthToken()}`}});r.status===200&&(i.debug("[PERSONAL AGENT] Backend stop successful:",r.data),r.data.stopped_sessions&&i.debug("[PERSONAL AGENT] Stopped sessions:",r.data.stopped_sessions),r.data.stopped_tools&&i.debug("[PERSONAL AGENT] Stopped tools:",r.data.stopped_tools))}catch(e){i.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){i.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`);let n=this.currentSessionId;this.currentSessionId=null,i.debug(`[PERSONAL AGENT] 🆔 SESSION ID CLEARED FIRST on conversation completion (was: ${n})`),Z.getInstance().handleConversationComplete();let o={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",o),this.resetState(),i.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear(),this.activeToolNames.clear(),this.toolArgumentsCache.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 br={};ke(br,{FirebaseNativeService:()=>Gt,TaskMode:()=>Fo,TaskStatus:()=>$o});import{getDatabase as ic,ref as Oo,onChildAdded as ac,update as cc,set as lc,serverTimestamp as uc}from"firebase/database";import{EventEmitter as dc}from"events";var Fo,$o,Gt,Uo=D(()=>{"use strict";L();on();Fo=(t=>(t.NEW="new",t.EXISTING="existing",t))(Fo||{}),$o=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s.QUEUE_FULL="queue_full",s))($o||{}),Gt=class c extends dc{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;processedTaskIds=new Set;MAX_PROCESSED_IDS=50;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),i.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=ze.getInstance()}setFirebaseInstances(e,t){i.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=ic(e),i.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(i.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(i.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){i.error("[Firebase Native] Firebase not initialized properly");return}i.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let n=`users/${e}/devices/${t}/tasks`;i.debug("[Firebase Native] Creating Firebase reference",{taskPath:n});let s=Oo(this.database,n),o=this.auth?.currentUser;i.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!o,uid:o?.uid||"none",email:o?.email||"none"}),this.listenerHandle=ac(s,r=>{let a=r.key,l=r.val();if(i.debug("[Firebase Native] Child added event received",{taskId:a,status:l?.status,exists:r.exists()}),!a||!l){i.debug("[Firebase Native] Invalid task snapshot - skipping");return}if(this.processedTaskIds.has(a)){i.debug("[Firebase Native] Task already processed - skipping duplicate",{taskId:a});return}if(l.status!=="pending"){i.debug("[Firebase Native] Task not pending - skipping",{taskId:a,status:l.status});return}if(this.processedTaskIds.add(a),this.processedTaskIds.size>this.MAX_PROCESSED_IDS){let u=Array.from(this.processedTaskIds);u.slice(0,u.length-this.MAX_PROCESSED_IDS).forEach(p=>this.processedTaskIds.delete(p))}i.debug("[Firebase Native] Processing new PENDING task",{taskId:a}),this.handleIncomingTask(a,l)},r=>{i.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),i.debug("[Firebase Native] Firebase onChildAdded listener established",{taskPath:n,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}async handleIncomingTask(e,t){i.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,i.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),i.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),i.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(n){i.error("[Firebase Native] Error processing task",{taskId:e,error:n.message,stack:n.stack}),await this.updateTaskStatus(e,"completed",`Error: ${n.message}`)}}async executeTask(e,t,n){i.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${n}`),i.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),i.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(Ae(),it))).PersonalAgentService.getInstance()){i.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}i.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),n==="new"?i.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):i.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),i.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:n==="new"?"new":"existing"}),i.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(s){i.error("[FIREBASE-NATIVE] Task execution failed:",s.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(Ae(),it)),n=t.getInstance();await this.cleanupObservers(),this.completedObserver=s=>{this.currentTaskId===e&&(i.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},n.on("BotResponseCompleted",this.completedObserver),this.errorObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.message||s||"Unknown error occurred";i.debug(`[RESULT MONITOR] Task ${e} failed: ${o}`),this.cleanupObservers()},n.on("BotResponseError",this.errorObserver),this.stopObserver=s=>{if(this.currentTaskId!==e)return;let o=s?.reason;i.debug(`[RESULT MONITOR] Task ${e} stopped: ${o}`),setTimeout(()=>{this.cleanupObservers()},100)},n.on("BotResponseStopped",this.stopObserver),i.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(Ae(),it)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),i.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,n){if(!this.currentUserId||!this.currentDeviceId){i.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,o={status:t,updatedAt:"firebase_timestamp"};n&&(o.result=n),i.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:s,status:t,hasResult:!!n});try{i.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(s,o),i.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){i.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:s,error:r.message}),i.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Oo(this.database,s),l={status:t,updatedAt:uc()};n&&(l.result=n),await cc(a,l),i.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else i.error("[Firebase Native] Database not available for fallback")}catch(a){i.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,n,s){let o=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;i.debug("[Firebase Native] Sending task to device",{taskId:o,targetDeviceId:t,mode:s});try{let r=Oo(this.database,`users/${e}/devices/${t}/tasks/${o}`),a={taskId:o,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:n,mode:s,timestamp:Date.now(),status:"pending"};return await lc(r,a),i.debug("[Firebase Native] Task sent successfully",{taskId:o,targetDeviceId:t}),o}catch(r){throw r}}stopListening(){if(i.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,i.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){i.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,this.processedTaskIds.clear(),i.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as pc}from"events";var xt,Lo=D(()=>{"use strict";Xe();le();on();Uo();Ae();L();xt=class c extends pc{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=me.getInstance(),this.authService=z.getInstance(),this.firebaseAPI=ze.getInstance(),this.firebaseNative=Gt.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=de.getInstance();e.on("BotResponseCompleted",()=>{this.handleTaskCompletion()}),e.on("BotResponseStopped",()=>{this.handleTaskCompletion()}),e.on("BotResponseError",()=>{this.handleTaskCompletion()})}async handleTaskCompletion(){i.debug("✅ [CrossDevice] Task completion event received"),this.currentlyExecutingTaskId&&(i.debug("✅ [CrossDevice] Marking task completed:",this.currentlyExecutingTaskId),await this.markTaskCompletedById(this.currentlyExecutingTaskId),this.currentlyExecutingTaskId=null),this.incomingTaskQueue.length>0&&!this.isProcessingIncoming?(i.debug(`🔵 [CrossDevice] Task completed, processing next from incoming queue (${this.incomingTaskQueue.length} waiting)`),this.processIncomingTaskQueue()):this.processNextQueuedTask()}async markTaskCompletedById(e){i.debug("🔵 [CrossDevice] Marking task complete:",e),await this.updateTaskStatus(e,"completed")}processNextQueuedTask(){if(de.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug("⏸️ [CrossDevice] System still busy, waiting for completion");return}if(this.pendingTasksQueue.length===0){i.debug("✅ [CrossDevice] No pending tasks in queue");return}let n=this.pendingTasksQueue.shift();i.debug(`📤 [CrossDevice] Processing next task from queue: ${n.taskId}`),this.executeTaskImmediately(n.taskId,n.prompt,n.mode)}async startListening(e,t){let n=t||this.deviceRegistrationService.getCurrentDeviceId();if(!n){i.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=n,i.debug(`Starting listener - User: ${e}, Device: ${n}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let s=this.authService.getFirebaseAuth();if(!s?.currentUser){i.error("No authenticated Firebase user - cannot start listeners");return}if(s.currentUser.uid!==e){i.error("SECURITY: User ID mismatch! Firebase UID:",s.currentUser.uid,"Requested:",e),i.error("Refusing to start listener for different user");return}i.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,n)}catch(s){throw i.error("Failed to start listener:",s.message),s}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),i.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){i.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){i.error("No stored user ID found - cannot authenticate Firebase for listeners");return}i.debug("Found stored user ID, getting custom token from API...");try{let n=await this.authService.getCustomTokenFromAPI(e);if(t){let s=await this.authService.signInWithCustomToken(n);i.debug("Firebase authenticated successfully - UID:",s.user.uid)}}catch(n){i.warn("Firebase authentication failed:",n.message),i.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){i.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e.taskId),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}i.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,i.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),i.debug("Cross-device task UI flow triggered successfully")}catch(t){i.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){i.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(n){i.error("Failed to process task:",n.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),i.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let n=e.split("_");if(n.length!==3||n[0]!=="task")return!1;let s=n[1],o=n[2];return s.length!==13||!Number.isInteger(Number(s))||o.length!==9?!1:/^[a-z0-9]+$/.test(o)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let n=t.id,s=t.prompt,o=t.status;if(!n||!s){i.error("❌ [CrossDevice] Invalid task data (missing id or prompt)");return}if(o!=="pending"){i.debug("⏭️ [CrossDevice] Skipping non-pending task:",n,"Status:",o);return}this.incomingTaskQueue.push({taskId:n,prompt:s,snapshot:e}),i.debug(`📨 [CrossDevice] Task queued for processing: ${n}`),i.debug(` Incoming queue size: ${this.incomingTaskQueue.length}`),this.isProcessingIncoming||this.processIncomingTaskQueue()}catch(t){i.error("❌ [CrossDevice] Error in handleIncomingTask:",t.message)}}async processIncomingTaskQueue(){if(this.incomingTaskQueue.length===0){this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Incoming queue empty, processing complete");return}this.isProcessingIncoming=!0;let{taskId:e,prompt:t,snapshot:n}=this.incomingTaskQueue.shift();i.debug(`🔵 [CrossDevice] Processing task: ${e}`),i.debug(` Remaining in incoming queue: ${this.incomingTaskQueue.length}`);let s=n.val();if(i.debug("🔵 [CrossDevice] Task received, updating status to processing immediately"),await this.updateTaskStatus(e,"processing"),!this.validateTaskId(e)){i.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),i.warn("🚨 [SECURITY] Task ID:",e),i.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),i.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access"),await this.updateTaskStatus(e,"completed"),this.processIncomingTaskQueue();return}if(i.debug("✅ [SECURITY] Task ID validation passed:",e),!this.canAcceptTask()){i.warn("⚠️ [CrossDevice] Cannot accept task - execution queue is full"),await this.updateTaskStatus(e,"queue_full"),this.processIncomingTaskQueue();return}i.debug("✅ [CrossDevice] Task accepted:",e),i.debug(" Prompt:",t),this.currentlyExecutingTaskId=e,this.currentTaskId=e;let r="existing";await this.executeTask(e,t,r),this.isProcessingIncoming=!1,i.debug("✅ [CrossDevice] Task dispatched for execution, waiting for completion")}canAcceptTask(){if(de.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){let s=(mt(),Ui(ks)).MessageQueueManager.getInstance(),o=s.getQueueCount(),r=s.canAddToQueue();if(i.debug(`🔍 [CrossDevice] Queue capacity check: ${o}/5 used, hasSpace: ${r}`),!r)return!1}return!0}async executeTask(e,t,n){if(i.debug(`Executing task: ${e} with mode: ${n}`),i.debug(`Prompt to execute: ${t}`),de.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){i.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:n};this.pendingTasksQueue.push(r),i.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}i.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,n)}async executeTaskImmediately(e,t,n){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{i.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",n),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:n})})}catch(s){i.error("Task execution failed:",s.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let n=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,s={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(n,s)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){this.cleanupObservers();let t=()=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)},n=o=>{this.currentTaskId===e&&this.cleanupObservers()},s=o=>{this.currentTaskId===e&&setTimeout(()=>{this.cleanupObservers()},100)};this.once("BotResponseCompleted",t),this.once("BotResponseError",n),this.once("BotResponseStopped",s)}cleanupObservers(){this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),this.currentTaskId=null}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,n="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let s=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={taskId:s,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:n,timestamp:je,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${s}`;try{await this.firebaseAPI.writeRealtimeData(r,o),i.debug("Task submitted to device:",e)}catch(a){throw i.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([n,s])=>({id:n,...s})).filter(n=>n.isOnline&&n.id!==this.currentDeviceId)}catch(e){return i.error("Failed to get available devices:",e.message),[]}}enable(){i.debug("[CROSS DEVICE] Service enabled")}disable(){i.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){i.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Si={};ke(Si,{SnowXStreamHandlerService:()=>ds});import{EventEmitter as Il}from"events";var ds,wi=D(()=>{"use strict";ds=class extends Il{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,n,s,o){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let d=this.byteBuffer.toString("utf8");this.buffer+=d,this.rawDataReceived+=d,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(n,s,o)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(n,s,o),this.printFinalStatistics(),!this.fullResponse&&!o){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,n){if(this.isCancelled)return;let s,o=this.buffer.indexOf(`\r
493
+ `);if(o!==-1)s=o;else{let r=this.buffer.indexOf(`
494
+ `);if(r!==-1)s=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)s=a;else return}}for(;s!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,s);this.linesProcessed++,this.buffer.substring(s,s+2)===`\r
495
+ `?this.buffer=this.buffer.substring(s+2):this.buffer=this.buffer.substring(s+1);let a=r.trim();if(!a){s=this.findNextLineEnd();continue}if(a.startsWith(":")){s=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,n),s=this.findNextLineEnd()}}processDataLine(e,t,n,s){if(this.isCancelled)return;this.dataLinesFound++;let o=e.substring(6).trim();if(o==="[DONE]"){this.emit("streamEnd");return}if(o)try{let r=JSON.parse(o);if(r.choices&&r.choices.length>0){let a=r.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)s?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,n))}}catch{}}processThinkingContent(e,t,n){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let s=this.thinkingBuffer.indexOf("</think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.thinkingContent+=o,n?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",n?.(this.thinkingContent));break}else{let s=this.thinkingBuffer.indexOf("<think>");if(s!==-1){let o=this.thinkingBuffer.substring(0,s);o&&(this.regularContent+=o,this.fullResponse+=o,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(s+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,n){if(this.rawDataReceived.startsWith("data: ")){let s=this.rawDataReceived.substring(6).trim();try{let o=JSON.parse(s);o.choices&&o.choices.length>0&&o.choices[0].delta.content&&this.processThinkingContent(o.choices[0].delta.content,e,t)}catch{}}else try{let s=JSON.parse(this.rawDataReceived);s.choices?.[0]?.message?.content&&this.processThinkingContent(s.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
501
496
  `);if(e!==-1)return e;let t=this.buffer.indexOf(`
502
- `);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import bl from"axios";import{EventEmitter as Tl}from"events";import yl from"http";import Sl from"https";var Kn,mi=D(()=>{"use strict";ce();Kn=class extends Tl{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new yl.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Sl.Agent({keepAlive:!0,timeout:36e5}),this.client=bl.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=H.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(o){if(o.response?.status===429){if(n===t-1)throw new Error("Rate limit exceeded");let s=Math.pow(2,n);await new Promise(r=>setTimeout(r,s*1e3))}else throw o}throw new Error("Max retries exceeded")}buildRequest(e,t,n,o=.7,s=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:o,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:s,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,o=.9,s,r){let a=this.buildRequest(e,t,!1,n,o,s,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,n=.7,o=.9,s,r,a,l,u){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(pi(),di)),p=this.buildRequest(e,t,!0,n,o,s,r);return new Promise((m,h)=>{this.currentAbortController=new AbortController;let f=[],y=new Map,S=new d;this.client.post("/chat/completions",p,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async b=>{let w=b.data,k=b.headers["content-type"]||"",v=x=>{if(x?.index!==void 0){let P=x.index;y.has(P)||y.set(P,{});let A=y.get(P);x.id&&(A.id=x.id,A.type="function"),x.function&&(A.function||(A.function={name:"",arguments:""}),x.function.name&&(A.function.name=x.function.name),x.function.arguments&&(A.function.arguments+=x.function.arguments))}u?.(x),this.emit("tool_call_delta",x)};S.on("streamEnd",()=>{y.forEach((x,P)=>{x.id&&x.function?.name&&f.push(x)}),this.emit("done"),m({content:S.getFinalResponse(),toolCalls:f.length>0?f:void 0})}),S.on("cancelled",()=>{this.emit("canceled"),m({content:S.getFinalResponse(),toolCalls:f.length>0?f:void 0})});try{await S.processStreamingResponse(w,k,a||(()=>{}),l,v),y.forEach((x,P)=>{x.id&&x.function?.name&&f.push(x)}),this.emit("done"),m({content:S.getFinalResponse(),toolCalls:f.length>0?f:void 0})}catch(x){this.emit("error",x),h(x)}}).catch(b=>{b.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:f.length>0?f:void 0})):h(b)})})}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 wl}from"socket.io-client";import{EventEmitter as Cl}from"events";var Qn,gi=D(()=>{"use strict";ze();Qn=class c extends Cl{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=me.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=wl(t,n),this.setupEventHandlers(),new Promise((o,s)=>{let r=setTimeout(()=>{s(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),o(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),s(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var hi,fi=D(()=>{"use strict";hi={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 bi={};Ee(bi,{ServiceManager:()=>Yt});import{EventEmitter as xl}from"events";import{initializeApp as El,getApps as vi}from"firebase/app";import{getAuth as kl}from"firebase/auth";var Yt,rs=D(()=>{"use strict";Pe();mi();ce();ze();gi();bt();Do();mn();He();$();fi();Yt=class c extends xl{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=ue.getInstance(),this.networkClient=new Kn,this.authService=H.getInstance(),this.deviceRegistration=me.getInstance(),this.webSocketService=Qn.getInstance(),this.frontendWebSocketService=Y.getInstance(),this.crossDeviceService=wt.getInstance(),this.toolCalling=Ut.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||hi;if(vi().length===0?(this.firebaseApp=El(e),i.debug("Firebase app initialized")):(this.firebaseApp=vi()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=kl(this.firebaseApp),i.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),i.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Ao(),ar));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),i.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{i.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){i.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=Q[0],n={}){let{usePersonalAgent:o=!0,enableToolCalling:s=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=n;try{let l=[];if(o)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=s?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,p)=>{let m="";this.networkClient.on("data",h=>{m+=h}),this.networkClient.on("done",()=>{d(m)}),this.networkClient.on("error",p),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return 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((n,o)=>{let s=setTimeout(()=>{o(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(s),this.deviceRegistration.off("DeviceRegistrationComplete",r),n()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(s),this.deviceRegistration.off("DeviceRegistrationComplete",r),n())})}}});import*as ls from"@sentry/node";ls.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as Fl}from"commander";import Al from"react";import{render as Dl}from"@jrichman/ink";import q,{useCallback as pl,useState as ml,useEffect as gl}from"react";import{Box as xe,Text as li}from"@jrichman/ink";import hl from"ink-spinner";import Ln from"react";ce();import lc,{createContext as uc,useContext as Gt,useState as br,useCallback as Ro,useRef as Ct,useEffect as Ke,useMemo as xt}from"react";import{useApp as dc}from"@jrichman/ink";Pe();So();import we from"chalk";import ja from"ora";var de=class{static spinner=null;static formatUserMessage(e){return we.cyan("You: ")+e}static formatAssistantMessage(e){return we.green("Assistant: ")+e}static formatError(e){return we.red("Error: ")+e}static formatWarning(e){return we.yellow("Warning: ")+e}static formatInfo(e){return we.blue("Info: ")+e}static formatSuccess(e){return we.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=ja(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(we.gray("─".repeat(50)))}static printHeader(e){console.log(),console.log(we.bold.cyan(e)),console.log(we.gray("─".repeat(e.length))),console.log()}static formatTimestamp(e){return we.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return we.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(we.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};$();dt();mt();import{EventEmitter as Va}from"events";import Eo from"chalk";var Rn=class extends Va{delegate=null;personalAgentService=ue.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...o)=>{let s=String(o[0]||"");(s.includes("▸")||s.includes("→")||s.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,o)}),this.personalAgentService.on("data",o=>{if(t+=o,this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(!s.content||s.content===""?s.content=o:s.content+=o),r&&r.isStreaming&&(!r.content||r.content===""?r.content=o:r.content+=o)}}),this.personalAgentService.on("thinking",o=>{}),this.personalAgentService.on("toolExecuting",o=>{this.delegate?.usesCustomUI||console.log(`
503
- ▸ ${o}`)}),this.personalAgentService.on("tool_completed",o=>{if(!this.delegate?.usesCustomUI){let{toolName:s,success:r,error:a}=o;console.log(r!==!1?`✓ ${s}`:`✗ ${s} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",o=>{}),this.personalAgentService.on("todo_update",o=>{}),this.personalAgentService.on("operator_progress",o=>{}),this.personalAgentService.on("webview_update",o=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],s=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(o.isStreaming=!1),s&&s.isStreaming&&(s.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",o=>{console.error(`
504
- Error:`,o.message||o),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",o=>{if(i.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(o.content&&o.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${o.content.substring(0,50)}..."`),s.content=o.content,s.originalContent=o.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),o.completeWithTools&&(s.metadata={toolResults:o.completeWithTools}),s.isStreaming=!1,i.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(o.content&&o.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${o.content.substring(0,50)}..."`),r.content=o.content,r.originalContent=o.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),o.completeWithTools&&(r.metadata={toolResults:o.completeWithTools}),r.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,n=!0){if(!this.delegate||!e.trim())return;let o=new ye,s=e.trim(),r=o.count(s);if(r>pt){console.log(de.formatError(`Prompt too large (${r.toLocaleString()} tokens). Please reduce it to ${pt.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let u=ke.getInstance();u.addToQueue({content:s,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Eo.blue(`⚡ Message queued (${u.getQueueCount()} in queue)`)),console.log(Eo.dim(" Your feedback will be sent when AI completes current task"))):console.log(Eo.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await yt.getInstance().captureScreen(),a?i.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):i.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let l=[];t&&t.length>0&&(l.push(...t),i.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&l.push(a),this.delegate.currentInput="";try{n?await this.processStreamingMessage(l.length>0?l:void 0):await this.processNonStreamingMessage(l.length>0?l:void 0)}catch(u){console.error(de.formatError(`Message failed: ${u.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",u.message)}}async processStreamingMessage(e){if(this.delegate)try{i.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(s=>!(s.isStreaming||s.role==="system"||!s.content||typeof s.content=="string"&&s.content.trim().length===0)).map(s=>({role:s.role,content:s.content})),n=this.delegate.fullConversationHistory.filter(s=>s.role==="user"),o=n[n.length-1];if(o)try{let s={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(o.content,t,this.delegate.selectedModel,.7,!0,void 0,e,s),i.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(s){throw i.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${s.message}`),s}}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(o=>o.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let s=t.content;s.trim().length>0&&(s+=`
497
+ `);if(t!==-1)return t;let n=this.buffer.indexOf("\r");return n!==-1?n:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import Pl from"axios";import{EventEmitter as Al}from"events";import Dl from"http";import Nl from"https";var to,Ci=D(()=>{"use strict";le();to=class extends Al{client;baseURL="https://snowx.ai/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Dl.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Nl.Agent({keepAlive:!0,timeout:36e5}),this.client=Pl.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=z.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let n=0;n<t;n++)try{return await e()}catch(s){if(s.response?.status===429){if(n===t-1)throw new Error("Rate limit exceeded");let o=Math.pow(2,n);await new Promise(r=>setTimeout(r,o*1e3))}else throw s}throw new Error("Max retries exceeded")}buildRequest(e,t,n,s=.7,o=.9,r,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:n,temperature:t.name.includes("o4-mini")?void 0:s,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:o,reasoning_effort:t.reasoningEffort,tools:r,tool_choice:a}}async performNonStreamingRequest(e,t,n=.7,s=.9,o,r){let a=this.buildRequest(e,t,!1,n,s,o,r);try{let u=(await this.executeWithRetry(async()=>{let{data: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,n=.7,s=.9,o,r,a,l,u){let{SnowXStreamHandlerService:d}=await Promise.resolve().then(()=>(wi(),Si)),p=this.buildRequest(e,t,!0,n,s,o,r);return new Promise((m,g)=>{this.currentAbortController=new AbortController;let h=[],y=new Map,T=new d;this.client.post("/chat/completions",p,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async S=>{let w=S.data,E=S.headers["content-type"]||"",b=C=>{if(C?.index!==void 0){let P=C.index;y.has(P)||y.set(P,{});let R=y.get(P);C.id&&(R.id=C.id,R.type="function"),C.function&&(R.function||(R.function={name:"",arguments:""}),C.function.name&&(R.function.name=C.function.name),C.function.arguments&&(R.function.arguments+=C.function.arguments))}u?.(C),this.emit("tool_call_delta",C)};T.on("streamEnd",()=>{y.forEach((C,P)=>{C.id&&C.function?.name&&h.push(C)}),this.emit("done"),m({content:T.getFinalResponse(),toolCalls:h.length>0?h:void 0})}),T.on("cancelled",()=>{this.emit("canceled"),m({content:T.getFinalResponse(),toolCalls:h.length>0?h:void 0})});try{await T.processStreamingResponse(w,E,a||(()=>{}),l,b),y.forEach((C,P)=>{C.id&&C.function?.name&&h.push(C)}),this.emit("done"),m({content:T.getFinalResponse(),toolCalls:h.length>0?h:void 0})}catch(C){this.emit("error",C),g(C)}}).catch(S=>{S.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:h.length>0?h:void 0})):g(S)})})}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 Rl}from"socket.io-client";import{EventEmitter as Ml}from"events";var no,xi=D(()=>{"use strict";Xe();no=class c extends Ml{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=me.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){if(this.isConnected)return!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),!this.deviceId)return!1;try{let n={transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:this.maxReconnectAttempts,reconnectionDelay:1e3,timeout:1e4,query:{userId:e,deviceId:this.deviceId,deviceType:"cli",platform:process.platform}};return this.socket=Rl(t,n),this.setupEventHandlers(),new Promise((s,o)=>{let r=setTimeout(()=>{o(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(r),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),s(!0)}),this.socket?.on("connect_error",a=>{clearTimeout(r),console.error("❌ WebSocket connection error:",a),o(a)})})}catch(n){return console.error("❌ Failed to connect WebSocket:",n),!1}}setupEventHandlers(){this.socket&&(this.socket.on("connect",()=>{this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),this.registerDevice()}),this.socket.on("disconnect",e=>{this.isConnected=!1,this.emit("disconnected",e),e==="io server disconnect"&&this.attemptReconnect()}),this.socket.on("connect_error",e=>{console.error("❌ WebSocket connection error:",e),this.emit("connection_error",e),this.attemptReconnect()}),this.socket.on("reconnect",e=>{this.isConnected=!0,this.emit("reconnected",e)}),this.socket.on("reconnect_error",e=>{console.error("❌ WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("❌ WebSocket reconnection failed after max attempts"),this.emit("reconnection_failed")}),this.socket.on("cross_device_message",e=>{this.emit("cross_device_message",e),this.handleCrossDeviceMessage(e)}),this.socket.on("conversation_sync",e=>{this.emit("conversation_sync",e),this.handleConversationSync(e)}),this.socket.on("device_status_update",e=>{this.emit("device_status_update",e),this.handleDeviceStatusUpdate(e)}),this.socket.on("typing_indicator",e=>{this.emit("typing_indicator",e)}),this.socket.on("notification",e=>{this.emit("notification",e),this.handleNotification(e)}),this.socket.on("user_activity",e=>{this.emit("user_activity",e)}),this.socket.on("tool_execution",e=>{this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("❌ Max reconnection attempts reached");return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.socket&&!this.isConnected&&this.socket.connect()},e)}registerDevice(){if(!this.deviceId){console.error("Cannot register device without device ID");return}let e={id:this.deviceId,name:"Orion CLI",type:"cli",platform:process.platform,lastSeen:new Date,isOnline:!0};this.send("register_device",e)}handleCrossDeviceMessage(e){}handleConversationSync(e){}handleDeviceStatusUpdate(e){}handleNotification(e){}send(e,t){if(!this.isConnected||!this.socket)return;let n={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};this.socket.emit(e,n)}sendCrossDeviceMessage(e,t,n){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:n,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,n){this.send("conversation_sync",{conversationId:e,action:t,data:n,timestamp:Date.now()})}syncToolExecution(e,t,n){this.send("tool_execution",{toolName:e,status:t,result:n,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var Ei,ki=D(()=>{"use strict";Ei={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 Pi={};ke(Pi,{ServiceManager:()=>en});import{EventEmitter as _l}from"events";import{initializeApp as Ol,getApps as Ii}from"firebase/app";import{getAuth as Fl}from"firebase/auth";var en,ps=D(()=>{"use strict";Ae();Ci();le();Xe();xi();yt();Lo();vn();qe();L();ki();en=class c extends _l{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=de.getInstance(),this.networkClient=new to,this.authService=z.getInstance(),this.deviceRegistration=me.getInstance(),this.webSocketService=no.getInstance(),this.frontendWebSocketService=Z.getInstance(),this.crossDeviceService=xt.getInstance(),this.toolCalling=Wt.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||Ei;if(Ii().length===0?(this.firebaseApp=Ol(e),i.debug("Firebase app initialized")):(this.firebaseApp=Ii()[0],i.debug("Using existing Firebase app")),this.firebaseAuth=Fl(this.firebaseApp),i.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),i.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(Uo(),br));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),i.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{i.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){i.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){if(this.webSocketService.isWebSocketConnected())return!0;let e=this.authService.getUserId();if(!e)return!1;try{return await this.webSocketService.connect(e)}catch{return!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=Y[0],n={}){let{usePersonalAgent:s=!0,enableToolCalling:o=this.options.enableToolCalling,temperature:r=.7,stream:a=!0}=n;try{let l=[];if(s)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,r,a,this.authService.getUserId()||void 0);{let u=o?this.toolCalling.getAvailableTools():void 0;return a?new Promise((d,p)=>{let m="";this.networkClient.on("data",g=>{m+=g}),this.networkClient.on("done",()=>{d(m)}),this.networkClient.on("error",p),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,r,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:n}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return Y.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){try{this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&this.toolCalling.stopAllRunningTools?.(),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown")}catch{}}async waitForDeviceRegistration(e=1e4){if(!this.deviceRegistration.getCurrentDeviceId())return new Promise((n,s)=>{let o=setTimeout(()=>{s(new Error(`Device registration timeout after ${e}ms`))},e),r=l=>{clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n()};this.deviceRegistration.on("DeviceRegistrationComplete",r),this.deviceRegistration.getCurrentDeviceId()&&(clearTimeout(o),this.deviceRegistration.off("DeviceRegistrationComplete",r),n())})}}});import*as fs from"@sentry/node";fs.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:"production"});import{Command as zl}from"commander";import Ll from"react";import{render as Wl}from"@jrichman/ink";import V,{useCallback as Sl,useState as wl,useEffect as bi,useMemo as Cl,useRef as xl}from"react";import{Box as Ee,Text as Ti}from"@jrichman/ink";import El from"ink-spinner";import co from"terminal-link";import{homedir as Li}from"os";function vs(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",Li())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Wi(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function tn(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,s)=>{let o=s;return!Wi(s)&&!s.startsWith("file://")&&(s.startsWith("/")||s.startsWith("~")||/\.[a-z]{2,4}$/i.test(s))&&(o=vs(s)),co(n,o,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(s)?t:co(t,t,{fallback:(o,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,s=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(s)||s.includes("http"))return t;let o=vs(t);return co(t,o,{fallback:(r,a)=>r})}),e}function nn(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(c))!==null;){let r=n[1].split(`
498
+ `).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 s=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return s=s.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:s}}function bs(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,s;for(;(s=e.exec(c))!==null;){let r=s[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],d=l[2];n.has(d)||(n.add(d),t.push({name:u,path:d}))}}let o=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return o=o.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:o}}function Ts(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=tn(e),e}function ys(c){return c.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Gn from"react";le();import yc,{createContext as Sc,useContext as zt,useState as Ar,useCallback as Bo,useRef as Et,useEffect as Je,useMemo as kt}from"react";import{useApp as wc}from"@jrichman/ink";Ae();Do();import Ce from"chalk";import sc from"ora";var pe=class{static spinner=null;static formatUserMessage(e){return Ce.cyan("You: ")+e}static formatAssistantMessage(e){return Ce.green("Assistant: ")+e}static formatError(e){return Ce.red("Error: ")+e}static formatWarning(e){return Ce.yellow("Warning: ")+e}static formatInfo(e){return Ce.blue("Info: ")+e}static formatSuccess(e){return Ce.green("✓ ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=sc(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(Ce.gray("".repeat(50)))}static printHeader(e){console.log(),console.log(Ce.bold.cyan(e)),console.log(Ce.gray("".repeat(e.length))),console.log()}static formatTimestamp(e){return Ce.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return Ce.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(Ce.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};L();mt();ht();import{EventEmitter as rc}from"events";import _o from"chalk";var Fn=class extends rc{delegate=null;personalAgentService=de.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",n=console.log;this.delegate?.usesCustomUI||(console.log=(...s)=>{let o=String(s[0]||"");(o.includes("▸")||o.includes("→")||o.includes("✎"))&&t&&(e&&(e=!1),t=""),n.apply(console,s)}),this.personalAgentService.on("data",s=>{if(t+=s,this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(!o.content||o.content===""?o.content=s:o.content+=s),r&&r.isStreaming&&(!r.content||r.content===""?r.content=s:r.content+=s)}}),this.personalAgentService.on("thinking",s=>{}),this.personalAgentService.on("toolExecuting",s=>{this.delegate?.usesCustomUI||console.log(`
499
+ ${s}`)}),this.personalAgentService.on("tool_completed",s=>{if(!this.delegate?.usesCustomUI){let{toolName:o,success:r,error:a}=s;console.log(r!==!1?`✓ ${o}`:`✗ ${o} failed${a?": "+a.substring(0,50):""}`)}}),this.personalAgentService.on("toolComplete",s=>{}),this.personalAgentService.on("todo_update",s=>{}),this.personalAgentService.on("operator_progress",s=>{}),this.personalAgentService.on("webview_update",s=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let s=this.delegate.messages[this.delegate.messages.length-1],o=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];s&&s.isStreaming&&(s.isStreaming=!1),o&&o.isStreaming&&(o.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",s=>{console.error(`
500
+ ❌ Error:`,s.message||s),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",s=>{if(i.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let o=this.delegate.messages[this.delegate.messages.length-1],r=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];o&&o.isStreaming&&(s.content&&s.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${s.content.substring(0,50)}..."`),o.content=s.content,o.originalContent=s.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),s.completeWithTools&&(o.metadata={toolResults:s.completeWithTools}),o.isStreaming=!1,i.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),r&&r.isStreaming&&(s.content&&s.content.trim()?(i.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${s.content.substring(0,50)}..."`),r.content=s.content,r.originalContent=s.content):i.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),s.completeWithTools&&(r.metadata={toolResults:s.completeWithTools}),r.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t,n=!0){if(!this.delegate||!e.trim())return;let s=new Se,o=e.trim(),r=s.count(o);if(r>gt){console.log(pe.formatError(`Prompt too large (${r.toLocaleString()} tokens). Please reduce it to ${gt.toLocaleString()} tokens or less.`));return}if(this.delegate.isLoading){let u=Ie.getInstance();u.addToQueue({content:o,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(_o.blue(`⚡ Message queued (${u.getQueueCount()} in queue)`)),console.log(_o.dim(" Your feedback will be sent when AI completes current task"))):console.log(_o.yellow("⚠️ Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let a=null;this.delegate.isVisionEnabled&&(a=await wt.getInstance().captureScreen(),a?i.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${a.length} chars`):i.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision"));let l=[];t&&t.length>0&&(l.push(...t),i.debug(`[MESSAGE HANDLER] Received ${t.length} image attachments`)),a&&l.push(a),this.delegate.currentInput="";try{n?await this.processStreamingMessage(l.length>0?l:void 0):await this.processNonStreamingMessage(l.length>0?l:void 0)}catch(u){console.error(pe.formatError(`Message failed: ${u.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",u.message)}}async processStreamingMessage(e){if(this.delegate)try{i.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(o=>!(o.isStreaming||o.role==="system"||!o.content||typeof o.content=="string"&&o.content.trim().length===0)).map(o=>({role:o.role,content:o.content})),n=this.delegate.fullConversationHistory.filter(o=>o.role==="user"),s=n[n.length-1];if(s)try{let o={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(s.content,t,this.delegate.selectedModel,.7,!0,void 0,e,o),i.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(o){throw i.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${o.message}`),o}}async processNonStreamingMessage(e){throw new Error("processNonStreamingMessage is deprecated - PersonalAgentService handles all conversations")}stopStreaming(){if(this.currentStreamingTask&&(this.currentStreamingTask.abort(),this.currentStreamingTask=null),this.delegate){let e="",t=this.delegate.messages.find(s=>s.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let o=t.content;o.trim().length>0&&(o+=`
505
501
 
506
- `),s+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=s}t.isStreaming=!1;let o=this.delegate.fullConversationHistory.find(s=>s.isStreaming);o&&(o.content=t.content,o.isStreaming=!1)}this.delegate.isLoading=!1,ue.getInstance().stopStreaming().catch(o=>{i.error("[MESSAGE HANDLER] Error in comprehensive stop:",o)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Pe();dt();bt();Do();io();He();be();Ie();var nc=0;function Z(){return`msg-${Date.now()}-${++nc}`}function cr(c){return c.content||c.text||"Untitled task"}import{useEffect as oc,useRef as Ht,useCallback as lr}from"react";function ur({personalAgent:c,handlers:e}){let t=Ht(""),n=Ht(!0),o=Ht(!1),s=Ht(!1),r=Ht(null),a=100,l=lr(()=>{if(r.current=null,s.current=!1,!o.current||!n.current)return;o.current=!1;let d=t.current;e.onMessagesUpdate(p=>p.map((m,h)=>m.role==="assistant"&&!p.slice(h+1).some(y=>y.role==="assistant")?{...m,content:d}:m))},[e]);return oc(()=>{n.current=!0,t.current="";let d=v=>{e.onConversationIdReceived(v)},p=()=>{e.onLoadingMessageChange("Processing")},m=v=>{t.current+=v,o.current=!0,s.current||(s.current=!0,r.current=setTimeout(l,a))},h=v=>{let x=typeof v=="string"?v:v.name,P=typeof v=="string"?`tool-${Date.now()}`:v.toolCallId,A=typeof v=="string"?void 0:v.arguments,_=x.toLowerCase().replace(/_/g,"")==="todowrite";e.onActiveToolsUpdate(N=>{let C=new Map(N);return C.set(P,{toolCallId:P,name:x,arguments:A,startTime:new Date,state:"running"}),C}),_||e.onLoadingMessageChange("Processing")},f=v=>{if(!v||!v.toolName)return;let x=v.toolId||`tool-${v.toolName}-${Date.now()}`,P=v.success===!1||v.error,A=v.error||v.result?.error||"",B=v.arguments,_="";v.result&&(typeof v.result=="string"?_=v.result:Array.isArray(v.result)?_=v.result.map(g=>typeof g=="string"?g:g&&typeof g=="object"?g.text||g.content||JSON.stringify(g):"").join(""):v.result.output?_=typeof v.result.output=="string"?v.result.output:JSON.stringify(v.result.output,null,2):v.result.content?_=v.result.content:_=JSON.stringify(v.result,null,2));let N=_.length>500?_.substring(0,500)+`
507
- ...(truncated)`:_,C=`<context>
508
- ${_}
509
- </context>`,E=P?"failed":"completed";e.onActiveToolsUpdate(g=>{let T=new Map(g),I=x;if(!T.has(x)){for(let[M,O]of T.entries())if(O.name===v.toolName&&O.state==="running"){I=M;break}}if(T.has(I)){let M=T.get(I);T.set(I,{...M,arguments:M.arguments||B,state:E,output:N,error:P?A:void 0})}else T.set(I,{toolCallId:I,name:v.toolName,arguments:B,startTime:new Date,state:E,output:N,error:P?A:void 0});return T}),e.onMessagesUpdate(g=>g.map((T,I)=>{if(T.role==="assistant"&&!g.slice(I+1).some(O=>O.role==="assistant")){let O=T.metadata?.toolResults;return{...T,metadata:{...T.metadata,toolResults:O?O+`
510
- `+C:C}}}return T}))},y=v=>{!v||!v.toolCallId||e.onActiveToolsUpdate(x=>{let P=new Map(x),A=P.get(v.toolCallId);return A&&P.set(v.toolCallId,{...A,arguments:v.arguments}),P})},S=()=>{if(o.current){o.current=!1,s.current=!1;let v=t.current;e.onMessagesUpdate(x=>x.map((P,A)=>P.role==="assistant"&&!x.slice(A+1).some(_=>_.role==="assistant")?{...P,content:v}:P))}e.onLoadingChange(!1),e.onActiveToolsUpdate(()=>new Map),t.current=""},b=v=>{e.onError(v.message||"Unknown error"),e.onLoadingChange(!1),e.onActiveToolsUpdate(()=>new Map),t.current=""},w=v=>{e.onConfirmationRequest({id:v.confirmationId,type:v.type,title:v.title,message:v.message,command:v.command,targets:v.targets,isDestructive:v.isDestructive,timeout:v.isDestructive?v.timeout||3e4:void 0})},k=v=>{e.onTodoUpdate(v)};return c.on("conversation_id_received",d),c.on("thinking",p),c.on("data",m),c.on("toolExecuting",h),c.on("tool_completed",f),c.on("tool_args_update",y),c.on("done",S),c.on("error",b),c.on("confirmation_request",w),c.on("todo_update",k),()=>{n.current=!1,r.current&&(clearTimeout(r.current),r.current=null),c.off("conversation_id_received",d),c.off("thinking",p),c.off("data",m),c.off("toolExecuting",h),c.off("tool_completed",f),c.off("tool_args_update",y),c.off("done",S),c.off("error",b),c.off("confirmation_request",w),c.off("todo_update",k)}},[c,e,l]),{resetContent:lr(()=>{t.current=""},[])}}import{useState as sc,useEffect as dr,useCallback as pr,useMemo as mr,useRef as No}from"react";function gr({queueManager:c,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:o,onCrossDeviceTask:s}){let[r,a]=sc([]),l=No(n),u=No(o),d=No(s);dr(()=>{l.current=n,u.current=o,d.current=s},[n,o,s]);let p=mr(()=>r.filter(S=>!S.isCrossDeviceTask),[r]),m=mr(()=>r.filter(S=>S.isCrossDeviceTask),[r]),h=r.length>0,f=pr((S,b=[])=>c.addToQueue({content:S,imageUrls:b,attachments:[],model:u.current.name}),[c]),y=pr(()=>{if(!c.hasQueuedMessages())return null;let S=c.processNextMessage();return S&&c.startProcessing(),S},[c]);return dr(()=>{let S=k=>{a(k)},b=()=>{},w=k=>{if(l.current){c.addToQueue({content:k.prompt,imageUrls:[],attachments:[],model:u.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:k.taskId})||d.current(k.taskId,"");return}d.current(k.taskId,k.prompt)};return c.on("queue:updated",S),e.on("feedback:sent",b),t.on("CrossDeviceTaskSendMessage",w),()=>{c.off("queue:updated",S),e.off("feedback:sent",b),t.off("CrossDeviceTaskSendMessage",w)}},[c,e,t]),{queuedMessages:r,regularQueuedMessages:p,crossDeviceTasks:m,addToQueue:f,processNextMessage:y,hasQueuedMessages:h}}import{useState as rc,useEffect as ic}from"react";function hr({subAgentManager:c}){let[e,t]=rc(new Map);return ic(()=>{let n=()=>{let o=c.getOperations();t(new Map(o))};return c.on("spawn_started",n),c.on("agent_started",n),c.on("agent_streaming",n),c.on("agent_completed",n),c.on("spawn_completed",n),c.on("progress",n),()=>{c.off("spawn_started",n),c.off("agent_started",n),c.off("agent_streaming",n),c.off("agent_completed",n),c.off("spawn_completed",n),c.off("progress",n)}},[c]),{subAgentOperations:e}}import{useState as ac,useEffect as fr,useRef as cc}from"react";function vr(){let[c,e]=ac(null),t=cc(null);return fr(()=>{t.current=c},[c]),fr(()=>{if(!c||c.todos.length===0)return;let n=c.todos.filter(r=>r.status==="completed").length,o=c.todos.length;if(n===o&&o>0){let r=setTimeout(()=>{e(null),t.current=null},3e3);return()=>clearTimeout(r)}},[c]),{todoList:c,setTodoList:e,todoListRef:t}}var $e=uc(null);function Mo({children:c,initialProjectPath:e}){let t=e||process.cwd(),{exit:n}=dc(),o=xt(()=>({authService:H.getInstance(),personalAgent:ue.getInstance(),queueManager:ke.getInstance(),frontendWS:Y.getInstance(),crossDevice:wt.getInstance(),subAgentManager:Ot.getInstance()}),[]);Ke(()=>(F.enableCustomUI(),()=>F.disableCustomUI()),[]);let s=xt(()=>Q.find(g=>g.name===Fe.string("selectedPersonalModel"))||Q.find(g=>g.name==="snowx-c5")||Q[0],[]),[r,a]=br({messages:[{id:Z(),role:"system",content:`Welcome to Orion
502
+ `),o+="⏹️ **[STOPPED]** - Operation was cancelled by user request.",t.content=o}t.isStreaming=!1;let s=this.delegate.fullConversationHistory.find(o=>o.isStreaming);s&&(s.content=t.content,s.isStreaming=!1)}this.delegate.isLoading=!1,de.getInstance().stopStreaming().catch(s=>{i.error("[MESSAGE HANDLER] Error in comprehensive stop:",s)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};Ae();mt();yt();Lo();ho();qe();be();Pe();var mc=0;function ee(){return`msg-${Date.now()}-${++mc}`}function Tr(c){return c.content||c.text||"Untitled task"}import{useEffect as gc,useRef as qt,useCallback as yr}from"react";function Sr({personalAgent:c,handlers:e}){let t=qt(""),n=qt(!0),s=qt(!1),o=qt(!1),r=qt(null),a=100,l=yr(()=>{if(r.current=null,o.current=!1,!s.current||!n.current)return;s.current=!1;let d=t.current;e.onMessagesUpdate(p=>p.map((m,g)=>m.role==="assistant"&&!p.slice(g+1).some(y=>y.role==="assistant")?{...m,content:d}:m))},[e]);return gc(()=>{n.current=!0,t.current="";let d=b=>{e.onConversationIdReceived(b)},p=()=>{e.onLoadingMessageChange("Processing")},m=b=>{t.current+=b,s.current=!0,o.current||(o.current=!0,r.current=setTimeout(l,a))},g=b=>{let C=typeof b=="string"?b:b.name,P=typeof b=="string"?`tool-${Date.now()}`:b.toolCallId,R=typeof b=="string"?void 0:b.arguments,j=C.toLowerCase().replace(/_/g,"")==="todowrite";e.onActiveToolsUpdate(q=>{let N=new Map(q);return N.set(P,{toolCallId:P,name:C,arguments:R,startTime:new Date,state:"running"}),N}),j||e.onLoadingMessageChange("Processing")},h=b=>{if(!b||!b.toolName)return;let C=b.toolId||`tool-${b.toolName}-${Date.now()}`,P=b.success===!1||b.error,R=b.error||b.result?.error||"",O=b.arguments,j="";b.result&&(typeof b.result=="string"?j=b.result:Array.isArray(b.result)?j=b.result.map(f=>typeof f=="string"?f:f&&typeof f=="object"?f.text||f.content||JSON.stringify(f):"").join(""):b.result.output?j=typeof b.result.output=="string"?b.result.output:JSON.stringify(b.result.output,null,2):b.result.content?j=b.result.content:j=JSON.stringify(b.result,null,2));let q=j.length>500?j.substring(0,500)+`
503
+ ...(truncated)`:j,N=`<context>
504
+ ${j}
505
+ </context>`,k=P?"failed":"completed";e.onActiveToolsUpdate(f=>{let v=new Map(f),x=C;if(!v.has(C)){for(let[U,A]of v.entries())if(A.name===b.toolName&&A.state==="running"){x=U;break}}if(v.has(x)){let U=v.get(x);v.set(x,{...U,arguments:U.arguments||O,state:k,output:q,error:P?R:void 0})}else v.set(x,{toolCallId:x,name:b.toolName,arguments:O,startTime:new Date,state:k,output:q,error:P?R:void 0});return v}),e.onMessagesUpdate(f=>f.map((v,x)=>{if(v.role==="assistant"&&!f.slice(x+1).some(A=>A.role==="assistant")){let A=v.metadata?.toolResults;return{...v,metadata:{...v.metadata,toolResults:A?A+`
506
+ `+N:N}}}return v}))},y=b=>{!b||!b.toolCallId||e.onActiveToolsUpdate(C=>{let P=new Map(C),R=P.get(b.toolCallId);return R&&P.set(b.toolCallId,{...R,arguments:b.arguments}),P})},T=()=>{if(s.current){s.current=!1,o.current=!1;let b=t.current;e.onMessagesUpdate(C=>C.map((P,R)=>P.role==="assistant"&&!C.slice(R+1).some(j=>j.role==="assistant")?{...P,content:b}:P))}e.onLoadingChange(!1),e.onActiveToolsUpdate(()=>new Map),t.current=""},S=b=>{e.onError(b.message||"Unknown error"),e.onLoadingChange(!1),e.onActiveToolsUpdate(()=>new Map),t.current=""},w=b=>{e.onConfirmationRequest({id:b.confirmationId,type:b.type,title:b.title,message:b.message,command:b.command,targets:b.targets,isDestructive:b.isDestructive,timeout:b.isDestructive?b.timeout||3e4:void 0})},E=b=>{e.onTodoUpdate(b)};return c.on("conversation_id_received",d),c.on("thinking",p),c.on("data",m),c.on("toolExecuting",g),c.on("tool_completed",h),c.on("tool_args_update",y),c.on("done",T),c.on("error",S),c.on("confirmation_request",w),c.on("todo_update",E),()=>{n.current=!1,r.current&&(clearTimeout(r.current),r.current=null),c.off("conversation_id_received",d),c.off("thinking",p),c.off("data",m),c.off("toolExecuting",g),c.off("tool_completed",h),c.off("tool_args_update",y),c.off("done",T),c.off("error",S),c.off("confirmation_request",w),c.off("todo_update",E)}},[c,e,l]),{resetContent:yr(()=>{t.current=""},[])}}import{useState as hc,useEffect as wr,useCallback as Cr,useMemo as xr,useRef as Wo}from"react";function Er({queueManager:c,frontendWS:e,crossDevice:t,isLoading:n,selectedModel:s,onCrossDeviceTask:o}){let[r,a]=hc([]),l=Wo(n),u=Wo(s),d=Wo(o);wr(()=>{l.current=n,u.current=s,d.current=o},[n,s,o]);let p=xr(()=>r.filter(T=>!T.isCrossDeviceTask),[r]),m=xr(()=>r.filter(T=>T.isCrossDeviceTask),[r]),g=r.length>0,h=Cr((T,S=[])=>c.addToQueue({content:T,imageUrls:S,attachments:[],model:u.current.name}),[c]),y=Cr(()=>{if(!c.hasQueuedMessages())return null;let T=c.processNextMessage();return T&&c.startProcessing(),T},[c]);return wr(()=>{let T=E=>{a(E)},S=()=>{},w=E=>{if(l.current){c.addToQueue({content:E.prompt,imageUrls:[],attachments:[],model:u.current.name,isCrossDeviceTask:!0,crossDeviceTaskId:E.taskId})||d.current(E.taskId,"");return}d.current(E.taskId,E.prompt)};return c.on("queue:updated",T),e.on("feedback:sent",S),t.on("CrossDeviceTaskSendMessage",w),()=>{c.off("queue:updated",T),e.off("feedback:sent",S),t.off("CrossDeviceTaskSendMessage",w)}},[c,e,t]),{queuedMessages:r,regularQueuedMessages:p,crossDeviceTasks:m,addToQueue:h,processNextMessage:y,hasQueuedMessages:g}}import{useState as fc,useEffect as vc}from"react";function kr({subAgentManager:c}){let[e,t]=fc(new Map);return vc(()=>{let n=()=>{let s=c.getOperations();t(new Map(s))};return c.on("spawn_started",n),c.on("agent_started",n),c.on("agent_streaming",n),c.on("agent_completed",n),c.on("spawn_completed",n),c.on("progress",n),()=>{c.off("spawn_started",n),c.off("agent_started",n),c.off("agent_streaming",n),c.off("agent_completed",n),c.off("spawn_completed",n),c.off("progress",n)}},[c]),{subAgentOperations:e}}import{useState as bc,useEffect as Ir,useRef as Tc}from"react";function Pr(){let[c,e]=bc(null),t=Tc(null);return Ir(()=>{t.current=c},[c]),Ir(()=>{if(!c||c.todos.length===0)return;let n=c.todos.filter(r=>r.status==="completed").length,s=c.todos.length;if(n===s&&s>0){let r=setTimeout(()=>{e(null),t.current=null},3e3);return()=>clearTimeout(r)}},[c]),{todoList:c,setTodoList:e,todoListRef:t}}var Ue=Sc(null);function Ho({children:c,initialProjectPath:e}){let t=e||process.cwd(),{exit:n}=wc(),s=kt(()=>({authService:z.getInstance(),personalAgent:de.getInstance(),queueManager:Ie.getInstance(),frontendWS:Z.getInstance(),crossDevice:xt.getInstance(),subAgentManager:Ft.getInstance()}),[]);Je(()=>(F.enableCustomUI(),()=>F.disableCustomUI()),[]);let o=kt(()=>Y.find(f=>f.name===Fe.string("selectedPersonalModel"))||Y.find(f=>f.name==="snowx-c5")||Y[0],[]),[r,a]=Ar({messages:[{id:ee(),role:"system",content:`Welcome to Orion
511
507
 
512
508
  Your autonomous on-device AI agent.
513
509
  Current project path: ${t}
514
510
 
515
- Type a message to start.`,timestamp:Date.now()}],conversationId:null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,todoList:null}),l=Ct(r.isLoading),u=Ct(r.messages),d=Ct(r.conversationId),p=Ct(s),m=Ct(!1);Ke(()=>{l.current=r.isLoading,u.current=r.messages,d.current=r.conversationId},[r.isLoading,r.messages,r.conversationId]);let{todoList:h,setTodoList:f}=vr();Ke(()=>{a(g=>({...g,todoList:h}))},[h]),Ke(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let g=setTimeout(()=>{let I=[{id:Z(),role:"system",content:`Welcome to Orion
511
+ Type a message to start.`,timestamp:Date.now()}],conversationId:null,conversationTitleGenerated:!1,isLoading:!1,loadingMessage:"Processing",activeTools:new Map,subAgentOperations:new Map,pendingConfirmation:null,todoList:null}),l=Et(r.isLoading),u=Et(r.messages),d=Et(r.conversationId),p=Et(o),m=Et(!1);Je(()=>{l.current=r.isLoading,u.current=r.messages,d.current=r.conversationId},[r.isLoading,r.messages,r.conversationId]);let{todoList:g,setTodoList:h}=Pr();Je(()=>{a(f=>({...f,todoList:g}))},[g]),Je(()=>{if(process.env.MOCK_MESSAGES!=="true")return;let f=setTimeout(()=>{let x=[{id:ee(),role:"system",content:`Welcome to Orion
516
512
 
517
513
  Your autonomous on-device AI agent.
518
514
  Current project path: /mock/project
519
515
 
520
- Type a message to start.`,timestamp:Date.now()},{id:Z(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:Z(),role:"assistant",content:`## Heading Level 2
516
+ Type a message to start.`,timestamp:Date.now()},{id:ee(),role:"user",content:"Show me all UI components for testing the chatbox",timestamp:Date.now()+100},{id:ee(),role:"assistant",content:`## Heading Level 2
521
517
 
522
518
  ### Heading Level 3
523
519
 
@@ -584,66 +580,78 @@ package.json
584
580
  Run tests
585
581
  Check build
586
582
  Deploy to staging
587
- </suggestions>`,timestamp:Date.now()+200},{id:Z(),role:"system",content:"[!] This is an error/warning system message",timestamp:Date.now()+300},{id:Z(),role:"user",content:`Another user message with
583
+ </suggestions>`,timestamp:Date.now()+200},{id:ee(),role:"system",content:"[!] This is an error/warning system message",timestamp:Date.now()+300},{id:ee(),role:"user",content:`Another user message with
588
584
  multiple lines
589
- to test multiline rendering`,timestamp:Date.now()+400},{id:Z(),role:"assistant",content:"Short assistant response with `code` and **bold**.",timestamp:Date.now()+500},...Array.from({length:20},(z,K)=>({id:Z(),role:K%2===0?"user":"assistant",content:K%2===0?`User message #${K+1}: This is a test message to fill up the chat for scroll testing.`:`Assistant response #${K+1}: Here's a longer response with some **markdown** and \`code\` to make it more realistic.
585
+ to test multiline rendering`,timestamp:Date.now()+400},{id:ee(),role:"assistant",content:"Short assistant response with `code` and **bold**.",timestamp:Date.now()+500},...Array.from({length:20},(M,_)=>({id:ee(),role:_%2===0?"user":"assistant",content:_%2===0?`User message #${_+1}: This is a test message to fill up the chat for scroll testing.`:`Assistant response #${_+1}: Here's a longer response with some **markdown** and \`code\` to make it more realistic.
590
586
 
591
587
  This response has multiple paragraphs to take up more space.
592
588
 
593
589
  - Item 1
594
590
  - Item 2
595
- - Item 3`,timestamp:Date.now()+600+K*100}))],M={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},O=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(z=>({...z,messages:I,todoList:M,activeTools:O,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(g)},[]);let[y]=br(()=>{let g={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:s,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Rn(g)});Ke(()=>{let g=r.messages.map(T=>({role:T.role,content:T.content,timestamp:new Date(T.timestamp||Date.now()),...T.tool&&{tool:T.tool},...T.toolOutput&&{toolOutput:T.toolOutput}}));y.setDelegate({messages:g,fullConversationHistory:g,isLoading:r.isLoading,currentInput:"",selectedModel:p.current,isVisionEnabled:m.current,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[r.messages,r.isLoading,r.conversationId,y]);let S=Ct(null),b=Ro(async(g,T=[])=>{if(l.current){o.queueManager.addToQueue({content:g,imageUrls:T,attachments:[],model:p.current.name})||a(Te=>({...Te,messages:[...Te.messages,{id:Z(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let I=Date.now(),M={id:Z(),role:"user",content:g,timestamp:I},O={id:Z(),role:"assistant",content:"",timestamp:I+1},z=[...u.current,M,O];a(J=>({...J,messages:z,isLoading:!0,loadingMessage:"Processing"}));let K=z.map(J=>({role:J.role,content:J.content,timestamp:new Date(J.timestamp||Date.now()),...J.tool&&{tool:J.tool},...J.toolOutput&&{toolOutput:J.toolOutput}}));y.setDelegate({messages:K,fullConversationHistory:K,isLoading:!1,currentInput:"",selectedModel:p.current,isVisionEnabled:m.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(g,T.length>0?T:void 0)}catch(J){a(Te=>({...Te,messages:[...Te.messages,{id:Z(),role:"system",content:`Error: ${J.message}`,timestamp:Date.now()}],isLoading:!1}))}},[o.queueManager,y]);S.current=b;let w=xt(()=>({onConversationIdReceived:g=>{a(T=>({...T,conversationId:g.conversationId,conversationTitleGenerated:!!g.title}))},onMessagesUpdate:g=>{a(T=>({...T,messages:g(T.messages)}))},onActiveToolsUpdate:g=>{a(T=>({...T,activeTools:g(T.activeTools)}))},onLoadingChange:g=>{a(T=>({...T,isLoading:g,activeTools:g?T.activeTools:new Map,subAgentOperations:g?T.subAgentOperations:new Map}))},onLoadingMessageChange:g=>{a(T=>({...T,loadingMessage:g}))},onTodoUpdate:g=>{f(g)},onConfirmationRequest:g=>{a(T=>({...T,pendingConfirmation:g}))},onError:g=>{a(T=>({...T,messages:[...T.messages,{id:Z(),role:"system",content:`Error: ${g}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[f]);ur({personalAgent:o.personalAgent,handlers:w});let{regularQueuedMessages:k,crossDeviceTasks:v,processNextMessage:x,hasQueuedMessages:P}=gr({queueManager:o.queueManager,frontendWS:o.frontendWS,crossDevice:o.crossDevice,isLoading:r.isLoading,selectedModel:p.current,onCrossDeviceTask:(g,T)=>{T&&S.current?.(T)}}),{subAgentOperations:A}=hr({subAgentManager:o.subAgentManager});Ke(()=>{a(g=>({...g,subAgentOperations:A}))},[A]),Ke(()=>{if(!r.isLoading&&P){let g=x();g&&S.current?.(g.content)}},[r.isLoading,P,x]);let B=xt(()=>({addMessage:g=>{a(T=>({...T,messages:[...T.messages,g]}))},addSystemMessage:g=>{a(T=>({...T,messages:[...T.messages,{id:Z(),role:"system",content:g,timestamp:Date.now()}]}))},updateMessages:g=>{a(T=>({...T,messages:g(T.messages)}))},setLoading:(g,T)=>{a(I=>({...I,isLoading:g,loadingMessage:T||I.loadingMessage}))},setConversationId:(g,T)=>{a(I=>({...I,conversationId:g,conversationTitleGenerated:!!T}))},clearChat:()=>{a(g=>({...g,messages:[{id:Z(),role:"system",content:`Welcome to Orion
591
+ - Item 3`,timestamp:Date.now()+600+_*100}))],U={todos:[{id:"todo-1",content:"Setup project structure",status:"completed",activeForm:"Setting up project structure"},{id:"todo-2",content:"Implement core features",status:"completed",activeForm:"Implementing core features"},{id:"todo-3",content:"Add authentication",status:"in_progress",activeForm:"Adding authentication"},{id:"todo-4",content:"Write unit tests",status:"pending",activeForm:"Writing unit tests"},{id:"todo-5",content:"Setup CI/CD pipeline",status:"pending",activeForm:"Setting up CI/CD"},{id:"todo-6",content:"Deploy to production",status:"pending",activeForm:"Deploying to production"}],timestamp:new Date},A=new Map([["tool-1",{toolCallId:"tool-1",name:"Bash",arguments:{command:"npm install",description:"Install dependencies"},startTime:new Date,state:"running"}],["tool-2",{toolCallId:"tool-2",name:"Read",arguments:{file_path:"/src/index.ts"},startTime:new Date(Date.now()-5e3),state:"completed",output:"File content..."}],["tool-3",{toolCallId:"tool-3",name:"Grep",arguments:{pattern:"TODO",path:"src/"},startTime:new Date(Date.now()-3e3),state:"completed"}],["tool-4",{toolCallId:"tool-4",name:"Write",arguments:{file_path:"/src/new-file.ts"},startTime:new Date(Date.now()-1e3),state:"failed",error:"Permission denied"}],["tool-5",{toolCallId:"tool-5",name:"WebFetch",arguments:{url:"https://api.example.com/data"},startTime:new Date,state:"running"}]]);a(M=>({...M,messages:x,todoList:U,activeTools:A,isLoading:!0,loadingMessage:"Processing mock request..."}))},500);return()=>clearTimeout(f)},[]);let[y]=Ar(()=>{let f={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:o,isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new Fn(f)});Je(()=>{let f=r.messages.map(v=>({role:v.role,content:v.content,timestamp:new Date(v.timestamp||Date.now()),...v.tool&&{tool:v.tool},...v.toolOutput&&{toolOutput:v.toolOutput}}));y.setDelegate({messages:f,fullConversationHistory:f,isLoading:r.isLoading,currentInput:"",selectedModel:p.current,isVisionEnabled:m.current,conversationId:r.conversationId,usesCustomUI:!0,updateCurrentConversation:()=>{}})},[r.messages,r.isLoading,r.conversationId,y]);let T=Et(null),S=Bo(async(f,v=[])=>{if(l.current){s.queueManager.addToQueue({content:f,imageUrls:v,attachments:[],model:p.current.name})||a(ye=>({...ye,messages:[...ye.messages,{id:ee(),role:"system",content:"[!] Queue is full (max 5 messages). Your input was not saved.",timestamp:Date.now()}]}));return}let x=Date.now(),U={id:ee(),role:"user",content:f,timestamp:x},A={id:ee(),role:"assistant",content:"",timestamp:x+1},M=[...u.current,U,A];a(B=>({...B,messages:M,isLoading:!0,loadingMessage:"Processing"}));let _=M.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}}));y.setDelegate({messages:_,fullConversationHistory:_,isLoading:!1,currentInput:"",selectedModel:p.current,isVisionEnabled:m.current,conversationId:d.current,usesCustomUI:!0,updateCurrentConversation:()=>{}});try{await y.sendMessage(f,v.length>0?v:void 0)}catch(B){a(ye=>({...ye,messages:[...ye.messages,{id:ee(),role:"system",content:`Error: ${B.message}`,timestamp:Date.now()}],isLoading:!1}))}},[s.queueManager,y]);T.current=S;let w=kt(()=>({onConversationIdReceived:f=>{a(v=>({...v,conversationId:f.conversationId,conversationTitleGenerated:!!f.title}))},onMessagesUpdate:f=>{a(v=>({...v,messages:f(v.messages)}))},onActiveToolsUpdate:f=>{a(v=>({...v,activeTools:f(v.activeTools)}))},onLoadingChange:f=>{a(v=>({...v,isLoading:f,activeTools:f?v.activeTools:new Map,subAgentOperations:f?v.subAgentOperations:new Map}))},onLoadingMessageChange:f=>{a(v=>({...v,loadingMessage:f}))},onTodoUpdate:f=>{h(f)},onConfirmationRequest:f=>{a(v=>({...v,pendingConfirmation:f}))},onError:f=>{a(v=>({...v,messages:[...v.messages,{id:ee(),role:"system",content:`Error: ${f}`,timestamp:Date.now()}],isLoading:!1,activeTools:new Map,subAgentOperations:new Map}))}}),[h]);Sr({personalAgent:s.personalAgent,handlers:w});let{regularQueuedMessages:E,crossDeviceTasks:b,processNextMessage:C,hasQueuedMessages:P}=Er({queueManager:s.queueManager,frontendWS:s.frontendWS,crossDevice:s.crossDevice,isLoading:r.isLoading,selectedModel:p.current,onCrossDeviceTask:(f,v)=>{v&&T.current?.(v)}}),{subAgentOperations:R}=kr({subAgentManager:s.subAgentManager});Je(()=>{a(f=>({...f,subAgentOperations:R}))},[R]),Je(()=>{if(!r.isLoading&&P){let f=C();f&&T.current?.(f.content)}},[r.isLoading,P,C]);let O=kt(()=>({addMessage:f=>{a(v=>({...v,messages:[...v.messages,f]}))},addSystemMessage:f=>{a(v=>({...v,messages:[...v.messages,{id:ee(),role:"system",content:f,timestamp:Date.now()}]}))},updateMessages:f=>{a(v=>({...v,messages:f(v.messages)}))},setLoading:(f,v)=>{a(x=>({...x,isLoading:f,loadingMessage:v||x.loadingMessage}))},setConversationId:(f,v)=>{a(x=>({...x,conversationId:f,conversationTitleGenerated:!!v}))},clearChat:()=>{a(f=>({...f,messages:[{id:ee(),role:"system",content:`Welcome to Orion
596
592
 
597
593
  Your intelligent AI assistant.
598
- Type a message to start.`,timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1}))},handleSubmit:b,handleConfirmationConfirm:g=>{let T=r.pendingConfirmation?.id;T&&(a(I=>({...I,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:T,response:g,confirmed:!0}))},handleConfirmationDecline:()=>{let g=r.pendingConfirmation?.id;g&&(a(T=>({...T,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:g,response:"n",confirmed:!1}),a(T=>({...T,messages:[...T.messages,{id:Z(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let g=r.pendingConfirmation?.id;g&&(a(T=>({...T,pendingConfirmation:null})),o.personalAgent.emit("confirmation_response",{confirmationId:g,response:"n",confirmed:!1,timedOut:!0}),a(T=>({...T,messages:[...T.messages,{id:Z(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:()=>{o.personalAgent.stopStreaming(),a(g=>({...g,isLoading:!1,messages:[...g.messages,{id:Z(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))}}),[b,o.personalAgent,r.pendingConfirmation]),_=xt(()=>({regularQueuedMessages:k,crossDeviceTasks:v,hasQueuedMessages:P}),[k,v,P]),N=Ro(g=>{p.current=g},[]),C=Ro(g=>{m.current=g},[]),E=xt(()=>({state:r,actions:B,services:o,queue:_,projectPath:t}),[r,B,o,_,t]);return Ke(()=>{$e._updateModelRef=N,$e._updateVisionRef=C},[N,C]),lc.createElement($e.Provider,{value:E},c)}function qt(){let c=Gt($e);if(!c)throw new Error("useChatState must be used within ChatProvider");return c.state}function Ue(){let c=Gt($e);if(!c)throw new Error("useChatActions must be used within ChatProvider");return c.actions}function Oo(){let c=Gt($e);if(!c)throw new Error("useChatServices must be used within ChatProvider");return c.services}function Fo(){let c=Gt($e);if(!c)throw new Error("useChatQueue must be used within ChatProvider");return c.queue}function _o(){let c=Gt($e);if(!c)throw new Error("useProjectPath must be used within ChatProvider");return c.projectPath}function Tr(){return $e}He();be();Nt();ce();import pc,{createContext as mc,useContext as $o,useState as gc,useMemo as Mn,useEffect as hc}from"react";var On=mc(null);function Uo({children:c}){let e=Mn(()=>Q.find(l=>l.name===Fe.string("selectedPersonalModel"))||Q.find(l=>l.name==="snowx-c5")||Q[0],[]),[t,n]=gc({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1}),o=Ue();hc(()=>{let l=Tr();l._updateModelRef&&l._updateModelRef(t.selectedModel),l._updateVisionRef&&l._updateVisionRef(t.isVisionEnabled)},[t.selectedModel,t.isVisionEnabled]);let s=Mn(()=>({email:H.getInstance().getUserEmail()||"User",tier:ae.getDisplayName(ae.getCurrentUserTier()),userTier:ae.getCurrentUserTier()}),[]),r=Mn(()=>({toggleHelp:()=>n(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>n(l=>({...l,showHelp:!0})),hideHelp:()=>n(l=>({...l,showHelp:!1})),toggleModelMenu:()=>n(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>n(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>n(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>n(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>n(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>n(l=>({...l,showCommandMenu:!1})),setModel:l=>{Fe.set("selectedPersonalModel",l.name),n(u=>({...u,selectedModel:l,showModelMenu:!1})),o.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{n(l=>{let u=!l.isVisionEnabled;return o.addSystemMessage(`Vision mode ${u?"enabled":"disabled"}`),{...l,isVisionEnabled:u}})},closeAllModals:()=>n(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))}),[o]),a=Mn(()=>({state:t,actions:r,info:s}),[t,r,s]);return pc.createElement(On.Provider,{value:a},c)}function zt(){let c=$o(On);if(!c)throw new Error("useUIState must be used within UIProvider");return c.state}function ot(){let c=$o(On);if(!c)throw new Error("useUIActions must be used within UIProvider");return c.actions}function Lo(){let c=$o(On);if(!c)throw new Error("useUIInfo must be used within UIProvider");return c.info}import Tc,{createContext as yc,useContext as Pr,useState as Sc,useMemo as Ir,useRef as wc}from"react";import _n from"path";import Wo from"fs";import st from"path";import fc from"os";var wr={".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"},Cr=Object.keys(wr),vc=[...Cr,".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"],yr=20*1024*1024,Sr=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 Bo(c,e=30){if(c.length<=e)return c;let t=st.extname(c);return st.basename(c,t).slice(0,e-t.length-3)+"..."+t}function xr(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(`
599
- `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),n=/^[A-Za-z]:[\\\/]/.test(e),o=e.startsWith("./")||e.startsWith("../"),s=e.startsWith("~/");if(!(t||n||o||s))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),l=st.extname(a),u=Cr.includes(l),d=vc.includes(l);return{isFilePath:!0,isImage:u,isBinary:d,path:e}}function bc(c){return c.startsWith("~/")?st.join(fc.homedir(),c.slice(2)):c}function Ho(c){let e=bc(c);return st.isAbsolute(e)?e:st.resolve(process.cwd(),e)}function Fn(c){try{let e=Ho(c),t=Wo.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 Er(c){try{let e=Ho(c),t=Fn(c);if(!t.exists)return{data:null,error:t.error};if(t.size>yr)return{data:null,error:`Image too large (${rt(t.size)}, max ${rt(yr)})`};let n=Wo.readFileSync(e),o=st.extname(c).toLowerCase(),s=wr[o]||"image/png",r=n.toString("base64");return{data:`data:${s};base64,${r}`}}catch(e){return{data:null,error:e.message}}}function kr(c){try{let e=Ho(c),t=Fn(c);return t.exists?t.size>Sr?{content:null,error:`File too large (${rt(t.size)}, max ${rt(Sr)})`}:{content:Wo.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}var Go=yc(null);function qo({children:c}){let[e,t]=Sc({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1}),n=wc(0),o=Ir(()=>({setInput:r=>{t(a=>({...a,input:r,cursorPosition:r.length}))},setCursor:r=>{t(a=>({...a,cursorPosition:Math.max(0,Math.min(r,a.input.length))}))},insertAtCursor:r=>{t(a=>{let l=a.input.slice(0,a.cursorPosition)+r+a.input.slice(a.cursorPosition);return{...a,input:l,cursorPosition:a.cursorPosition+r.length}})},deleteAtCursor:()=>{t(r=>{if(r.input===""&&r.pastedTexts.length>0)return{...r,pastedTexts:r.pastedTexts.slice(0,-1)};if(r.cursorPosition===0)return r;let a=r.input.slice(0,r.cursorPosition-1)+r.input.slice(r.cursorPosition);return{...r,input:a,cursorPosition:r.cursorPosition-1}})},clearInput:()=>{t(r=>({...r,input:"",cursorPosition:0,pastedTexts:[]}))},moveCursorLeft:()=>{t(r=>({...r,cursorPosition:Math.max(0,r.cursorPosition-1)}))},moveCursorRight:()=>{t(r=>({...r,cursorPosition:Math.min(r.input.length,r.cursorPosition+1)}))},moveCursorToStart:()=>{t(r=>({...r,cursorPosition:0}))},moveCursorToEnd:()=>{t(r=>({...r,cursorPosition:r.input.length}))},addPastedContent:r=>{let a=xr(r),l=r.split(`
600
- `);n.current+=1;let u="text",d,p;if(a.isFilePath){a.isImage?u="image_path":a.isBinary?(u="file_path",p="Binary file - cannot read as text"):u="file_path";let m=Fn(a.path);m.exists?d=m.size:p=m.error}t(m=>({...m,pastedTexts:[...m.pastedTexts,{id:n.current,content:r,lineCount:l.length,type:u,filePath:a.isFilePath?a.path:void 0,fileSize:d,error:p}]}))},clearPastedTexts:()=>{t(r=>({...r,pastedTexts:[]}))},removeLastPaste:()=>{t(r=>({...r,pastedTexts:r.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{t(r=>({...r,isProcessingFiles:!0}));try{let r=e,a=r.pastedTexts.filter(b=>b.type==="image_path"&&b.filePath),l=r.pastedTexts.filter(b=>b.type==="file_path"&&b.filePath),u=r.pastedTexts.filter(b=>b.type==="text"),d=[],p=[],m=[];for(let b of l)if(b.filePath&&!b.error){let w=kr(b.filePath);if(w.content){let k=_n.basename(b.filePath),v=_n.extname(k).slice(1)||"text";p.push(`[File: ${k}]
601
- \`\`\`${v}
602
- ${w.content}
603
- \`\`\``)}else w.error&&m.push(`${_n.basename(b.filePath)}: ${w.error}`)}for(let b of a)if(b.filePath&&!b.error){let w=await Er(b.filePath);w.data?d.push(w.data):w.error&&m.push(`${_n.basename(b.filePath)}: ${w.error}`)}let h=u.map(b=>b.content).join(`
604
-
605
- `),f=p.join(`
606
-
607
- `),y=[h,f].filter(Boolean).join(`
608
-
609
- `);return{fullInput:y?r.input.trim()?`${y}
610
-
611
- ${r.input}`:y:r.input,imageUrls:d,errors:m}}finally{t(r=>({...r,isProcessingFiles:!1}))}}}),[e]),s=Ir(()=>({state:e,actions:o}),[e,o]);return Tc.createElement(Go.Provider,{value:s},c)}function Xt(){let c=Pr(Go);if(!c)throw new Error("useInputState must be used within InputProvider");return c.state}function it(){let c=Pr(Go);if(!c)throw new Error("useInputActions must be used within InputProvider");return c.actions}import Ec,{createContext as kc,useContext as Jh,useCallback as Un,useRef as Dr,useEffect as Ic}from"react";import{EventEmitter as xc}from"events";function Ar(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var $n=new xc;$n.setMaxListeners(50);var Pc=kc(null);function zo({children:c,enableMouse:e=!0}){let t=Dr(new Set),n=Dr(new Set),o=Un(l=>{t.current.add(l)},[]),s=Un(l=>{t.current.delete(l)},[]),r=Un(l=>{n.current.add(l)},[]),a=Un(l=>{n.current.delete(l)},[]);return Ic(()=>{if(!e)return;let l=u=>{for(let d of t.current)d(u);if(u.name==="scroll-up")for(let d of n.current)d("up");else if(u.name==="scroll-down")for(let d of n.current)d("down")};return $n.on("mouse",l),()=>{$n.off("mouse",l)}},[e]),Ec.createElement(Pc.Provider,{value:{subscribe:o,unsubscribe:s,subscribeScroll:r,unsubscribeScroll:a,isMouseEnabled:e}},c)}function Nr({children:c,initialProjectPath:e}){return Ln.createElement(zo,{enableMouse:!1},Ln.createElement(Mo,{initialProjectPath:e},Ln.createElement(Uo,null,Ln.createElement(qo,null,c))))}import{useRef as Xo,useEffect as Dc}from"react";import{useInput as Nc,useApp as Rc}from"@jrichman/ink";import{useCallback as Rr}from"react";import{useApp as Ac}from"@jrichman/ink";function Wn(){let{exit:c}=Ac(),e=Ue(),t=Oo(),n=ot(),o=it(),s=Rr(a=>a.startsWith("/"),[]);return{handleCommand:Rr(async a=>{if(!a.startsWith("/"))return{handled:!1};let l=a.toLowerCase().trim();if(l==="/help"||l==="/?")return n.showCommandMenu(),o.clearInput(),{handled:!0,clearInput:!0};if(l==="/model")return n.showModelMenu(),o.clearInput(),{handled:!0,clearInput:!0};if(l==="/clear"||l==="/new")return e.clearChat(),o.clearInput(),{handled:!0,clearInput:!0};if(l==="/vision")return n.toggleVision(),o.clearInput(),{handled:!0,clearInput:!0};if(l==="/exit"||l==="/quit")return c(),{handled:!0};if(l==="/stop")return e.stopStreaming(),o.clearInput(),{handled:!0,clearInput:!0};if(l==="/signout"){e.addSystemMessage("[...] Signing out..."),o.clearInput();try{await t.authService.signOut()&&(e.addSystemMessage("[OK] Successfully signed out. Goodbye!"),setTimeout(()=>c(),1e3))}catch(u){e.addSystemMessage(`[ERROR] ${u.message}`)}return{handled:!0,clearInput:!0}}return e.addSystemMessage(`Unknown command: ${a}
612
-
613
- Type /help to see available commands.`),o.clearInput(),{handled:!0,clearInput:!0}},[c,e,t.authService,n,o]),isCommand:s}}function Mr({onSubmit:c}){let{exit:e}=Rc(),t=qt(),n=Ue(),o=zt(),s=ot(),r=Xt(),a=it(),{handleCommand:l,isCommand:u}=Wn(),d=Xo(""),p=Xo(null),m=Xo(0);return Dc(()=>()=>{p.current&&clearTimeout(p.current)},[]),Nc((h,f)=>{if(!(h.startsWith("[<")||h.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(h)||/^\d+[mM]/.test(h)||/^;\d+;\d+[mM]/.test(h)||/^\d+;\d+[mM]/.test(h))){if(f.escape){if(t.isLoading){n.stopStreaming();return}if(o.showModelMenu||o.showCommandMenu){s.closeAllModals(),o.showCommandMenu&&r.input==="/"&&a.clearInput();return}if(o.showHelp){s.hideHelp();return}if(r.pastedTexts.length>0){a.clearPastedTexts();return}return}if(!o.showModelMenu&&!(o.showCommandMenu&&(f.upArrow||f.downArrow||f.return))){if(f.ctrl&&h==="l"){process.stdout.write("\x1B[2J\x1B[H");return}if(f.ctrl&&h==="c"){t.isLoading?n.stopStreaming():e();return}if(h==="?"&&r.input===""&&!o.showCommandMenu){s.toggleHelp();return}if(f.return){let y=r.pastedTexts.filter(b=>!b.error||b.type==="text");(r.input.trim()||y.length>0)&&c();return}if(f.leftArrow){a.moveCursorLeft();return}if(f.rightArrow){a.moveCursorRight();return}if(f.home){a.moveCursorToStart();return}if(f.end){a.moveCursorToEnd();return}if(f.delete||f.backspace){a.deleteAtCursor(),o.showCommandMenu&&((r.input.slice(0,r.cursorPosition-1)+r.input.slice(r.cursorPosition)).startsWith("/")||s.hideCommandMenu());return}if(!f.ctrl&&!f.meta&&h){let y=Date.now(),S=y-m.current;m.current=y;let b=S<50,w=h.includes(`
614
- `),k=h.length>50;if(w||k){p.current&&(clearTimeout(p.current),p.current=null);let A=d.current+h;d.current="",a.addPastedContent(A);return}if(b&&h.length===1){d.current+=h,p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{let A=d.current;d.current="",p.current=null,A&&(a.insertAtCursor(A),r.input===""&&A==="/"&&s.showCommandMenu())},100);return}p.current&&(clearTimeout(p.current),p.current=null);let v=d.current;d.current="";let x=v+h;a.insertAtCursor(x),r.input.slice(0,r.cursorPosition)+x+r.input.slice(r.cursorPosition)==="/"&&!o.showCommandMenu&&s.showCommandMenu()}}}}),{handleCommand:l,isCommand:u}}import ne from"react";import{Box as Bn,Text as Le}from"@jrichman/ink";import Mc from"ink-spinner";function Oc(c,e){let t=c.toLowerCase(),n=e?.description;if(t==="bash"||t==="command"||t==="run_command"){let o=e?.command,s=n&&n.length<50?n:"Running command",r=o?`$ ${o.substring(0,80)}`:void 0;return{title:s,details:r}}if(t==="read"||t==="readfile")return{title:"Reading",details:e?.file_path};if(t==="write"||t==="writefile")return{title:"Writing",details:e?.file_path};if(t==="edit"||t==="editfile")return{title:"Editing",details:e?.file_path};if(t==="grep"){let o=e?.pattern,s=e?.path;return{title:"Searching",details:o?`"${o}"${s?` in ${s}`:""}`:void 0}}if(t==="glob")return{title:"Finding files",details:e?.pattern};if(t==="webfetch"||t==="web_fetch"){let o=e?.url;return{title:"Fetching",details:o?o.substring(0,60):void 0}}if(t==="task"){let o=e?.description,s=e?.subagent_type;return{title:s?`Agent: ${s}`:"Running agent",details:o?o.substring(0,60):void 0}}if(t==="websearch"||t==="web_search"){let o=e?.query;return{title:"Web search",details:o?`"${o}"`:void 0}}return n&&n.length<60?{title:n}:{title:c}}function jo({tool:c}){let{title:e,details:t}=Oc(c.name,c.arguments),n=c.state==="running",o=c.state==="completed",s=c.state==="failed",r=t?t.length>60?t.substring(0,57)+"...":t:void 0;return ne.createElement(Bn,null,n&&ne.createElement(Le,{color:"cyan"},ne.createElement(Mc,{type:"dots"})),o&&ne.createElement(Le,{color:"#5AD8A6"},"✓"),s&&ne.createElement(Le,{color:"#F5716C"},"✗"),ne.createElement(Le,null," "),ne.createElement(Le,{color:n?"whiteBright":"#9CA3AF"},e),r?ne.createElement(Le,{color:"#6B7280"}," ",r):n?ne.createElement(Le,{color:"#6B7280"}," ..."):null)}function Or({activeTools:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([a,l])=>l.name.toLowerCase().replace(/_/g,"")!=="todowrite");if(e.length===0)return null;let t=e.filter(([a,l])=>l.state==="running"),n=e.filter(([a,l])=>l.state==="completed"),o=e.filter(([a,l])=>l.state==="failed"),s=n.slice(-3),r=n.length-s.length;return ne.createElement(Bn,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1},t.map(([a,l])=>ne.createElement(jo,{key:a,tool:l})),s.map(([a,l])=>ne.createElement(jo,{key:a,tool:l})),o.map(([a,l])=>ne.createElement(Bn,{key:a,flexDirection:"column"},ne.createElement(jo,{tool:l}),l.error&&ne.createElement(Bn,{marginLeft:2},ne.createElement(Le,{color:"#F5716C"},l.error.substring(0,60))))),r>0&&ne.createElement(Le,{color:"#6B7280"}," +",r," more completed"))}import G from"react";import{Box as We,Text as oe}from"@jrichman/ink";import Fr from"ink-spinner";function Fc(c,e=60){return c?c.length<=e?c:c.substring(0,e-3)+"...":"Processing..."}function _c({agent:c}){let e=Fc(c.task||"Working..."),t=s=>{switch(s){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},n=()=>c.status==="running"?G.createElement(oe,{color:"cyan"},G.createElement(Fr,{type:"dots"})):c.status==="completed"?G.createElement(oe,{color:"#5AD8A6"},"[done]"):c.status==="failed"?G.createElement(oe,{color:"#F5716C"},"[fail]"):c.status==="timeout"?G.createElement(oe,{color:"#FBBF24"},"[time]"):G.createElement(oe,{color:"#6B7280"},"[ ]"),o=t(c.status);return G.createElement(We,{flexDirection:"column",marginLeft:2},G.createElement(We,null,n(),G.createElement(oe,{color:o,bold:!0}," Agent #",c.agentNumber)),G.createElement(We,{marginLeft:2},G.createElement(oe,{color:"#9CA3AF"},e)),c.error&&G.createElement(We,{marginLeft:2},G.createElement(oe,{color:"#F5716C"},"Error: ",c.error.substring(0,60),c.error.length>60?"...":"")),c.streamingContent&&c.status==="running"&&G.createElement(We,{marginLeft:2},G.createElement(oe,{color:"#6B7280"},c.streamingContent.split(`
615
- `)[0]?.substring(0,50),"...")))}function $c({operation:c}){let e=Array.from(c.agents.values()).sort((u,d)=>u.agentNumber-d.agentNumber),t=e.filter(u=>u.status==="completed").length,n=e.filter(u=>u.status==="failed").length,o=e.filter(u=>u.status==="running").length,s=c.totalAgents,r=()=>c.status==="starting"||c.status==="running"?`Spawning ${s} agents`:c.status==="completed"?`${s} agents completed`:"Operation failed",a=()=>c.status==="running"||c.status==="starting"?G.createElement(oe,{color:"cyan"},G.createElement(Fr,{type:"dots"})):c.status==="completed"?G.createElement(oe,{color:"#5AD8A6"},"[done]"):G.createElement(oe,{color:"#F5716C"},"[fail]"),l=c.status==="completed"?"#5AD8A6":c.status==="failed"?"#F5716C":"cyan";return G.createElement(We,{flexDirection:"column"},G.createElement(We,null,a(),G.createElement(oe,{color:l,bold:!0}," ",r()),G.createElement(oe,{color:"#6B7280"}," "),G.createElement(oe,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",t,"/",s," "),o>0&&G.createElement(oe,{color:"cyan"}," (",o," running)"),n>0&&G.createElement(oe,{color:"#F5716C"}," [",n," failed]")),G.createElement(We,{flexDirection:"column",marginTop:1},e.map(u=>G.createElement(_c,{key:u.agentNumber,agent:u}))))}function _r({operations:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0);return e.length===0?null:G.createElement(We,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>G.createElement($c,{key:t,operation:n})))}import De,{useState as Uc,useEffect as Lc,useRef as $r}from"react";import{Box as jt,Text as Vt}from"@jrichman/ink";import Wc from"ink-select-input";function Ur({request:c,onConfirm:e,onDecline:t,onTimeout:n}){let[o,s]=Uc(c.timeout?Math.ceil(c.timeout/1e3):null),r=$r(null),a=$r(0);Lc(()=>{if(c.timeout)return a.current=Date.now(),s(Math.ceil(c.timeout/1e3)),r.current=setInterval(()=>{let m=Date.now()-a.current,h=Math.max(0,c.timeout-m),f=Math.ceil(h/1e3);s(f),h<=0&&(r.current&&clearInterval(r.current),n?.())},1e3),()=>{r.current&&clearInterval(r.current)}},[c.timeout,n]);let l=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}],u=m=>{r.current&&(clearInterval(r.current),r.current=null),m.value==="confirm"?e("y"):t()},d=c.targets?.filter(m=>m.startsWith("/")||m.startsWith("./")||m.startsWith("~/")).slice(0,3)||[],p=c.command&&c.command.length>60?c.command.substring(0,57)+"...":c.command;return De.createElement(jt,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},De.createElement(Vt,{color:"white",bold:!0},c.title),p&&De.createElement(jt,{marginTop:1},De.createElement(Vt,{color:"gray"},"$ "),De.createElement(Vt,{color:"white"},p)),d.length>0&&De.createElement(jt,{marginTop:1,flexDirection:"column"},d.map((m,h)=>De.createElement(Vt,{key:h,color:"gray"}," ",m))),o!==null&&De.createElement(jt,{marginTop:1},De.createElement(Vt,{color:"yellow"},"Auto-cancel in ",o,"s")),De.createElement(jt,{marginTop:1},De.createElement(Wc,{items:l,onSelect:u})))}import Ce from"react";import{Box as Kt,Text as at}from"@jrichman/ink";var Bc=8;function Lr({todoList:c}){if(!c||c.todos.length===0)return null;let e=c.todos.filter(r=>r.status!=="completed"),t=c.todos.filter(r=>r.status==="completed"),n=e.length===0&&t.length>0,o=[...e,...t.slice(-2)].slice(0,Bc),s=c.todos.length-o.length;return Ce.createElement(Kt,{paddingX:2,marginBottom:1},Ce.createElement(Kt,{borderStyle:"round",borderColor:n?"#5AD8A6":"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},Ce.createElement(Kt,{marginBottom:1},Ce.createElement(at,{color:"whiteBright",bold:!0},"Tasks"),Ce.createElement(at,{color:"#6B7280"}," - "),Ce.createElement(at,{color:n?"#5AD8A6":"#9CA3AF"},t.length,"/",c.todos.length,n&&" ✓")),o.map((r,a)=>{let l=r.status==="completed"?"[done]":r.status==="in_progress"?"[..]":"[ ]",u=r.status==="completed"?"#5AD8A6":r.status==="in_progress"?"cyan":"#6B7280",d=r.status==="in_progress"&&r.activeForm?r.activeForm:cr(r);return Ce.createElement(Kt,{key:r.id||`todo-${a}`},Ce.createElement(at,{color:u},l),Ce.createElement(at,{color:"#6B7280"}," "),Ce.createElement(at,{color:r.status==="completed"?"#6B7280":"whiteBright"},d))}),s>0&&Ce.createElement(Kt,{marginTop:0},Ce.createElement(at,{color:"#6B7280"}," +",s," more tasks"))))}import se from"react";import{Box as Vo,Text as he}from"@jrichman/ink";function Wr(){return se.createElement(Vo,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},se.createElement(he,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),se.createElement(Vo,{marginTop:1,flexDirection:"column"},se.createElement(he,{color:"#9CA3AF"},"• ",se.createElement(he,{color:"whiteBright",bold:!0},"Enter")," ",se.createElement(he,{color:"#9CA3AF"},"Submit message")),se.createElement(he,{color:"#9CA3AF"},"• ",se.createElement(he,{color:"whiteBright",bold:!0},"?")," ",se.createElement(he,{color:"#9CA3AF"},"Toggle this help")),se.createElement(he,{color:"#9CA3AF"},"• ",se.createElement(he,{color:"whiteBright",bold:!0},"Esc")," ",se.createElement(he,{color:"#9CA3AF"},"Stop generation / Close menus")),se.createElement(he,{color:"#9CA3AF"},"• ",se.createElement(he,{color:"whiteBright",bold:!0},"Ctrl+C")," ",se.createElement(he,{color:"#9CA3AF"},"Stop generation / Exit"))),se.createElement(Vo,{marginTop:1},se.createElement(he,{color:"#6B7280"},"Press Esc to close")))}import fe from"react";import{Box as Gn,Text as Be}from"@jrichman/ink";import Et,{useState as Hc,useEffect as Gc}from"react";import{Box as Ko,Text as Br,useInput as qc}from"@jrichman/ink";function zc({item:c,isSelected:e,highlightColor:t}){return Et.createElement(Br,{color:e?"#000":"#fff",backgroundColor:e?t:void 0},c.label)}function Hn({items:c,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:o="#D97706",itemComponent:s=zc}){let[r,a]=Hc(0);return Gc(()=>{a(0)},[c.length]),qc((l,u)=>{if(n){if(u.upArrow){let d=r>0?r-1:c.length-1;a(d),t?.(c[d])}if(u.downArrow){let d=r<c.length-1?r+1:0;a(d),t?.(c[d])}if(u.return){let d=c[r];d&&e(d)}}},{isActive:n}),c.length===0?Et.createElement(Ko,null,Et.createElement(Br,{color:"#6B7280"},"No items")):Et.createElement(Ko,{flexDirection:"column"},c.map((l,u)=>{let d=u===r;return Et.createElement(Ko,{key:l.value||u},Et.createElement(s,{item:l,isSelected:d,highlightColor:o}))}))}He();Nt();function Hr({userTier:c,onSelect:e,onAccessDenied:t}){let n=p=>{switch(p){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},o=Q.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),s=Q.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),r=Q.filter(p=>p.name.startsWith("snowx-g")),a=p=>p.map(m=>{let h=ae.isModelAccessible(m.name,c),f=n(m.creditMultiplier);return{label:`${h?"":"[LOCKED] "}${m.displayName} ${f}`,value:m.name,isAccessible:h,creditMultiplier:m.creditMultiplier,isHeader:!1}}),l=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(o),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(s),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(r)],u=l.filter(p=>!p.isHeader),d=p=>{if(p.value.startsWith("_"))return;if(!l.find(f=>f.value===p.value)?.isAccessible){t(p.value);return}let h=Q.find(f=>f.name===p.value);h&&e(h)};return fe.createElement(Gn,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},fe.createElement(Be,{bold:!0,color:"whiteBright"},"Select Model"),fe.createElement(Gn,null,fe.createElement(Be,{color:"#6B7280"},"Tier: ",ae.getDisplayName(c)," - "),fe.createElement(Be,{color:"#5AD8A6"},"[0.5x]"),fe.createElement(Be,{color:"#6B7280"}," "),fe.createElement(Be,{color:"#9CA3AF"},"[1x]"),fe.createElement(Be,{color:"#6B7280"}," "),fe.createElement(Be,{color:"#FBBF24"},"[2x]"),fe.createElement(Be,{color:"#6B7280"}," credits")),fe.createElement(Gn,{marginTop:1},fe.createElement(Hn,{items:u.map(p=>({label:p.label,value:p.value})),onSelect:d,isFocused:!0,highlightColor:"#D97706"})),fe.createElement(Gn,{marginTop:1},fe.createElement(Be,{color:"#6B7280"},"Esc to cancel")))}import kt from"react";import{Box as Qo,Text as Gr}from"@jrichman/ink";var qr=[{command:"/model",description:"change AI model",value:"model"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}];function Xc({item:c,isSelected:e,highlightColor:t}){let[n,o]=c.label.split(" ");return kt.createElement(Qo,{width:50,backgroundColor:e?t:void 0},kt.createElement(Qo,{width:14},kt.createElement(Gr,{color:e?"#1a1a1a":"whiteBright",bold:!0},n)),kt.createElement(Gr,{color:e?"#1a1a1a":"#6B7280"},o))}function zr({filterText:c,onSelect:e}){let n=(c?qr.filter(s=>s.value.toLowerCase().includes(c)):qr).map(s=>({label:`${s.command} ${s.description}`,value:s.value})),o=s=>{s.value&&e(s.value)};return kt.createElement(Qo,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},kt.createElement(Hn,{items:n.length>0?n:[{label:"No matching commands",value:""}],onSelect:o,itemComponent:Xc,isFocused:!0,highlightColor:"#D97706"}))}import ee from"react";import{Box as Qe,Text as Je}from"@jrichman/ink";function Xr({regularQueuedMessages:c,crossDeviceTasks:e}){return ee.createElement(ee.Fragment,null,c.length>0&&ee.createElement(Qe,{flexDirection:"column",paddingX:2,marginBottom:1},c.map((t,n)=>ee.createElement(Qe,{key:t.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},ee.createElement(Qe,null,ee.createElement(Je,{color:"whiteBright",bold:!0},n+1),ee.createElement(Je,{color:"#6B7280"}," • "),ee.createElement(Je,{color:"#9CA3AF"},t.content.length>60?t.content.substring(0,60)+"...":t.content)))),ee.createElement(Qe,null,ee.createElement(Je,{color:"#9CA3AF"},c.length," message",c.length>1?"s":""," queued"))),e.length>0&&ee.createElement(Qe,{flexDirection:"column",paddingX:2,marginBottom:1},e.map((t,n)=>ee.createElement(Qe,{key:`cross-${t.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},ee.createElement(Qe,null,ee.createElement(Je,{color:"#22D3EE",bold:!0},"[M] ",n+1),ee.createElement(Je,{color:"#6B7280"}," - "),ee.createElement(Je,{color:"#9CA3AF"},t.content.length>60?t.content.substring(0,60)+"...":t.content)))),ee.createElement(Qe,null,ee.createElement(Je,{color:"#22D3EE"},e.length," cross-device task",e.length>1?"s":""," waiting"))))}import V from"react";import{Box as Me,Text as pe}from"@jrichman/ink";import jr from"path";var ie={Foreground:"#E5E7EB",Background:"#111827",AccentBlue:"#60A5FA",AccentPurple:"#A78BFA",AccentCyan:"#22D3EE",AccentGreen:"#34D399",AccentYellow:"#FBBF24",AccentRed:"#F87171",Gray:"#9CA3AF",DarkGray:"#6B7280",LightGray:"#D1D5DB",Comment:"#6B7280"},jc={text:{primary:ie.Foreground,secondary:ie.Gray,accent:ie.AccentPurple,link:ie.AccentBlue,response:ie.Foreground},background:{primary:ie.Background,secondary:"#1F2937"},border:{default:ie.DarkGray,focused:ie.AccentBlue},ui:{comment:ie.Comment,symbol:ie.Gray,muted:ie.DarkGray},status:{success:ie.AccentGreen,warning:ie.AccentYellow,error:ie.AccentRed,info:ie.AccentCyan}},Jo={name:"Default Dark",type:"dark",colors:ie,semantic:jc};var It=Jo;var R={get text(){return It.semantic.text},get background(){return It.semantic.background},get border(){return It.semantic.border},get ui(){return It.semantic.ui},get status(){return It.semantic.status},get colors(){return It.colors}};function Vr({input:c,isLoading:e,pastedTexts:t,cursorPosition:n}){let o=c.length>0||t.length>0;return V.createElement(Me,{borderStyle:"round",borderColor:o?R.border.focused:R.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},t.length>0&&V.createElement(Me,{flexDirection:"column",marginBottom:0},t.map((r,a)=>{if(r.type==="image_path"&&r.filePath){let d=Bo(jr.basename(r.filePath)),p=r.fileSize?` ${rt(r.fileSize)}`:"",m=!!r.error;return V.createElement(Me,{key:`pasted-${r.id}`,flexDirection:"column"},V.createElement(Me,null,V.createElement(pe,{color:m?R.status.error:R.status.info}," ","[IMG] "),V.createElement(pe,{color:m?R.status.error:R.text.secondary},d),p&&V.createElement(pe,{color:R.ui.muted},p)),m&&V.createElement(Me,{marginLeft:4},V.createElement(pe,{color:R.status.error,dimColor:!0},"[!] ",r.error)))}if(r.type==="file_path"&&r.filePath){let d=Bo(jr.basename(r.filePath)),p=r.fileSize?` ${rt(r.fileSize)}`:"",m=!!r.error;return V.createElement(Me,{key:`pasted-${r.id}`,flexDirection:"column"},V.createElement(Me,null,V.createElement(pe,{color:m?R.status.error:R.status.info}," ","[FILE] "),V.createElement(pe,{color:m?R.status.error:R.text.secondary},d),p&&V.createElement(pe,{color:R.ui.muted},p)),m&&V.createElement(Me,{marginLeft:4},V.createElement(pe,{color:R.status.error,dimColor:!0},"[!] ",r.error)))}let l=r.lineCount-1,u=l>0?`+${l} lines`:"1 line";return V.createElement(Me,{key:`pasted-${r.id}`},V.createElement(pe,{color:R.ui.muted}," ","[TEXT] "),V.createElement(pe,{color:R.text.secondary},"Pasted text #",a+1),V.createElement(pe,{color:R.ui.muted}," (",u,")"))})),V.createElement(Me,null,V.createElement(pe,{color:R.text.accent},"> "),c.length===0&&!e?V.createElement(pe,{color:R.ui.muted}," Type your message or @path/to/file"):V.createElement(pe,{color:R.text.primary},c.slice(0,n),!e&&V.createElement(pe,{inverse:!0}," "),c.slice(n))))}import j from"react";import{Box as ve,Text as Oe}from"@jrichman/ink";import Yo from"terminal-link";import{homedir as Vc}from"os";function Kr(c){let e=c.trim();return e.startsWith("~")&&(e=e.replace("~",Vc())),e.startsWith("file://")||(e.startsWith("/")||(e="/"+e),e="file://"+e),e}function Kc(c){return c.startsWith("http://")||c.startsWith("https://")||c.startsWith("mailto:")}function qn(c){let e=c;return e=e.replace(/\[(.+?)\]\((.+?)\)/g,(t,n,o)=>{let s=o;return!Kc(o)&&!o.startsWith("file://")&&(o.startsWith("/")||o.startsWith("~")||/\.[a-z]{2,4}$/i.test(o))&&(s=Kr(o)),Yo(n,s,{fallback:(r,a)=>`${r} (${a})`})}),e=e.replace(/(https?:\/\/[^\s\)]+)/g,t=>{let n=/\x1b\]8;;/,o=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));return n.test(o)?t:Yo(t,t,{fallback:(s,r)=>r})}),e=e.replace(/([/~][^\s:,\)]+\.[a-z]{2,4})/gi,t=>{let n=/\x1b\]8;;/,o=e.slice(Math.max(0,e.indexOf(t)-20),e.indexOf(t));if(n.test(o)||o.includes("http"))return t;let s=Kr(t);return Yo(t,s,{fallback:(r,a)=>r})}),e}function Qr(c){let e=/<suggestion>([\s\S]*?)<\/suggestion>/g,t=[],n;for(;(n=e.exec(c))!==null;){let r=n[1].split(`
616
- `).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 o=c.replace(/<suggestion>[\s\S]*?<\/suggestion>/g,"");return o=o.replace(/<suggestion>[\s\S]*$/g,""),{suggestions:t,cleanedContent:o}}function Jr(c){let e=/<working-files>([\s\S]*?)<\/working-files>/g,t=[],n=new Set,o;for(;(o=e.exec(c))!==null;){let r=o[1],a=/\[([^\]]+)\]\(<?([^>)]+)>?\)/g,l;for(;(l=a.exec(r))!==null;){let u=l[1],d=l[2];n.has(d)||(n.add(d),t.push({name:u,path:d}))}}let s=c.replace(/<working-files>[\s\S]*?<\/working-files>/g,"");return s=s.replace(/<working-files>[\s\S]*$/g,""),{workingFiles:t,cleanedContent:s}}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=qn(e),e}function Zr(c){return c.replace(/\[TOOL:[^\]]+\]/g,"").trim()}import Pt from"react";import{Box as zn,Text as ei}from"@jrichman/ink";function ti({suggestions:c,onSelect:e}){return c.length===0?null:Pt.createElement(zn,{flexDirection:"column",marginTop:1,width:"100%"},c.map((t,n)=>Pt.createElement(zn,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((o,s)=>Pt.createElement(zn,{key:`sug-opt-${n}-${s}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Pt.createElement(ei,{color:"#22D3EE"},o))))),e&&Pt.createElement(zn,{marginTop:0,width:"100%"},Pt.createElement(ei,{color:"#6B7280"},"Type a suggestion to use it")))}import ct from"react";import{Box as Xn,Text as Zo}from"@jrichman/ink";function ni({workingFiles:c}){return c.length===0?null:ct.createElement(Xn,{flexDirection:"column",marginTop:1,width:"100%"},ct.createElement(Xn,{marginBottom:0,width:"100%"},ct.createElement(Zo,{color:"#9CA3AF",bold:!0},"Working Files"),ct.createElement(Zo,{color:"#6B7280"}," (",c.length,")")),ct.createElement(Xn,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},c.map(e=>ct.createElement(Xn,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},ct.createElement(Zo,{color:"white"},e.name)))))}var es={user:"> ",assistant:"✦ ",system:"ℹ "},Qc=150;function oi({message:c,onSuggestionClick:e,maxLines:t=Qc}){let{role:n,content:o}=c,s=(r,a)=>r.length<=a?{lines:r,truncated:!1}:{lines:r.slice(0,a),truncated:!0};if(n==="system"){let r=o.split(`
617
- `),{lines:a,truncated:l}=s(r,t);return j.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},j.createElement(ve,{flexDirection:"row"},j.createElement(ve,{width:2,flexShrink:0},j.createElement(Oe,{color:R.status.info},es.system)),j.createElement(ve,{flexDirection:"column",flexGrow:1},a.map((u,d)=>j.createElement(Oe,{key:`sys-line-${d}`,color:R.text.secondary},u)),l&&j.createElement(Oe,{color:R.ui.muted,dimColor:!0},"... (",r.length-t," more lines)"))))}if(n==="user"){let r=o.split(`
618
- `),{lines:a,truncated:l}=s(r,t);return j.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},j.createElement(ve,{flexDirection:"row"},j.createElement(ve,{width:2,flexShrink:0},j.createElement(Oe,{color:R.text.accent},es.user)),j.createElement(ve,{flexDirection:"column",flexGrow:1},a.map((u,d)=>j.createElement(Oe,{key:`user-line-${d}`,color:R.text.secondary},u)),l&&j.createElement(Oe,{color:R.ui.muted,dimColor:!0},"... (",r.length-t," more lines)"))))}if(n==="assistant"){let{suggestions:r,cleanedContent:a}=Qr(o),{workingFiles:l,cleanedContent:u}=Jr(a),p=Zr(u).split(`
619
- `),{lines:m,truncated:h}=s(p,t);return j.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},j.createElement(ve,{flexDirection:"row"},j.createElement(ve,{width:2,flexShrink:0},j.createElement(Oe,{color:R.text.accent},es.assistant)),j.createElement(ve,{flexDirection:"column",flexGrow:1},m.map((f,y)=>f.trim()===""?j.createElement(Oe,{key:`asst-line-${y}`}," "):j.createElement(Oe,{key:`asst-line-${y}`,color:R.text.primary},Yr(f))),h&&j.createElement(Oe,{color:R.ui.muted,dimColor:!0},"... (",p.length-t," more lines)"))),l.length>0&&j.createElement(ve,{paddingLeft:2},j.createElement(ni,{workingFiles:l})),r.length>0&&j.createElement(ve,{paddingLeft:2},j.createElement(ti,{suggestions:r,onSelect:e})))}return null}import Qt,{useState as Jc,useEffect as Yc}from"react";import{Box as Zc,Text as ts}from"@jrichman/ink";import el from"ink-spinner";function tl(c){if(c<60)return`${c}s`;let e=Math.floor(c/60),t=c%60;return`${e}m ${t}s`}function si({isLoading:c,phrase:e="Processing",startTime:t}){let[n,o]=Jc(0);return Yc(()=>{if(!c){o(0);return}let s=t||Date.now(),r=setInterval(()=>{let a=Date.now(),l=Math.floor((a-s)/1e3);o(l)},1e3);return()=>clearInterval(r)},[c,t]),c?Qt.createElement(Zc,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1},Qt.createElement(ts,{color:R.text.accent},Qt.createElement(el,{type:"dots"})),Qt.createElement(ts,{color:R.text.primary}," ",e,"... "),Qt.createElement(ts,{color:R.text.secondary},"(esc to cancel",n>0?`, ${tl(n)}`:"",")")):null}import Ye from"react";import{Box as jn,Text as Vn,useStdout as nl}from"@jrichman/ink";function ol(c){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&c.startsWith(e)?"~"+c.slice(e.length):c}function sl(c,e){if(c.length<=e)return c;let t=c.split("/");if(t.length<=2)return c.slice(0,e-3)+"...";let n=t[0]+"/.../"+t[t.length-1];return n.length>e&&(n=".../"+t[t.length-1]),n.length>e&&(n=n.slice(0,e-3)+"..."),n}function ri({cwd:c,selectedModel:e,showScrollHint:t=!1}){let{stdout:n}=nl(),o=n?.columns||80,s=`${e.displayName} /model`,r=t?"? help · Shift+↑↓ scroll":"? help",l=s.length+r.length+" ".length*2+4,u=Math.max(15,Math.floor((o-l)*.4)),d=sl(ol(c),u);return Ye.createElement(jn,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},Ye.createElement(jn,null,Ye.createElement(Vn,{color:R.text.link},d)),Ye.createElement(jn,null,Ye.createElement(Vn,{color:R.text.accent},e.displayName),Ye.createElement(Vn,{color:R.text.secondary}," /model")),Ye.createElement(jn,null,Ye.createElement(Vn,{color:R.text.secondary},r)))}import Ze,{useState as ns,useEffect as rl,useRef as os,useCallback as il,useLayoutEffect as al}from"react";import{Box as Jt,Text as ii,useStdout as cl,getScrollHeight as ll,getInnerHeight as ul,useInput as dl}from"@jrichman/ink";var ai=3;function ci({children:c,reservedLines:e=8,autoScrollToBottom:t=!0,hasFocus:n=!0}){let{stdout:o}=cl(),s=o?.rows||24,r=Math.max(5,s-e),[a,l]=ns(0),[u,d]=ns({innerHeight:0,scrollHeight:0}),[p,m]=ns(!1),h=os(null),f=os(u),y=os(0);rl(()=>{f.current=u},[u]),al(()=>{if(!h.current)return;let v=Math.round(ul(h.current)),x=Math.round(ll(h.current)),P=a>=u.scrollHeight-u.innerHeight-1;(u.innerHeight!==v||u.scrollHeight!==x)&&(d({innerHeight:v,scrollHeight:x}),P&&t&&l(Math.max(0,x-v)));let A=x>r;A!==p&&m(A);let B=Ze.Children.count(c);t&&y.current!==B&&l(Math.max(0,x-v)),y.current=B});let S=il(v=>{let{scrollHeight:x,innerHeight:P}=f.current;l(A=>{let B=Math.max(0,x-P);return Math.min(Math.max(0,A+v),B)})},[]);dl((v,x)=>{if(n){if(x.pageUp){S(-r+2);return}if(x.pageDown){S(r-2);return}if(x.shift&&x.upArrow){S(-ai);return}if(x.shift&&x.downArrow){S(ai);return}}},{isActive:n});let b=Math.max(0,u.scrollHeight-u.innerHeight),w=a>0,k=a<b;return Ze.createElement(Jt,{flexDirection:"column",flexGrow:1},w&&Ze.createElement(Jt,{paddingX:2},Ze.createElement(ii,{color:R.text.secondary},"↑ Page Up / Shift+↑ to scroll up")),Ze.createElement(Jt,{ref:h,height:p?r:void 0,flexDirection:"column",overflowY:p?"scroll":"hidden",overflowX:"hidden",scrollTop:a,flexGrow:1},Ze.createElement(Jt,{flexDirection:"column",flexShrink:0,paddingRight:1},c)),k&&Ze.createElement(Jt,{paddingX:2},Ze.createElement(ii,{color:R.text.secondary},"↓ Page Down / Shift+↓ to scroll down")))}Nt();function fl(){let c=qt(),e=Ue(),{regularQueuedMessages:t,crossDeviceTasks:n}=Fo(),o=zt(),s=ot(),{userTier:r}=Lo(),a=Xt(),l=it(),{handleCommand:u}=Wn(),d=_o(),[p,m]=ml();gl(()=>{c.isLoading&&!p?m(Date.now()):c.isLoading||m(void 0)},[c.isLoading,p]);let h=pl(async()=>{let f=a.pastedTexts.filter(y=>!y.error||y.type==="text");if(a.input.startsWith("/")){await u(a.input);return}if(l.clearPastedTexts(),f.length>0){let{fullInput:y,imageUrls:S,errors:b}=await l.processFilesForSubmit();if(b.length>0&&!y.trim()&&S.length===0){e.addSystemMessage(`Failed to read files:
620
- ${b.map(w=>` - ${w}`).join(`
621
- `)}`);return}e.handleSubmit(y.trim()||"Please analyze this image.",S)}else e.handleSubmit(a.input.trim());l.clearInput()},[a.input,a.pastedTexts,l,e,u]);return Mr({onSubmit:h}),q.createElement(xe,{flexDirection:"column",width:"100%",height:"100%"},q.createElement(ci,{reservedLines:12,autoScrollToBottom:!0,hasFocus:!o.showHelp&&!o.showModelMenu&&!o.showCommandMenu},q.createElement(xe,{flexDirection:"column",paddingX:2,paddingY:1},c.messages.map(f=>q.createElement(oi,{key:f.id,message:f,onSuggestionClick:y=>l.setInput(y)})))),c.todoList&&c.todoList.todos.length>0&&q.createElement(xe,{flexShrink:0},q.createElement(Lr,{todoList:c.todoList})),c.activeTools.size>0&&q.createElement(xe,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Or,{activeTools:c.activeTools})),c.subAgentOperations.size>0&&q.createElement(xe,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(_r,{operations:c.subAgentOperations})),c.pendingConfirmation&&q.createElement(xe,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(Ur,{request:c.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&q.createElement(xe,{paddingX:2,marginBottom:1,flexShrink:0},q.createElement(li,{color:R.text.accent},q.createElement(hl,{type:"dots"})),q.createElement(li,{color:R.text.primary}," Reading files...")),!a.isProcessingFiles&&q.createElement(si,{isLoading:c.isLoading,phrase:c.loadingMessage||"Processing",startTime:p}),(t.length>0||n.length>0)&&q.createElement(xe,{flexShrink:0},q.createElement(Xr,{regularQueuedMessages:t,crossDeviceTasks:n})),o.showCommandMenu&&q.createElement(xe,{flexShrink:0,paddingX:2,marginBottom:0},q.createElement(zr,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:f=>{s.hideCommandMenu(),u(`/${f}`)}})),o.showModelMenu&&q.createElement(xe,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(Hr,{userTier:r,onSelect:f=>{s.setModel(f),s.hideModelMenu()},onAccessDenied:f=>{e.addSystemMessage(ae.getAccessDeniedMessage(f)),s.hideModelMenu()}})),o.showHelp&&q.createElement(xe,{flexShrink:0,paddingX:2,marginBottom:1},q.createElement(Wr,null)),q.createElement(xe,{flexShrink:0,paddingX:2},q.createElement(Vr,{input:a.input,isLoading:c.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition})),q.createElement(ri,{cwd:d,selectedModel:o.selectedModel,showScrollHint:!1}))}function ui({initialProjectPath:c}={}){return q.createElement(Nr,{initialProjectPath:c},q.createElement(fl,null))}rs();ce();ce();import L from"chalk";import Il from"inquirer";import{exec as Pl}from"child_process";var et=class{authService;constructor(){this.authService=H.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,o;n==="darwin"?o=`open "${e}"`:n==="win32"?o=`start "" "${e}"`:o=`xdg-open "${e}"`,Pl(o,s=>{s&&console.log(L.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(L.blue(`
622
- 🔐 Orion Authentication`)),console.log(L.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(L.yellow(`
623
- 📋 Opening browser for authentication...`)),console.log(L.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(L.white(`
624
- 1. Log in with your Orion account in the browser`)),console.log(L.white("2. Copy the access token shown after login")),console.log(L.white("3. Paste the token below")),console.log(L.yellow(`
625
- Paste your access token here:`));let{accessToken:t}=await Il.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(L.gray(`
626
- Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let o=await this.authService.getUserInfo();console.log(L.green(`
627
- ✅ Authentication successful!`)),o&&(console.log(L.gray(`Logged in as: ${o.email||o.username||"User"}`)),console.log(L.gray(`Subscription: ${this.getSubscriptionDisplay(o.subscription?.tier)}`)))}else console.log(L.red(`
628
- ❌ Authentication failed. Please try again.`))}catch(n){console.log(L.red(`
629
- ❌ Authentication error: ${n.message}`))}}async logout(){console.log(L.yellow(`
630
- 🔄 Signing out...`)),console.log(L.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(L.green(`
631
- Successfully signed out`)),console.log(L.gray("All authentication data and settings have been cleared.")),console.log(L.gray('Run "orion auth login" to sign in again.'))):(console.log(L.red(`
632
- ❌ Logout failed`)),console.log(L.gray("Some cleanup operations may have failed, but local data has been cleared.")))}async status(){if(await this.authService.autoAuthenticate(),this.authService.isAuthenticated()){let t=await this.authService.getUserInfo();if(console.log(L.green(`
633
- ✅ Authenticated`)),t){console.log(L.gray("".repeat(50))),console.log(L.white("User:",t.name||t.username||"N/A")),console.log(L.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(L.white("Subscription:",n)),t.usage&&(console.log(L.gray(`
634
- Usage:`)),console.log(L.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(L.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(L.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(L.yellow(`
635
- ⚠️ Not authenticated`)),console.log(L.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};Ie();Co();var Ti=!1;async function is(){let c=process.cwd();if(Ti){console.log("Already running...");return}Ti=!0,F.enableCustomUI();let e=Yt.getInstance(),t=H.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(r){console.error(`
594
+ Type a message to start.`,timestamp:Date.now()}],todoList:null,conversationId:null,conversationTitleGenerated:!1}))},handleSubmit:S,handleConfirmationConfirm:f=>{let v=r.pendingConfirmation?.id;v&&(a(x=>({...x,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:v,response:f,confirmed:!0}))},handleConfirmationDecline:()=>{let f=r.pendingConfirmation?.id;f&&(a(v=>({...v,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:f,response:"n",confirmed:!1}),a(v=>({...v,messages:[...v.messages,{id:ee(),role:"system",content:"[!] Action declined by user",timestamp:Date.now()}]})))},handleConfirmationTimeout:()=>{let f=r.pendingConfirmation?.id;f&&(a(v=>({...v,pendingConfirmation:null})),s.personalAgent.emit("confirmation_response",{confirmationId:f,response:"n",confirmed:!1,timedOut:!0}),a(v=>({...v,messages:[...v.messages,{id:ee(),role:"system",content:"[!] Confirmation timed out - action declined",timestamp:Date.now()}]})))},stopStreaming:()=>{s.personalAgent.stopStreaming(),a(f=>({...f,isLoading:!1,messages:[...f.messages,{id:ee(),role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))}}),[S,s.personalAgent,r.pendingConfirmation]),j=kt(()=>({regularQueuedMessages:E,crossDeviceTasks:b,hasQueuedMessages:P}),[E,b,P]),q=Bo(f=>{p.current=f},[]),N=Bo(f=>{m.current=f},[]),k=kt(()=>({state:r,actions:O,services:s,queue:j,projectPath:t}),[r,O,s,j,t]);return Je(()=>{Ue._updateModelRef=q,Ue._updateVisionRef=N},[q,N]),yc.createElement(Ue.Provider,{value:k},c)}function jt(){let c=zt(Ue);if(!c)throw new Error("useChatState must be used within ChatProvider");return c.state}function Le(){let c=zt(Ue);if(!c)throw new Error("useChatActions must be used within ChatProvider");return c.actions}function Go(){let c=zt(Ue);if(!c)throw new Error("useChatServices must be used within ChatProvider");return c.services}function qo(){let c=zt(Ue);if(!c)throw new Error("useChatQueue must be used within ChatProvider");return c.queue}function zo(){let c=zt(Ue);if(!c)throw new Error("useProjectPath must be used within ChatProvider");return c.projectPath}function Dr(){return Ue}qe();be();Mt();le();import Cc,{createContext as xc,useContext as jo,useState as Ec,useMemo as $n,useEffect as kc}from"react";var Un=xc(null);function Xo({children:c}){let e=$n(()=>Y.find(l=>l.name===Fe.string("selectedPersonalModel"))||Y.find(l=>l.name==="snowx-c5")||Y[0],[]),[t,n]=Ec({showHelp:!1,showModelMenu:!1,showCommandMenu:!1,selectedModel:e,isVisionEnabled:!1}),s=Le();kc(()=>{let l=Dr();l._updateModelRef&&l._updateModelRef(t.selectedModel),l._updateVisionRef&&l._updateVisionRef(t.isVisionEnabled)},[t.selectedModel,t.isVisionEnabled]);let o=$n(()=>({email:z.getInstance().getUserEmail()||"User",tier:ce.getDisplayName(ce.getCurrentUserTier()),userTier:ce.getCurrentUserTier()}),[]),r=$n(()=>({toggleHelp:()=>n(l=>({...l,showHelp:!l.showHelp})),showHelp:()=>n(l=>({...l,showHelp:!0})),hideHelp:()=>n(l=>({...l,showHelp:!1})),toggleModelMenu:()=>n(l=>({...l,showModelMenu:!l.showModelMenu})),showModelMenu:()=>n(l=>({...l,showModelMenu:!0})),hideModelMenu:()=>n(l=>({...l,showModelMenu:!1})),toggleCommandMenu:()=>n(l=>({...l,showCommandMenu:!l.showCommandMenu})),showCommandMenu:()=>n(l=>({...l,showCommandMenu:!0})),hideCommandMenu:()=>n(l=>({...l,showCommandMenu:!1})),setModel:l=>{Fe.set("selectedPersonalModel",l.name),n(u=>({...u,selectedModel:l,showModelMenu:!1})),s.addSystemMessage(`Switched to ${l.displayName}`)},toggleVision:()=>{n(l=>{let u=!l.isVisionEnabled;return s.addSystemMessage(`Vision mode ${u?"enabled":"disabled"}`),{...l,isVisionEnabled:u}})},closeAllModals:()=>n(l=>({...l,showHelp:!1,showModelMenu:!1,showCommandMenu:!1}))}),[s]),a=$n(()=>({state:t,actions:r,info:o}),[t,r,o]);return Cc.createElement(Un.Provider,{value:a},c)}function Xt(){let c=jo(Un);if(!c)throw new Error("useUIState must be used within UIProvider");return c.state}function at(){let c=jo(Un);if(!c)throw new Error("useUIActions must be used within UIProvider");return c.actions}function Vo(){let c=jo(Un);if(!c)throw new Error("useUIInfo must be used within UIProvider");return c.info}import Dc,{createContext as Nc,useContext as Lr,useState as Rc,useMemo as Ur,useRef as Mc}from"react";import Wn from"path";import Ko from"fs";import ct from"path";import Ic from"os";var Mr={".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"},_r=Object.keys(Mr),Pc=[..._r,".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"],Nr=20*1024*1024,Rr=1*1024*1024;function Ye(c){return c<1024?`${c}B`:c<1024*1024?`${(c/1024).toFixed(1)}KB`:`${(c/(1024*1024)).toFixed(1)}MB`}function Qo(c,e=30){if(c.length<=e)return c;let t=ct.extname(c);return ct.basename(c,t).slice(0,e-t.length-3)+"..."+t}function Or(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(`
595
+ `))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let t=e.startsWith("/"),n=/^[A-Za-z]:[\\\/]/.test(e),s=e.startsWith("./")||e.startsWith("../"),o=e.startsWith("~/");if(!(t||n||s||o))return{isFilePath:!1,isImage:!1,isBinary:!1,path:""};let a=e.toLowerCase(),l=ct.extname(a),u=_r.includes(l),d=Pc.includes(l);return{isFilePath:!0,isImage:u,isBinary:d,path:e}}function Ac(c){return c.startsWith("~/")?ct.join(Ic.homedir(),c.slice(2)):c}function Jo(c){let e=Ac(c);return ct.isAbsolute(e)?e:ct.resolve(process.cwd(),e)}function Ln(c){try{let e=Jo(c),t=Ko.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 Fr(c){try{let e=Jo(c),t=Ln(c);if(!t.exists)return{data:null,error:t.error};if(t.size>Nr)return{data:null,error:`Image too large (${Ye(t.size)}, max ${Ye(Nr)})`};let n=Ko.readFileSync(e),s=ct.extname(c).toLowerCase(),o=Mr[s]||"image/png",r=n.toString("base64");return{data:`data:${o};base64,${r}`}}catch(e){return{data:null,error:e.message}}}function $r(c){try{let e=Jo(c),t=Ln(c);return t.exists?t.size>Rr?{content:null,error:`File too large (${Ye(t.size)}, max ${Ye(Rr)})`}:{content:Ko.readFileSync(e,"utf8")}:{content:null,error:t.error}}catch(e){return{content:null,error:e.message}}}var Yo=Nc(null);function Zo({children:c}){let[e,t]=Rc({input:"",cursorPosition:0,pastedTexts:[],isProcessingFiles:!1,suggestion:null}),n=Mc(0),s=Ur(()=>({setInput:r=>{t(a=>({...a,input:r,cursorPosition:r.length}))},setCursor:r=>{t(a=>({...a,cursorPosition:Math.max(0,Math.min(r,a.input.length))}))},insertAtCursor:r=>{t(a=>{let l=a.input.slice(0,a.cursorPosition)+r+a.input.slice(a.cursorPosition);return{...a,input:l,cursorPosition:a.cursorPosition+r.length}})},deleteAtCursor:()=>{t(r=>{if(r.input===""&&r.pastedTexts.length>0)return{...r,pastedTexts:r.pastedTexts.slice(0,-1)};if(r.cursorPosition===0)return r;let a=r.input.slice(0,r.cursorPosition-1)+r.input.slice(r.cursorPosition);return{...r,input:a,cursorPosition:r.cursorPosition-1}})},clearInput:()=>{t(r=>({...r,input:"",cursorPosition:0,pastedTexts:[],suggestion:null}))},moveCursorLeft:()=>{t(r=>({...r,cursorPosition:Math.max(0,r.cursorPosition-1)}))},moveCursorRight:()=>{t(r=>({...r,cursorPosition:Math.min(r.input.length,r.cursorPosition+1)}))},moveCursorToStart:()=>{t(r=>({...r,cursorPosition:0}))},moveCursorToEnd:()=>{t(r=>({...r,cursorPosition:r.input.length}))},addPastedContent:r=>{let a=Or(r),l=r.split(`
596
+ `);n.current+=1;let u="text",d,p;if(a.isFilePath){a.isImage?u="image_path":a.isBinary?(u="file_path",p="Binary file - cannot read as text"):u="file_path";let m=Ln(a.path);m.exists?d=m.size:p=m.error}t(m=>({...m,pastedTexts:[...m.pastedTexts,{id:n.current,content:r,lineCount:l.length,type:u,filePath:a.isFilePath?a.path:void 0,fileSize:d,error:p}]}))},addClipboardImage:(r,a)=>{n.current+=1,t(l=>({...l,pastedTexts:[...l.pastedTexts,{id:n.current,content:"Clipboard image",lineCount:1,type:"clipboard_image",imageData:r,fileSize:a}]}))},clearPastedTexts:()=>{t(r=>({...r,pastedTexts:[]}))},removeLastPaste:()=>{t(r=>({...r,pastedTexts:r.pastedTexts.slice(0,-1)}))},processFilesForSubmit:async()=>{t(r=>({...r,isProcessingFiles:!0}));try{let r=e,a=r.pastedTexts.filter(w=>w.type==="image_path"&&w.filePath),l=r.pastedTexts.filter(w=>w.type==="clipboard_image"&&w.imageData),u=r.pastedTexts.filter(w=>w.type==="file_path"&&w.filePath),d=r.pastedTexts.filter(w=>w.type==="text"),p=[],m=[],g=[];for(let w of u)if(w.filePath&&!w.error){let E=$r(w.filePath);if(E.content){let b=Wn.basename(w.filePath),C=Wn.extname(b).slice(1)||"text";m.push(`[File: ${b}]
597
+ \`\`\`${C}
598
+ ${E.content}
599
+ \`\`\``)}else E.error&&g.push(`${Wn.basename(w.filePath)}: ${E.error}`)}for(let w of a)if(w.filePath&&!w.error){let E=await Fr(w.filePath);E.data?p.push(E.data):E.error&&g.push(`${Wn.basename(w.filePath)}: ${E.error}`)}for(let w of l)w.imageData&&!w.error&&p.push(w.imageData);let h=d.map(w=>w.content).join(`
600
+
601
+ `),y=m.join(`
602
+
603
+ `),T=[h,y].filter(Boolean).join(`
604
+
605
+ `);return{fullInput:T?r.input.trim()?`${T}
606
+
607
+ ${r.input}`:T:r.input,imageUrls:p,errors:g}}finally{t(r=>({...r,isProcessingFiles:!1}))}},setSuggestion:r=>{t(a=>({...a,suggestion:r}))},acceptSuggestion:()=>{t(r=>{if(!r.suggestion)return r;let a=r.suggestion.startsWith(r.input)?r.suggestion.slice(r.input.length):r.suggestion,l=r.input+a;return{...r,input:l,cursorPosition:l.length,suggestion:null}})}}),[e]),o=Ur(()=>({state:e,actions:s}),[e,s]);return Dc.createElement(Yo.Provider,{value:o},c)}function Vt(){let c=Lr(Yo);if(!c)throw new Error("useInputState must be used within InputProvider");return c.state}function lt(){let c=Lr(Yo);if(!c)throw new Error("useInputActions must be used within InputProvider");return c.actions}import Fc,{createContext as $c,useContext as mf,useCallback as Hn,useRef as Br,useEffect as Uc}from"react";import{EventEmitter as Oc}from"events";function Wr(){process.stdout.write("\x1B[?1006l\x1B[?1002l")}var Bn=new Oc;Bn.setMaxListeners(50);var Lc=$c(null);function es({children:c,enableMouse:e=!0}){let t=Br(new Set),n=Br(new Set),s=Hn(l=>{t.current.add(l)},[]),o=Hn(l=>{t.current.delete(l)},[]),r=Hn(l=>{n.current.add(l)},[]),a=Hn(l=>{n.current.delete(l)},[]);return Uc(()=>{if(!e)return;let l=u=>{for(let d of t.current)d(u);if(u.name==="scroll-up")for(let d of n.current)d("up");else if(u.name==="scroll-down")for(let d of n.current)d("down")};return Bn.on("mouse",l),()=>{Bn.off("mouse",l)}},[e]),Fc.createElement(Lc.Provider,{value:{subscribe:s,unsubscribe:o,subscribeScroll:r,unsubscribeScroll:a,isMouseEnabled:e}},c)}function Hr({children:c,initialProjectPath:e}){return Gn.createElement(es,{enableMouse:!1},Gn.createElement(Ho,{initialProjectPath:e},Gn.createElement(Xo,null,Gn.createElement(Zo,null,c))))}import{useRef as Xn,useEffect as Bc}from"react";import{useInput as Hc,useApp as Gc}from"@jrichman/ink";import{useCallback as zr}from"react";import{useApp as Wc}from"@jrichman/ink";import{execSync as Gr}from"child_process";import qr from"os";import We from"fs";function qn(){if(qr.platform()!=="darwin")return!1;try{let c=Gr('osascript -e "clipboard info"',{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]});return c.includes("PNGf")||c.includes("TIFF")||c.includes("JPEG")||c.includes("jp2")||c.includes("GIF")||c.includes("BMP")}catch{return!1}}async function zn(){if(qr.platform()!=="darwin")return{data:null,size:0,error:"Clipboard image not supported on this platform"};let c=Date.now(),e=`/tmp/clipboard-image-${c}.png`,t=`/tmp/clipboard-script-${c}.scpt`;try{let n=`use framework "AppKit"
608
+ use scripting additions
609
+
610
+ set theClipboard to current application's NSPasteboard's generalPasteboard()
611
+ set imageData to theClipboard's dataForType:(current application's NSPasteboardTypePNG)
612
+
613
+ if imageData is not missing value then
614
+ set filePath to "${e}"
615
+ imageData's writeToFile:filePath atomically:true
616
+ return "success"
617
+ else
618
+ return "error:No PNG image in clipboard"
619
+ end if
620
+ `;We.writeFileSync(t,n);let s;try{s=Gr(`osascript "${t}"`,{encoding:"utf8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim()}finally{try{We.unlinkSync(t)}catch{}}if(s.startsWith("error:"))return{data:null,size:0,error:s.replace("error:","")};if(!We.existsSync(e))return{data:null,size:0,error:"Failed to save clipboard image"};let o=We.readFileSync(e),r=o.length,l=`data:image/png;base64,${o.toString("base64")}`;try{We.unlinkSync(e)}catch{}return{data:l,size:r}}catch(n){try{We.existsSync(e)&&We.unlinkSync(e),We.existsSync(t)&&We.unlinkSync(t)}catch{}return{data:null,size:0,error:n.message||"Failed to read clipboard image"}}}function jn(){let{exit:c}=Wc(),e=Le(),t=Go(),n=at(),s=lt(),o=zr(a=>a.startsWith("/"),[]);return{handleCommand:zr(async a=>{if(!a.startsWith("/"))return{handled:!1};let l=a.toLowerCase().trim();if(l==="/help"||l==="/?")return n.showCommandMenu(),s.clearInput(),{handled:!0,clearInput:!0};if(l==="/model")return n.showModelMenu(),s.clearInput(),{handled:!0,clearInput:!0};if(l==="/clear"||l==="/new")return e.clearChat(),s.clearInput(),{handled:!0,clearInput:!0};if(l==="/vision")return n.toggleVision(),s.clearInput(),{handled:!0,clearInput:!0};if(l==="/exit"||l==="/quit")return c(),{handled:!0};if(l==="/stop")return e.stopStreaming(),s.clearInput(),{handled:!0,clearInput:!0};if(l==="/img"||l==="/image"||l==="/paste"){if(s.clearInput(),!qn())return e.addSystemMessage("[!] No image found in clipboard"),{handled:!0,clearInput:!0};try{let u=await zn();u.data?(s.addClipboardImage(u.data,u.size),e.addSystemMessage("[OK] Image added from clipboard")):e.addSystemMessage(`[!] Failed to read clipboard image: ${u.error||"Unknown error"}`)}catch(u){e.addSystemMessage(`[!] Error reading clipboard: ${u.message}`)}return{handled:!0,clearInput:!0}}if(l==="/signout"){e.addSystemMessage("[...] Signing out..."),s.clearInput();try{await t.authService.signOut()&&(e.addSystemMessage("[OK] Successfully signed out. Goodbye!"),setTimeout(()=>c(),1e3))}catch(u){e.addSystemMessage(`[ERROR] ${u.message}`)}return{handled:!0,clearInput:!0}}return e.addSystemMessage(`Unknown command: ${a}
621
+
622
+ Type /help to see available commands.`),s.clearInput(),{handled:!0,clearInput:!0}},[c,e,t.authService,n,s]),isCommand:o}}function jr({onSubmit:c}){let{exit:e}=Gc(),t=jt(),n=Le(),s=Xt(),o=at(),r=Vt(),a=lt(),{handleCommand:l,isCommand:u}=jn(),d=Xn(""),p=Xn(null),m=Xn(0),g=Xn(!1);return Bc(()=>()=>{p.current&&clearTimeout(p.current)},[]),Hc((h,y)=>{if(!(h.startsWith("[<")||h.startsWith("[M")||/^\[<?\d+;\d+;\d+[mM]?/.test(h)||/^\d+[mM]/.test(h)||/^;\d+;\d+[mM]/.test(h)||/^\d+;\d+[mM]/.test(h))){if(y.escape){if(t.isLoading){n.stopStreaming();return}if(s.showModelMenu||s.showCommandMenu){o.closeAllModals(),s.showCommandMenu&&r.input==="/"&&a.clearInput();return}if(s.showHelp){o.hideHelp();return}if(r.pastedTexts.length>0){a.clearPastedTexts();return}return}if(!s.showModelMenu&&!(s.showCommandMenu&&(y.upArrow||y.downArrow||y.return))){if(y.ctrl&&h==="l"){process.stdout.write("\x1B[2J\x1B[H");return}if(y.ctrl&&h==="c"){t.isLoading?n.stopStreaming():e();return}if(h===""||y.ctrl&&h==="v"){if(g.current)return;if(qn()){g.current=!0,zn().then(T=>{g.current=!1,T.data&&a.addClipboardImage(T.data,T.size)}).catch(()=>{g.current=!1});return}return}if(y.tab){r.suggestion&&a.acceptSuggestion();return}if(h==="?"&&r.input===""&&!s.showCommandMenu){o.toggleHelp();return}if(y.return){let T=r.pastedTexts.filter(w=>!w.error||w.type==="text");(r.input.trim()||T.length>0)&&c();return}if(y.leftArrow){a.moveCursorLeft();return}if(y.rightArrow){a.moveCursorRight();return}if(y.home){a.moveCursorToStart();return}if(y.end){a.moveCursorToEnd();return}if(y.delete||y.backspace){a.deleteAtCursor(),s.showCommandMenu&&((r.input.slice(0,r.cursorPosition-1)+r.input.slice(r.cursorPosition)).startsWith("/")||o.hideCommandMenu());return}if(!y.ctrl&&!y.meta&&h){let T=Date.now(),S=T-m.current;m.current=T;let w=S<50,E=h.includes(`
623
+ `),b=h.length>50;if(E||b){p.current&&(clearTimeout(p.current),p.current=null);let O=d.current+h;d.current="",a.addPastedContent(O);return}if(w&&h.length===1){d.current+=h,p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{let O=d.current;d.current="",p.current=null,O&&(a.insertAtCursor(O),r.input===""&&O==="/"&&o.showCommandMenu())},100);return}p.current&&(clearTimeout(p.current),p.current=null);let C=d.current;d.current="";let P=C+h;a.insertAtCursor(P),r.input.slice(0,r.cursorPosition)+P+r.input.slice(r.cursorPosition)==="/"&&!s.showCommandMenu&&o.showCommandMenu()}}}}),{handleCommand:l,isCommand:u}}import oe from"react";import{Box as Vn,Text as Be}from"@jrichman/ink";import qc from"ink-spinner";function zc(c,e){let t=c.toLowerCase(),n=e?.description;if(t==="bash"||t==="command"||t==="run_command"){let o=e?.command,r=n&&n.length<50?n:"Running command",a=o?`$ ${o.substring(0,80)}`:void 0;return{title:r,details:a}}if(t==="read"||t==="readfile"){let o=e?.file_path,r=e?.offset,a=e?.limit,l=o;return l&&(r!==void 0||a!==void 0)&&(l+=` (lines ${r||0}-${a?(r||0)+a:"end"})`),{title:"Reading",details:l}}if(t==="write"||t==="writefile"){let o=e?.file_path,r=e?.content;return{title:"Writing",details:o?r?`${o} (${r.length} bytes)`:o:void 0}}if(t==="edit"||t==="editfile")return{title:"Editing",details:e?.file_path};if(t==="grep"){let o=e?.pattern,r=e?.path;return{title:"Searching",details:o?`"${o}"${r?` in ${r}`:""}`:void 0}}if(t==="glob"){let o=e?.pattern,r=e?.path;return{title:"Finding files",details:o?r?`${o} in ${r}`:o:void 0}}if(t==="webfetch"||t==="web_fetch"){let o=e?.url;return{title:"Fetching URL",details:o?o.substring(0,60):void 0}}if(t==="task"){let o=e?.description,r=e?.subagent_type;return{title:r?`Agent: ${r}`:"Running agent",details:o?o.substring(0,60):void 0}}if(t==="websearch"||t==="web_search"||t==="search_tool"){let o=e?.query;return{title:"Searching web",details:o?`"${o}"`:void 0}}if(t==="read_url"||t==="readurl"){let o=e?.url,r=e?.format;return{title:"Reading URL",details:o?r?`${o} (${r})`:o:void 0}}if(t==="map_url"||t==="mapurl"){let o=e?.url,r=e?.search;return{title:"Mapping URL",details:o?r?`${o} → "${r}"`:o:void 0}}if(t==="generate_image"||t==="generateimage"||t==="image_generation"){let o=e?.prompt,r=e?.style,a=o?`"${o.substring(0,50)}"`:void 0;return a&&r&&(a+=` • ${r}`),{title:"Generating image",details:a}}if(t==="edit_image"||t==="editimage"){let o=e?.prompt;return{title:"Editing image",details:o?`"${o.substring(0,60)}"`:void 0}}if(t==="examine_image"||t==="examineimage"){let o=e?.question;return{title:"Examining image",details:o?`"${o.substring(0,60)}"`:void 0}}if(t==="generate_video_from_text"||t==="generate_video_from_text_sora"){let o=e?.prompt,r=e?.duration,a=o?`"${o.substring(0,50)}"`:void 0;return a&&r&&(a+=` • ${r}s`),{title:"Generating video",details:a}}if(t==="generate_video_from_image"||t==="generate_video_from_image_sora"){let o=e?.prompt;return{title:"Video from image",details:o?`"${o.substring(0,60)}"`:void 0}}if(t==="merge_videos_into_one"){let o=e?.video_urls?.length||e?.videos?.length;return{title:"Merging videos",details:o?`${o} videos`:void 0}}if(t==="generate_music"||t==="generatemusic"){let o=e?.prompt,r=e?.style,a=o?`"${o.substring(0,50)}"`:void 0;return a&&r&&(a+=` • ${r}`),{title:"Generating music",details:a}}if(t==="get_current_weather"||t==="getcurrentweather")return{title:"Getting weather",details:e?.location};if(t==="get_weather_forecast"||t==="getweatherforecast"){let o=e?.location,r=e?.days;return{title:"Getting forecast",details:o?r?`${o} (${r} days)`:o:void 0}}if(t==="search_flights"||t==="searchflights"){let o=e?.origin,r=e?.destination,a=e?.departure_date,l=o&&r?`${o} → ${r}`:void 0;return l&&a&&(l+=` • ${a}`),{title:"Searching flights",details:l}}if(t==="search_hotels"||t==="searchhotels"){let o=e?.location,r=e?.checkin_date;return{title:"Searching hotels",details:o?r?`${o} • ${r}`:o:void 0}}if(t==="calendar_list_events")return{title:"Listing calendar events"};if(t==="calendar_create_event")return{title:"Creating event",details:e?.summary};if(t==="calendar_delete_event")return{title:"Deleting event",details:e?.event_id};if(t==="calendar_update_event")return{title:"Updating event",details:e?.event_id};if(t==="slack_send_message"){let o=e?.channel,r=e?.message,a=o?`#${o}`:void 0;return a&&r&&(a+=` → "${r.substring(0,30)}"`),{title:"Sending Slack",details:a}}if(t==="slack_list_channels")return{title:"Listing Slack channels"};if(t==="slack_get_channel_history"){let o=e?.channel;return{title:"Getting Slack history",details:o?`#${o}`:void 0}}if(t==="discord_send_message"){let o=e?.channel_id,r=e?.content,a=o?`Channel: ${o}`:void 0;return a&&r&&(a+=` → "${r.substring(0,30)}"`),{title:"Sending Discord",details:a}}if(t==="discord_list_guilds")return{title:"Listing Discord servers"};if(t==="discord_list_channels"){let o=e?.guild_id;return{title:"Listing Discord channels",details:o?`Server: ${o}`:void 0}}if(t==="jira_list_projects")return{title:"Listing Jira projects"};if(t==="jira_search_issues"){let o=e?.jql;return{title:"Searching Jira",details:o?o.substring(0,60):void 0}}if(t==="jira_get_issue")return{title:"Getting Jira issue",details:e?.issue_key};if(t==="jira_create_issue"){let o=e?.summary,r=e?.project_key;return{title:"Creating Jira issue",details:o?r?`[${r}] ${o}`:o:void 0}}if(t==="jira_add_comment")return{title:"Adding Jira comment",details:e?.issue_key};if(t==="googledrive_list_files"){let o=e?.folder_id;return{title:"Listing Drive files",details:o?`Folder: ${o}`:void 0}}if(t==="googledrive_search_files"){let o=e?.query;return{title:"Searching Drive",details:o?`"${o}"`:void 0}}if(t==="googledrive_read_doc"||t==="googledrive_get_file")return{title:"Reading Drive file",details:e?.file_id};if(t==="googledrive_upload_file")return{title:"Uploading to Drive",details:e?.file_path};if(t==="googledrive_read_sheet")return{title:"Reading spreadsheet",details:e?.file_id};if(t==="gmail_send_email"){let o=e?.to,r=e?.subject;return{title:"Sending email",details:o?r?`To: ${o} • ${r}`:`To: ${o}`:void 0}}if(t==="gmail_read_emails"){let o=e?.max_results;return{title:"Reading emails",details:o?`${o} emails`:void 0}}if(t==="gmail_search_emails"){let o=e?.query;return{title:"Searching emails",details:o?`"${o}"`:void 0}}if(t==="bigquery_run_query"){let o=e?.query;return{title:"Running query",details:o?o.substring(0,60):void 0}}if(t.startsWith("bigquery_list"))return{title:"Listing BigQuery resources"};if(t==="schedule_one_time_task"){let o=e?.task_description;return{title:"Scheduling task",details:o?o.substring(0,60):void 0}}if(t==="schedule_recurring_task"){let o=e?.task_description;return{title:"Scheduling recurring",details:o?o.substring(0,60):void 0}}if(t==="list_scheduled_tasks")return{title:"Listing scheduled tasks"};if(t==="cancel_scheduled_task")return{title:"Cancelling task",details:e?.task_id};if(t==="linkedin_create_post"){let o=e?.content;return{title:"Posting to LinkedIn",details:o?`"${o.substring(0,50)}"`:void 0}}if(t==="x_create_tweet"){let o=e?.text;return{title:"Posting tweet",details:o?`"${o.substring(0,50)}"`:void 0}}if(t==="x_get_home_timeline")return{title:"Getting timeline"};if(t==="query_memory"||t==="retrieve_user_memories"){let o=e?.query;return{title:"Retrieving memories",details:o?`"${o}"`:void 0}}if(t==="add_memory"||t==="store_user_memory"){let o=e?.content||e?.memory;return{title:"Storing memory",details:o?`"${o.substring(0,50)}"`:void 0}}if(t==="operator_run_task"){let o=e?.task;return{title:"Running browser task",details:o?o.substring(0,60):void 0}}if(t==="get_user_devices")return{title:"Getting devices"};if(t==="communicate_with_other_orion")return{title:"Communicating with device",details:e?.device_name};if(t==="search_contacts"){let o=e?.query;return{title:"Searching contacts",details:o?`"${o}"`:void 0}}if(t==="compose_message"||t==="send_sms"){let o=e?.recipient||e?.phone_number;return{title:"Composing message",details:o?`To: ${o}`:void 0}}if(t==="make_phone_call")return{title:"Making call",details:e?.phone_number};if(t==="open_url")return{title:"Opening URL",details:e?.url};if(t==="get_location")return{title:"Getting location"};if(t==="spawn_agents"){let o=e?.agents?.length;return{title:"Spawning agents",details:o?`${o} agents`:void 0}}if(t==="todo_write"||t==="todowrite")return{title:"Updating todos"};if(n&&n.length<60){let o=Xr(e);return o?{title:n,details:o}:{title:n}}let s=Xr(e);return s?{title:c,details:s}:{title:c}}function Xr(c){if(!c||Object.keys(c).length===0)return;let e=["query","prompt","url","file_path","path","content","message","text","command","task","name","title"],t=Object.entries(c).filter(([n])=>n!=="description"&&!n.startsWith("_")).sort(([n],[s])=>{let o=e.indexOf(n.toLowerCase()),r=e.indexOf(s.toLowerCase());return o===-1&&r===-1?0:o===-1?1:r===-1?-1:o-r}).slice(0,2);if(t.length!==0)return t.map(([n,s])=>{let o=n.replace(/_/g," "),r;return typeof s=="string"?r=s.length<40?s:s.substring(0,37)+"...":typeof s=="number"||typeof s=="boolean"?r=String(s):Array.isArray(s)?r=`[${s.length}]`:r="{...}",`${o}: ${r}`}).join(" • ")}function ts({tool:c}){let{title:e,details:t}=zc(c.name,c.arguments),n=c.state==="running",s=c.state==="completed",o=c.state==="failed",r=t?t.length>60?t.substring(0,57)+"...":t:void 0;return oe.createElement(Vn,null,n&&oe.createElement(Be,{color:"cyan"},oe.createElement(qc,{type:"dots"})),s&&oe.createElement(Be,{color:"#5AD8A6"},"✓"),o&&oe.createElement(Be,{color:"#F5716C"},"✗"),oe.createElement(Be,null," "),oe.createElement(Be,{color:n?"whiteBright":"#9CA3AF"},e),r?oe.createElement(Be,{color:"#6B7280"}," ",r):n?oe.createElement(Be,{color:"#6B7280"}," ..."):null)}function Vr({activeTools:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([a,l])=>l.name.toLowerCase().replace(/_/g,"")!=="todowrite");if(e.length===0)return null;let t=e.filter(([a,l])=>l.state==="running"),n=e.filter(([a,l])=>l.state==="completed"),s=e.filter(([a,l])=>l.state==="failed"),o=n.slice(-3),r=n.length-o.length;return oe.createElement(Vn,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1},t.map(([a,l])=>oe.createElement(ts,{key:a,tool:l})),o.map(([a,l])=>oe.createElement(ts,{key:a,tool:l})),s.map(([a,l])=>oe.createElement(Vn,{key:a,flexDirection:"column"},oe.createElement(ts,{tool:l}),l.error&&oe.createElement(Vn,{marginLeft:2},oe.createElement(Be,{color:"#F5716C"},l.error.substring(0,60))))),r>0&&oe.createElement(Be,{color:"#6B7280"}," +",r," more completed"))}import X from"react";import{Box as He,Text as se}from"@jrichman/ink";import Kr from"ink-spinner";function jc(c,e=60){return c?c.length<=e?c:c.substring(0,e-3)+"...":"Processing..."}function Xc({agent:c}){let e=jc(c.task||"Working..."),t=o=>{switch(o){case"running":return"cyan";case"completed":return"#5AD8A6";case"failed":return"#F5716C";case"timeout":return"#FBBF24";default:return"#6B7280"}},n=()=>c.status==="running"?X.createElement(se,{color:"cyan"},X.createElement(Kr,{type:"dots"})):c.status==="completed"?X.createElement(se,{color:"#5AD8A6"},"[done]"):c.status==="failed"?X.createElement(se,{color:"#F5716C"},"[fail]"):c.status==="timeout"?X.createElement(se,{color:"#FBBF24"},"[time]"):X.createElement(se,{color:"#6B7280"},"[ ]"),s=t(c.status);return X.createElement(He,{flexDirection:"column",marginLeft:2},X.createElement(He,null,n(),X.createElement(se,{color:s,bold:!0}," Agent #",c.agentNumber)),X.createElement(He,{marginLeft:2},X.createElement(se,{color:"#9CA3AF"},e)),c.error&&X.createElement(He,{marginLeft:2},X.createElement(se,{color:"#F5716C"},"Error: ",c.error.substring(0,60),c.error.length>60?"...":"")),c.streamingContent&&c.status==="running"&&X.createElement(He,{marginLeft:2},X.createElement(se,{color:"#6B7280"},c.streamingContent.split(`
624
+ `)[0]?.substring(0,50),"...")))}function Vc({operation:c}){let e=Array.from(c.agents.values()).sort((u,d)=>u.agentNumber-d.agentNumber),t=e.filter(u=>u.status==="completed").length,n=e.filter(u=>u.status==="failed").length,s=e.filter(u=>u.status==="running").length,o=c.totalAgents,r=()=>c.status==="starting"||c.status==="running"?`Spawning ${o} agents`:c.status==="completed"?`${o} agents completed`:"Operation failed",a=()=>c.status==="running"||c.status==="starting"?X.createElement(se,{color:"cyan"},X.createElement(Kr,{type:"dots"})):c.status==="completed"?X.createElement(se,{color:"#5AD8A6"},"[done]"):X.createElement(se,{color:"#F5716C"},"[fail]"),l=c.status==="completed"?"#5AD8A6":c.status==="failed"?"#F5716C":"cyan";return X.createElement(He,{flexDirection:"column"},X.createElement(He,null,a(),X.createElement(se,{color:l,bold:!0}," ",r()),X.createElement(se,{color:"#6B7280"}," "),X.createElement(se,{backgroundColor:"#3F3F46",color:"whiteBright"}," ",t,"/",o," "),s>0&&X.createElement(se,{color:"cyan"}," (",s," running)"),n>0&&X.createElement(se,{color:"#F5716C"}," [",n," failed]")),X.createElement(He,{flexDirection:"column",marginTop:1},e.map(u=>X.createElement(Xc,{key:u.agentNumber,agent:u}))))}function Qr({operations:c}){if(c.size===0)return null;let e=Array.from(c.entries()).filter(([t,n])=>n.status==="running"||n.status==="starting"?!0:n.endTime?Date.now()-n.endTime.getTime()<1e4:!0);return e.length===0?null:X.createElement(He,{flexDirection:"column",borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},e.map(([t,n])=>X.createElement(Vc,{key:t,operation:n})))}import Ne,{useState as Kc,useEffect as Qc,useRef as Jr}from"react";import{Box as Kt,Text as Qt}from"@jrichman/ink";import Jc from"ink-select-input";function Yr({request:c,onConfirm:e,onDecline:t,onTimeout:n}){let[s,o]=Kc(c.timeout?Math.ceil(c.timeout/1e3):null),r=Jr(null),a=Jr(0);Qc(()=>{if(c.timeout)return a.current=Date.now(),o(Math.ceil(c.timeout/1e3)),r.current=setInterval(()=>{let m=Date.now()-a.current,g=Math.max(0,c.timeout-m),h=Math.ceil(g/1e3);o(h),g<=0&&(r.current&&clearInterval(r.current),n?.())},1e3),()=>{r.current&&clearInterval(r.current)}},[c.timeout,n]);let l=[{label:"Yes, proceed",value:"confirm"},{label:"No, cancel",value:"decline"}],u=m=>{r.current&&(clearInterval(r.current),r.current=null),m.value==="confirm"?e("y"):t()},d=c.targets?.filter(m=>m.startsWith("/")||m.startsWith("./")||m.startsWith("~/")).slice(0,3)||[],p=c.command&&c.command.length>60?c.command.substring(0,57)+"...":c.command;return Ne.createElement(Kt,{flexDirection:"column",borderStyle:"round",borderColor:"#525252",paddingX:2,paddingY:1},Ne.createElement(Qt,{color:"white",bold:!0},c.title),p&&Ne.createElement(Kt,{marginTop:1},Ne.createElement(Qt,{color:"gray"},"$ "),Ne.createElement(Qt,{color:"white"},p)),d.length>0&&Ne.createElement(Kt,{marginTop:1,flexDirection:"column"},d.map((m,g)=>Ne.createElement(Qt,{key:g,color:"gray"}," ",m))),s!==null&&Ne.createElement(Kt,{marginTop:1},Ne.createElement(Qt,{color:"yellow"},"Auto-cancel in ",s,"s")),Ne.createElement(Kt,{marginTop:1},Ne.createElement(Jc,{items:l,onSelect:u})))}import xe from"react";import{Box as Jt,Text as ut}from"@jrichman/ink";var Yc=8;function Zr({todoList:c}){if(!c||c.todos.length===0)return null;let e=c.todos.filter(r=>r.status!=="completed"),t=c.todos.filter(r=>r.status==="completed"),n=e.length===0&&t.length>0,s=[...e,...t.slice(-2)].slice(0,Yc),o=c.todos.length-s.length;return xe.createElement(Jt,{paddingX:2,marginBottom:1},xe.createElement(Jt,{borderStyle:"round",borderColor:n?"#5AD8A6":"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column"},xe.createElement(Jt,{marginBottom:1},xe.createElement(ut,{color:"whiteBright",bold:!0},"Tasks"),xe.createElement(ut,{color:"#6B7280"}," - "),xe.createElement(ut,{color:n?"#5AD8A6":"#9CA3AF"},t.length,"/",c.todos.length,n&&" ✓")),s.map((r,a)=>{let l=r.status==="completed"?"[done]":r.status==="in_progress"?"[..]":"[ ]",u=r.status==="completed"?"#5AD8A6":r.status==="in_progress"?"cyan":"#6B7280",d=r.status==="in_progress"&&r.activeForm?r.activeForm:Tr(r);return xe.createElement(Jt,{key:r.id||`todo-${a}`},xe.createElement(ut,{color:u},l),xe.createElement(ut,{color:"#6B7280"}," "),xe.createElement(ut,{color:r.status==="completed"?"#6B7280":"whiteBright"},d))}),o>0&&xe.createElement(Jt,{marginTop:0},xe.createElement(ut,{color:"#6B7280"}," +",o," more tasks"))))}import re from"react";import{Box as ns,Text as he}from"@jrichman/ink";function ei(){return re.createElement(ns,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},re.createElement(he,{bold:!0,color:"whiteBright"},"Keyboard Shortcuts"),re.createElement(ns,{marginTop:1,flexDirection:"column"},re.createElement(he,{color:"#9CA3AF"},"• ",re.createElement(he,{color:"whiteBright",bold:!0},"Enter")," ",re.createElement(he,{color:"#9CA3AF"},"Submit message")),re.createElement(he,{color:"#9CA3AF"},"• ",re.createElement(he,{color:"whiteBright",bold:!0},"?")," ",re.createElement(he,{color:"#9CA3AF"},"Toggle this help")),re.createElement(he,{color:"#9CA3AF"},"• ",re.createElement(he,{color:"whiteBright",bold:!0},"Esc")," ",re.createElement(he,{color:"#9CA3AF"},"Stop generation / Close menus")),re.createElement(he,{color:"#9CA3AF"},"• ",re.createElement(he,{color:"whiteBright",bold:!0},"Ctrl+C")," ",re.createElement(he,{color:"#9CA3AF"},"Stop generation / Exit"))),re.createElement(ns,{marginTop:1},re.createElement(he,{color:"#6B7280"},"Press Esc to close")))}import fe from"react";import{Box as Qn,Text as Ge}from"@jrichman/ink";import It,{useState as Zc,useEffect as el}from"react";import{Box as os,Text as ti,useInput as tl}from"@jrichman/ink";function nl({item:c,isSelected:e,highlightColor:t}){return It.createElement(ti,{color:e?"#000":"#fff",backgroundColor:e?t:void 0},c.label)}function Kn({items:c,onSelect:e,onHighlight:t,isFocused:n=!0,highlightColor:s="#D97706",itemComponent:o=nl}){let[r,a]=Zc(0);return el(()=>{a(0)},[c.length]),tl((l,u)=>{if(n){if(u.upArrow){let d=r>0?r-1:c.length-1;a(d),t?.(c[d])}if(u.downArrow){let d=r<c.length-1?r+1:0;a(d),t?.(c[d])}if(u.return){let d=c[r];d&&e(d)}}},{isActive:n}),c.length===0?It.createElement(os,null,It.createElement(ti,{color:"#6B7280"},"No items")):It.createElement(os,{flexDirection:"column"},c.map((l,u)=>{let d=u===r;return It.createElement(os,{key:l.value||u},It.createElement(o,{item:l,isSelected:d,highlightColor:s}))}))}qe();Mt();function ni({userTier:c,onSelect:e,onAccessDenied:t}){let n=p=>{switch(p){case .5:return"[0.5x]";case 1:return"[1x]";case 2:return"[2x]"}},s=Y.filter(p=>p.name.startsWith("snowx-o4")||p.name.startsWith("snowx-c")||p.name.startsWith("snowx-h")),o=Y.filter(p=>p.name.startsWith("snowx-5")||p.name.startsWith("snowx-o3")||p.name.startsWith("snowx-4")),r=Y.filter(p=>p.name.startsWith("snowx-g")),a=p=>p.map(m=>{let g=ce.isModelAccessible(m.name,c),h=n(m.creditMultiplier);return{label:`${g?"":"[LOCKED] "}${m.displayName} ${h}`,value:m.name,isAccessible:g,creditMultiplier:m.creditMultiplier,isHeader:!1}}),l=[{label:"-- Claude --",value:"_claude_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(s),{label:"-- GPT --",value:"_gpt_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(o),{label:"-- Gemini --",value:"_gemini_header",isAccessible:!1,creditMultiplier:1,isHeader:!0},...a(r)],u=l.filter(p=>!p.isHeader),d=p=>{if(p.value.startsWith("_"))return;if(!l.find(h=>h.value===p.value)?.isAccessible){t(p.value);return}let g=Y.find(h=>h.name===p.value);g&&e(g)};return fe.createElement(Qn,{borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:1,flexDirection:"column",backgroundColor:"#1a1a1a"},fe.createElement(Ge,{bold:!0,color:"whiteBright"},"Select Model"),fe.createElement(Qn,null,fe.createElement(Ge,{color:"#6B7280"},"Tier: ",ce.getDisplayName(c)," - "),fe.createElement(Ge,{color:"#5AD8A6"},"[0.5x]"),fe.createElement(Ge,{color:"#6B7280"}," "),fe.createElement(Ge,{color:"#9CA3AF"},"[1x]"),fe.createElement(Ge,{color:"#6B7280"}," "),fe.createElement(Ge,{color:"#FBBF24"},"[2x]"),fe.createElement(Ge,{color:"#6B7280"}," credits")),fe.createElement(Qn,{marginTop:1},fe.createElement(Kn,{items:u.map(p=>({label:p.label,value:p.value})),onSelect:d,isFocused:!0,highlightColor:"#D97706"})),fe.createElement(Qn,{marginTop:1},fe.createElement(Ge,{color:"#6B7280"},"Esc to cancel")))}import Pt from"react";import{Box as ss,Text as oi}from"@jrichman/ink";var si=[{command:"/model",description:"change AI model",value:"model"},{command:"/new",description:"start new conversation",value:"new"},{command:"/clear",description:"clear conversation",value:"clear"},{command:"/stop",description:"stop current generation",value:"stop"},{command:"/vision",description:"toggle vision mode",value:"vision"},{command:"/img",description:"paste image from clipboard",value:"img"},{command:"/signout",description:"sign out and exit",value:"signout"},{command:"/help",description:"show help",value:"help"},{command:"/exit",description:"exit the app",value:"exit"}];function ol({item:c,isSelected:e,highlightColor:t}){let[n,s]=c.label.split(" ");return Pt.createElement(ss,{width:50,backgroundColor:e?t:void 0},Pt.createElement(ss,{width:14},Pt.createElement(oi,{color:e?"#1a1a1a":"whiteBright",bold:!0},n)),Pt.createElement(oi,{color:e?"#1a1a1a":"#6B7280"},s))}function ri({filterText:c,onSelect:e}){let n=(c?si.filter(o=>o.value.toLowerCase().includes(c)):si).map(o=>({label:`${o.command} ${o.description}`,value:o.value})),s=o=>{o.value&&e(o.value)};return Pt.createElement(ss,{flexDirection:"column",paddingX:1,paddingY:1,width:"100%",borderStyle:"single",borderColor:"#3F3F46",backgroundColor:"#18181B"},Pt.createElement(Kn,{items:n.length>0?n:[{label:"No matching commands",value:""}],onSelect:s,itemComponent:ol,isFocused:!0,highlightColor:"#D97706"}))}import te from"react";import{Box as Ze,Text as et}from"@jrichman/ink";function ii({regularQueuedMessages:c,crossDeviceTasks:e}){return te.createElement(te.Fragment,null,c.length>0&&te.createElement(Ze,{flexDirection:"column",paddingX:2,marginBottom:1},c.map((t,n)=>te.createElement(Ze,{key:t.id,borderStyle:"round",borderColor:"#3F3F46",paddingX:2,paddingY:0,marginBottom:1},te.createElement(Ze,null,te.createElement(et,{color:"whiteBright",bold:!0},n+1),te.createElement(et,{color:"#6B7280"}," • "),te.createElement(et,{color:"#9CA3AF"},t.content.length>60?t.content.substring(0,60)+"...":t.content)))),te.createElement(Ze,null,te.createElement(et,{color:"#9CA3AF"},c.length," message",c.length>1?"s":""," queued"))),e.length>0&&te.createElement(Ze,{flexDirection:"column",paddingX:2,marginBottom:1},e.map((t,n)=>te.createElement(Ze,{key:`cross-${t.id}`,borderStyle:"round",borderColor:"#0E7490",paddingX:2,paddingY:0,marginBottom:1},te.createElement(Ze,null,te.createElement(et,{color:"#22D3EE",bold:!0},"[M] ",n+1),te.createElement(et,{color:"#6B7280"}," - "),te.createElement(et,{color:"#9CA3AF"},t.content.length>60?t.content.substring(0,60)+"...":t.content)))),te.createElement(Ze,null,te.createElement(et,{color:"#22D3EE"},e.length," cross-device task",e.length>1?"s":""," waiting"))))}import $ from"react";import{Box as Te,Text as Q}from"@jrichman/ink";import ai from"path";var ae={Foreground:"#E5E7EB",Background:"#111827",AccentBlue:"#60A5FA",AccentPurple:"#A78BFA",AccentCyan:"#22D3EE",AccentGreen:"#34D399",AccentYellow:"#FBBF24",AccentRed:"#F87171",Gray:"#9CA3AF",DarkGray:"#6B7280",LightGray:"#D1D5DB",Comment:"#6B7280"},sl={text:{primary:ae.Foreground,secondary:ae.Gray,accent:ae.AccentPurple,link:ae.AccentBlue,response:ae.Foreground},background:{primary:ae.Background,secondary:"#1F2937"},border:{default:ae.DarkGray,focused:ae.AccentBlue},ui:{comment:ae.Comment,symbol:ae.Gray,muted:ae.DarkGray},status:{success:ae.AccentGreen,warning:ae.AccentYellow,error:ae.AccentRed,info:ae.AccentCyan}},rs={name:"Default Dark",type:"dark",colors:ae,semantic:sl};var At=rs;var I={get text(){return At.semantic.text},get background(){return At.semantic.background},get border(){return At.semantic.border},get ui(){return At.semantic.ui},get status(){return At.semantic.status},get colors(){return At.colors}};function ci({input:c,isLoading:e,pastedTexts:t,cursorPosition:n,suggestion:s}){let o=c.length>0||t.length>0,r=" Type your message or @path/to/file",a=s&&s.toLowerCase().startsWith(c.toLowerCase())&&c.length>0?s.slice(c.length):null;return $.createElement(Te,{borderStyle:"round",borderColor:o?I.border.focused:I.border.default,paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},t.length>0&&$.createElement(Te,{flexDirection:"column",marginBottom:0},t.map((l,u)=>{if(l.type==="clipboard_image"){let m=l.fileSize?` ${Ye(l.fileSize)}`:"",g=!!l.error;return $.createElement(Te,{key:`pasted-${l.id}`,flexDirection:"column"},$.createElement(Te,null,$.createElement(Q,{color:g?I.status.error:I.status.info}," ","[CLIPBOARD] "),$.createElement(Q,{color:g?I.status.error:I.text.secondary},"Image"),m&&$.createElement(Q,{color:I.ui.muted},m)),g&&$.createElement(Te,{marginLeft:4},$.createElement(Q,{color:I.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="image_path"&&l.filePath){let m=Qo(ai.basename(l.filePath)),g=l.fileSize?` ${Ye(l.fileSize)}`:"",h=!!l.error;return $.createElement(Te,{key:`pasted-${l.id}`,flexDirection:"column"},$.createElement(Te,null,$.createElement(Q,{color:h?I.status.error:I.status.info}," ","[IMG] "),$.createElement(Q,{color:h?I.status.error:I.text.secondary},m),g&&$.createElement(Q,{color:I.ui.muted},g)),h&&$.createElement(Te,{marginLeft:4},$.createElement(Q,{color:I.status.error,dimColor:!0},"[!] ",l.error)))}if(l.type==="file_path"&&l.filePath){let m=Qo(ai.basename(l.filePath)),g=l.fileSize?` ${Ye(l.fileSize)}`:"",h=!!l.error;return $.createElement(Te,{key:`pasted-${l.id}`,flexDirection:"column"},$.createElement(Te,null,$.createElement(Q,{color:h?I.status.error:I.status.info}," ","[FILE] "),$.createElement(Q,{color:h?I.status.error:I.text.secondary},m),g&&$.createElement(Q,{color:I.ui.muted},g)),h&&$.createElement(Te,{marginLeft:4},$.createElement(Q,{color:I.status.error,dimColor:!0},"[!] ",l.error)))}let d=l.lineCount-1,p=d>0?`+${d} lines`:"1 line";return $.createElement(Te,{key:`pasted-${l.id}`},$.createElement(Q,{color:I.ui.muted}," ","[TEXT] "),$.createElement(Q,{color:I.text.secondary},"Pasted text #",u+1),$.createElement(Q,{color:I.ui.muted}," (",p,")"))})),$.createElement(Te,null,$.createElement(Q,{color:I.text.accent},"> "),c.length===0&&!e?s?$.createElement(Q,null,$.createElement(Q,{inverse:!0}," "),$.createElement(Q,{color:I.ui.muted},s),$.createElement(Q,{color:I.ui.muted,dimColor:!0}," (Tab to accept)")):$.createElement(Q,{color:I.ui.muted},r):$.createElement(Q,null,$.createElement(Q,{color:I.text.primary},c.slice(0,n)),!e&&$.createElement(Q,{inverse:!0}," "),$.createElement(Q,{color:I.text.primary},c.slice(n)),a&&$.createElement(Q,{color:I.ui.muted},a))))}import J from"react";import{Box as ve,Text as Oe}from"@jrichman/ink";import Dt from"react";import{Box as Jn,Text as li}from"@jrichman/ink";function ui({suggestions:c,onSelect:e}){return c.length===0?null:Dt.createElement(Jn,{flexDirection:"column",marginTop:1,width:"100%"},c.map((t,n)=>Dt.createElement(Jn,{key:`sug-block-${n}`,flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},t.options.map((s,o)=>Dt.createElement(Jn,{key:`sug-opt-${n}-${o}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},Dt.createElement(li,{color:"#22D3EE"},s))))),e&&Dt.createElement(Jn,{marginTop:0,width:"100%"},Dt.createElement(li,{color:"#6B7280"},"Type a suggestion to use it")))}import dt from"react";import{Box as Yn,Text as is}from"@jrichman/ink";function di({workingFiles:c}){return c.length===0?null:dt.createElement(Yn,{flexDirection:"column",marginTop:1,width:"100%"},dt.createElement(Yn,{marginBottom:0,width:"100%"},dt.createElement(is,{color:"#9CA3AF",bold:!0},"Working Files"),dt.createElement(is,{color:"#6B7280"}," (",c.length,")")),dt.createElement(Yn,{flexDirection:"row",flexWrap:"wrap",gap:1,width:"100%"},c.map(e=>dt.createElement(Yn,{key:`wf-${e.path}`,borderStyle:"round",borderColor:"#3F3F46",paddingX:1,paddingY:0},dt.createElement(is,{color:"white"},e.name)))))}var as={user:"> ",assistant:"✦ ",system:"ℹ "},rl=150;function pi({message:c,onSuggestionClick:e,maxLines:t=rl}){let{role:n,content:s}=c,o=(r,a)=>r.length<=a?{lines:r,truncated:!1}:{lines:r.slice(0,a),truncated:!0};if(n==="system"){let r=s.split(`
625
+ `),{lines:a,truncated:l}=o(r,t);return J.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},J.createElement(ve,{flexDirection:"row"},J.createElement(ve,{width:2,flexShrink:0},J.createElement(Oe,{color:I.status.info},as.system)),J.createElement(ve,{flexDirection:"column",flexGrow:1},a.map((u,d)=>J.createElement(Oe,{key:`sys-line-${d}`,color:I.text.secondary},u)),l&&J.createElement(Oe,{color:I.ui.muted,dimColor:!0},"... (",r.length-t," more lines)"))))}if(n==="user"){let r=s.split(`
626
+ `),{lines:a,truncated:l}=o(r,t);return J.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},J.createElement(ve,{flexDirection:"row"},J.createElement(ve,{width:2,flexShrink:0},J.createElement(Oe,{color:I.text.accent},as.user)),J.createElement(ve,{flexDirection:"column",flexGrow:1},a.map((u,d)=>J.createElement(Oe,{key:`user-line-${d}`,color:I.text.secondary},u)),l&&J.createElement(Oe,{color:I.ui.muted,dimColor:!0},"... (",r.length-t," more lines)"))))}if(n==="assistant"){let{suggestions:r,cleanedContent:a}=nn(s),{workingFiles:l,cleanedContent:u}=bs(a),p=ys(u).split(`
627
+ `),{lines:m,truncated:g}=o(p,t);return J.createElement(ve,{marginY:1,flexDirection:"column",width:"100%"},J.createElement(ve,{flexDirection:"row"},J.createElement(ve,{width:2,flexShrink:0},J.createElement(Oe,{color:I.text.accent},as.assistant)),J.createElement(ve,{flexDirection:"column",flexGrow:1},m.map((h,y)=>h.trim()===""?J.createElement(Oe,{key:`asst-line-${y}`}," "):J.createElement(Oe,{key:`asst-line-${y}`,color:I.text.primary},Ts(h))),g&&J.createElement(Oe,{color:I.ui.muted,dimColor:!0},"... (",p.length-t," more lines)"))),l.length>0&&J.createElement(ve,{paddingLeft:2},J.createElement(di,{workingFiles:l})),r.length>0&&J.createElement(ve,{paddingLeft:2},J.createElement(ui,{suggestions:r,onSelect:e})))}return null}import Yt,{useState as il,useEffect as al}from"react";import{Box as cl,Text as cs}from"@jrichman/ink";import ll from"ink-spinner";function ul(c){if(c<60)return`${c}s`;let e=Math.floor(c/60),t=c%60;return`${e}m ${t}s`}function mi({isLoading:c,phrase:e="Processing",startTime:t}){let[n,s]=il(0);return al(()=>{if(!c){s(0);return}let o=t||Date.now(),r=setInterval(()=>{let a=Date.now(),l=Math.floor((a-o)/1e3);s(l)},1e3);return()=>clearInterval(r)},[c,t]),c?Yt.createElement(cl,{flexDirection:"row",alignItems:"center",paddingX:2,marginBottom:1},Yt.createElement(cs,{color:I.text.accent},Yt.createElement(ll,{type:"dots"})),Yt.createElement(cs,{color:I.text.primary}," ",e,"... "),Yt.createElement(cs,{color:I.text.secondary},"(esc to cancel",n>0?`, ${ul(n)}`:"",")")):null}import tt from"react";import{Box as Zn,Text as eo,useStdout as dl}from"@jrichman/ink";function pl(c){let e=process.env.HOME||process.env.USERPROFILE||"";return e&&c.startsWith(e)?"~"+c.slice(e.length):c}function ml(c,e){if(c.length<=e)return c;let t=c.split("/");if(t.length<=2)return c.slice(0,e-3)+"...";let n=t[0]+"/.../"+t[t.length-1];return n.length>e&&(n=".../"+t[t.length-1]),n.length>e&&(n=n.slice(0,e-3)+"..."),n}function gi({cwd:c,selectedModel:e,showScrollHint:t=!1}){let{stdout:n}=dl(),s=n?.columns||80,o=`${e.displayName} /model`,r=t?"? help · Shift+↑↓ scroll":"? help",l=o.length+r.length+" ".length*2+4,u=Math.max(15,Math.floor((s-l)*.4)),d=ml(pl(c),u);return tt.createElement(Zn,{paddingX:2,paddingY:0,width:"100%",justifyContent:"space-between",flexDirection:"row"},tt.createElement(Zn,null,tt.createElement(eo,{color:I.text.link},d)),tt.createElement(Zn,null,tt.createElement(eo,{color:I.text.accent},e.displayName),tt.createElement(eo,{color:I.text.secondary}," /model")),tt.createElement(Zn,null,tt.createElement(eo,{color:I.text.secondary},r)))}import nt,{useState as ls,useEffect as gl,useRef as us,useCallback as hl,useLayoutEffect as fl}from"react";import{Box as Zt,Text as hi,useStdout as vl,getScrollHeight as bl,getInnerHeight as Tl,useInput as yl}from"@jrichman/ink";var fi=3;function vi({children:c,reservedLines:e=8,autoScrollToBottom:t=!0,hasFocus:n=!0}){let{stdout:s}=vl(),o=s?.rows||24,r=Math.max(5,o-e),[a,l]=ls(0),[u,d]=ls({innerHeight:0,scrollHeight:0}),[p,m]=ls(!1),g=us(null),h=us(u),y=us(0);gl(()=>{h.current=u},[u]),fl(()=>{if(!g.current)return;let b=Math.round(Tl(g.current)),C=Math.round(bl(g.current)),P=a>=u.scrollHeight-u.innerHeight-1;(u.innerHeight!==b||u.scrollHeight!==C)&&(d({innerHeight:b,scrollHeight:C}),P&&t&&l(Math.max(0,C-b)));let R=C>r;R!==p&&m(R);let O=nt.Children.count(c);t&&y.current!==O&&l(Math.max(0,C-b)),y.current=O});let T=hl(b=>{let{scrollHeight:C,innerHeight:P}=h.current;l(R=>{let O=Math.max(0,C-P);return Math.min(Math.max(0,R+b),O)})},[]);yl((b,C)=>{if(n){if(C.pageUp){T(-r+2);return}if(C.pageDown){T(r-2);return}if(C.shift&&C.upArrow){T(-fi);return}if(C.shift&&C.downArrow){T(fi);return}}},{isActive:n});let S=Math.max(0,u.scrollHeight-u.innerHeight),w=a>0,E=a<S;return nt.createElement(Zt,{flexDirection:"column",flexGrow:1},w&&nt.createElement(Zt,{paddingX:2},nt.createElement(hi,{color:I.text.secondary},"↑ Page Up / Shift+↑ to scroll up")),nt.createElement(Zt,{ref:g,height:p?r:void 0,flexDirection:"column",overflowY:p?"scroll":"hidden",overflowX:"hidden",scrollTop:a,flexGrow:1},nt.createElement(Zt,{flexDirection:"column",flexShrink:0,paddingRight:1},c)),E&&nt.createElement(Zt,{paddingX:2},nt.createElement(hi,{color:I.text.secondary},"↓ Page Down / Shift+↓ to scroll down")))}Mt();function kl(){let c=jt(),e=Le(),{regularQueuedMessages:t,crossDeviceTasks:n}=qo(),s=Xt(),o=at(),{userTier:r}=Vo(),a=Vt(),l=lt(),{handleCommand:u}=jn(),d=zo(),[p,m]=wl();bi(()=>{c.isLoading&&!p?m(Date.now()):c.isLoading||m(void 0)},[c.isLoading,p]);let g=Cl(()=>{let T=[...c.messages].reverse().find(w=>w.role==="assistant"&&w.content);if(!T)return null;let{suggestions:S}=nn(T.content);return S.length>0&&S[0].options.length>0?S[0].options[0]:null},[c.messages]),h=xl(null);bi(()=>{let T=null;c.isLoading?T=null:a.input===""||g&&g.toLowerCase().startsWith(a.input.toLowerCase())?T=g:T=null,h.current!==T&&(h.current=T,l.setSuggestion(T))},[g,c.isLoading,a.input]);let y=Sl(async()=>{let T=a.pastedTexts.filter(S=>!S.error||S.type==="text");if(a.input.startsWith("/")){await u(a.input);return}if(l.clearPastedTexts(),T.length>0){let{fullInput:S,imageUrls:w,errors:E}=await l.processFilesForSubmit();if(E.length>0&&!S.trim()&&w.length===0){e.addSystemMessage(`Failed to read files:
628
+ ${E.map(b=>` - ${b}`).join(`
629
+ `)}`);return}e.handleSubmit(S.trim()||"Please analyze this image.",w)}else e.handleSubmit(a.input.trim());l.clearInput()},[a.input,a.pastedTexts,l,e,u]);return jr({onSubmit:y}),V.createElement(Ee,{flexDirection:"column",width:"100%",height:"100%"},V.createElement(vi,{reservedLines:12,autoScrollToBottom:!0,hasFocus:!s.showHelp&&!s.showModelMenu&&!s.showCommandMenu},V.createElement(Ee,{flexDirection:"column",paddingX:2,paddingY:1},c.messages.map(T=>V.createElement(pi,{key:T.id,message:T,onSuggestionClick:S=>l.setInput(S)})))),c.todoList&&c.todoList.todos.length>0&&V.createElement(Ee,{flexShrink:0},V.createElement(Zr,{todoList:c.todoList})),c.activeTools.size>0&&V.createElement(Ee,{paddingX:2,marginBottom:1,flexShrink:0},V.createElement(Vr,{activeTools:c.activeTools})),c.subAgentOperations.size>0&&V.createElement(Ee,{paddingX:2,marginBottom:1,flexShrink:0},V.createElement(Qr,{operations:c.subAgentOperations})),c.pendingConfirmation&&V.createElement(Ee,{paddingX:2,marginBottom:1,flexShrink:0},V.createElement(Yr,{request:c.pendingConfirmation,onConfirm:e.handleConfirmationConfirm,onDecline:e.handleConfirmationDecline,onTimeout:e.handleConfirmationTimeout})),a.isProcessingFiles&&V.createElement(Ee,{paddingX:2,marginBottom:1,flexShrink:0},V.createElement(Ti,{color:I.text.accent},V.createElement(El,{type:"dots"})),V.createElement(Ti,{color:I.text.primary}," Reading files...")),!a.isProcessingFiles&&V.createElement(mi,{isLoading:c.isLoading,phrase:c.loadingMessage||"Processing",startTime:p}),(t.length>0||n.length>0)&&V.createElement(Ee,{flexShrink:0},V.createElement(ii,{regularQueuedMessages:t,crossDeviceTasks:n})),s.showCommandMenu&&V.createElement(Ee,{flexShrink:0,paddingX:2,marginBottom:0},V.createElement(ri,{filterText:a.input.startsWith("/")?a.input.substring(1).toLowerCase():"",onSelect:T=>{o.hideCommandMenu(),u(`/${T}`)}})),s.showModelMenu&&V.createElement(Ee,{flexShrink:0,paddingX:2,marginBottom:1},V.createElement(ni,{userTier:r,onSelect:T=>{o.setModel(T),o.hideModelMenu()},onAccessDenied:T=>{e.addSystemMessage(ce.getAccessDeniedMessage(T)),o.hideModelMenu()}})),s.showHelp&&V.createElement(Ee,{flexShrink:0,paddingX:2,marginBottom:1},V.createElement(ei,null)),V.createElement(Ee,{flexShrink:0,paddingX:2},V.createElement(ci,{input:a.input,isLoading:c.isLoading,pastedTexts:a.pastedTexts,cursorPosition:a.cursorPosition,suggestion:a.suggestion})),V.createElement(gi,{cwd:d,selectedModel:s.selectedModel,showScrollHint:!1}))}function yi({initialProjectPath:c}={}){return V.createElement(Hr,{initialProjectPath:c},V.createElement(kl,null))}ps();le();le();import H from"chalk";import $l from"inquirer";import{exec as Ul}from"child_process";var ot=class{authService;constructor(){this.authService=z.getInstance()}openBrowser(e){return new Promise(t=>{let n=process.platform,s;n==="darwin"?s=`open "${e}"`:n==="win32"?s=`start "" "${e}"`:s=`xdg-open "${e}"`,Ul(s,o=>{o&&console.log(H.yellow("⚠️ Could not auto-open browser. Please open the URL manually.")),t()})})}async login(){console.log(H.blue(`
630
+ 🔐 Orion Authentication`)),console.log(H.gray("─".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(H.yellow(`
631
+ 📋 Opening browser for authentication...`)),console.log(H.cyan.underline(` ${e}`)),await this.openBrowser(e),console.log(H.white(`
632
+ 1. Log in with your Orion account in the browser`)),console.log(H.white("2. Copy the access token shown after login")),console.log(H.white("3. Paste the token below")),console.log(H.yellow(`
633
+ Paste your access token here:`));let{accessToken:t}=await $l.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:n=>!n||n.trim().length===0?"Access token is required":!0}]);console.log(H.gray(`
634
+ Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let s=await this.authService.getUserInfo();console.log(H.green(`
635
+ ✅ Authentication successful!`)),s&&(console.log(H.gray(`Logged in as: ${s.email||s.username||"User"}`)),console.log(H.gray(`Subscription: ${this.getSubscriptionDisplay(s.subscription?.tier)}`)))}else console.log(H.red(`
636
+ ❌ Authentication failed. Please try again.`))}catch(n){console.log(H.red(`
637
+ ❌ Authentication error: ${n.message}`))}}async logout(){console.log(H.yellow(`
638
+ 🔄 Signing out...`)),console.log(H.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(H.green(`
639
+ ✅ Successfully signed out`)),console.log(H.gray("All authentication data and settings have been cleared.")),console.log(H.gray('Run "orion auth login" to sign in again.'))):(console.log(H.red(`
640
+ ❌ Logout failed`)),console.log(H.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(H.green(`
641
+ ✅ Authenticated`)),t){console.log(H.gray("─".repeat(50))),console.log(H.white("User:",t.name||t.username||"N/A")),console.log(H.white("Email:",t.email||"N/A"));let n=this.getSubscriptionDisplay(t.subscription?.tier);console.log(H.white("Subscription:",n)),t.usage&&(console.log(H.gray(`
642
+ Usage:`)),console.log(H.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(H.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(H.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(H.yellow(`
643
+ ⚠️ Not authenticated`)),console.log(H.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"}}};Pe();Ro();var Ai=!1;async function ms(){let c=process.cwd();if(Ai){console.log("Already running...");return}Ai=!0,F.enableCustomUI();let e=en.getInstance(),t=z.getInstance();if(!e.isInitialized()){console.log("🔧 Initializing Orion services...");try{await e.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(r){console.error(`
636
644
  ❌ Failed to initialize services:`,r.message),console.error(`
637
645
  💡 Tip: Check your internet connection and Firebase configuration.
638
646
  `),process.exit(1)}}(!await t.autoAuthenticate()||!t.isAuthenticated())&&(console.log(`🔐 Authentication required to use Orion CLI
639
- `),await new et().login(),t.isAuthenticated()||(console.error(`
647
+ `),await new ot().login(),t.isAuthenticated()||(console.error(`
640
648
  ❌ Authentication failed. Please try again.`),process.exit(1)),console.log(`
641
649
  ✨ Starting Orion CLI...
642
650
  `)),t.isFirebaseAuthenticated()||(console.error(`
643
651
  ❌ 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(`
644
652
  Please check your connection and try again.
645
- `),process.exit(1)),console.log("✅ Authentication verified"),Nn.getInstance().setWorkingDirectory(c),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:s}=Dl(Al.createElement(ui,{initialProjectPath:c}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await s(),Ar()}He();$();import{EventEmitter as Nl}from"events";import Rl from"axios";import{spawn as Ml}from"child_process";import Jn from"chalk";import lt from"fs";import Yn from"path";import as from"os";var Ol={enabled:!0,checkIntervalMs:1440*60*1e3},yi=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,Zn=class c extends Nl{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...Ol,...t},this.cacheFilePath=Yn.join(as.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){i.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){i.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){i.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):i.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){i.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(lt.existsSync(this.cacheFilePath)){let e=lt.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){i.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=Yn.dirname(this.cacheFilePath);lt.existsSync(t)||lt.mkdirSync(t,{recursive:!0}),lt.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){i.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:yi.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await Rl.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!n)throw new Error("No latest version found in registry response");return n}isNewerVersion(e,t){let n=this.parseVersion(e),o=this.parseVersion(t);if(!n||!o)return i.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let s=0;s<3;s++){if(n.numbers[s]>o.numbers[s])return!0;if(n.numbers[s]<o.numbers[s])return!1}return!n.prerelease&&o.prerelease?!0:n.prerelease&&!o.prerelease?!1:n.prerelease&&o.prerelease?this.comparePrerelease(n.prerelease,o.prerelease)>0:!1}parseVersion(e){let t=e.match(yi);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let n=e.split("."),o=t.split(".");for(let s=0;s<Math.max(n.length,o.length);s++){let r=n[s],a=o[s];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||Yn.join(as.homedir(),".local","share","pnpm");if(process.argv[1]?.includes("pnpm")||process.argv[1]?.includes(e))return"pnpm";let t=Yn.join(as.homedir(),".yarn");if(process.argv[1]?.includes("yarn")||process.argv[1]?.includes(t))return"yarn";let n=process.env.npm_config_user_agent||"";if(n.includes("pnpm"))return"pnpm";if(n.includes("yarn"))return"yarn"}catch(e){i.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:n,args:o}=this.getInstallCommand();i.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${n}`);let s=Ml(n,o,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),r="";s.stderr?.on("data",a=>{r+=a.toString()}),s.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(Jn.green(`
646
- ✓ Updated to v${e}`)+Jn.gray(` - restart CLI to use new version
647
- `))}),i.debug(`Successfully updated to ${e}`)):i.debug(`Update failed with code ${a}: ${r}`),t()}),s.on("error",a=>{i.debug("Auto-update spawn error:",a),t()}),setTimeout(()=>{this.updateCompleted||(s.kill(),i.debug("Update timed out"),t())},6e4)}catch(n){i.debug("Auto-update failed:",n),t()}})}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(Jn.green(`
648
- ✓ Updated to v${e.latestVersion}`)+Jn.gray(` - restart CLI to use new version
649
- `))}}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 i.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{lt.existsSync(this.cacheFilePath)&&lt.unlinkSync(this.cacheFilePath)}catch(e){i.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function Si(){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 n of e)if(c.includes(n)&&!c.includes("node_modules"))return!0;return!1}import _l from"dotenv";import{fileURLToPath as $l}from"url";import{dirname as Ul,join as Ll}from"path";import{readFileSync as Wl}from"fs";_l.config();var Bl=$l(import.meta.url),Hl=Ul(Bl),wi=JSON.parse(Wl(Ll(Hl,"..","package.json"),"utf8")),Gl=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!Si()&&!Gl&&Zn.getInstance(wi.version).checkAndUpdate().catch(()=>{});var At=new Fl;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 is()}catch(c){console.error(de.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(()=>(rs(),bi)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let o=Q.find(r=>r.name===e.model)||Q[0];console.log("💭 Sending message...");let s=await n.sendMessage(c,o,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(qn(s))}catch(t){de.stopSpinner(!1),console.error(de.formatError(t.message)),process.exit(1)}});var cs=At.command("auth").description("Authentication commands");cs.command("login").description("Login to Orion").action(async()=>{try{await new et().login()}catch(c){console.error(de.formatError(c.message)),process.exit(1)}});cs.command("logout").description("Logout from Orion").action(async()=>{try{await new et().logout()}catch(c){console.error(de.formatError(c.message)),process.exit(1)}});cs.command("status").description("Check authentication status").action(async()=>{try{await new et().status()}catch(c){console.error(de.formatError(c.message)),process.exit(1)}});At.command("models").description("List available AI models").action(()=>{de.printHeader("Available Models");for(let c of Q)console.log(`${de.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?is().catch(c=>{console.error(de.formatError(c.message)),process.exit(1)}):At.parse(process.argv);
653
+ `),process.exit(1)),console.log("✅ Authentication verified"),On.getInstance().setWorkingDirectory(c),process.stdout.write("\x1B[2J\x1B[H");let{waitUntilExit:o}=Wl(Ll.createElement(yi,{initialProjectPath:c}),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:!1});await o(),Wr()}qe();L();import{EventEmitter as Bl}from"events";import Hl from"axios";import{spawn as Gl}from"child_process";import oo from"chalk";import pt from"fs";import so from"path";import gs from"os";var ql={enabled:!0,checkIntervalMs:1440*60*1e3},Di=/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9.-]+))?(?:\+([a-zA-Z0-9.-]+))?$/,ro=class c extends Bl{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;config;cacheFilePath;updateCompleted=!1;constructor(e,t){super(),this.currentVersion=e,this.config={...ql,...t},this.cacheFilePath=so.join(gs.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){i.debug("Auto-update is disabled");return}if(!this.isChecking){if(!this.shouldCheckForUpdates()){i.debug("Skipping update check - within cooldown period");return}this.isChecking=!0;try{let e=await this.fetchLatestVersion();if(!this.isValidVersion(e)){i.debug(`Invalid version format from registry: ${e}`);return}this.saveCache({lastCheck:Date.now(),latestVersion:e}),this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):i.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){i.debug("Update check failed:",e)}finally{this.isChecking=!1}}}shouldCheckForUpdates(){let e=this.loadCache();return e?Date.now()-e.lastCheck>=this.config.checkIntervalMs:!0}loadCache(){try{if(pt.existsSync(this.cacheFilePath)){let e=pt.readFileSync(this.cacheFilePath,"utf8");return JSON.parse(e)}}catch(e){i.debug("Failed to load update cache:",e)}return null}saveCache(e){try{let t=so.dirname(this.cacheFilePath);pt.existsSync(t)||pt.mkdirSync(t,{recursive:!0}),pt.writeFileSync(this.cacheFilePath,JSON.stringify(e,null,2))}catch(t){i.debug("Failed to save update cache:",t)}}isValidVersion(e){return!e||typeof e!="string"?!1:Di.test(e)}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`,n=(await Hl.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"]?.latest;if(!n)throw new Error("No latest version found in registry response");return n}isNewerVersion(e,t){let n=this.parseVersion(e),s=this.parseVersion(t);if(!n||!s)return i.debug("Failed to parse versions for comparison",{latest:e,current:t}),!1;for(let o=0;o<3;o++){if(n.numbers[o]>s.numbers[o])return!0;if(n.numbers[o]<s.numbers[o])return!1}return!n.prerelease&&s.prerelease?!0:n.prerelease&&!s.prerelease?!1:n.prerelease&&s.prerelease?this.comparePrerelease(n.prerelease,s.prerelease)>0:!1}parseVersion(e){let t=e.match(Di);return t?{numbers:[parseInt(t[1],10),parseInt(t[2],10),parseInt(t[3],10)],prerelease:t[4]||null}:null}comparePrerelease(e,t){let n=e.split("."),s=t.split(".");for(let o=0;o<Math.max(n.length,s.length);o++){let r=n[o],a=s[o];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||so.join(gs.homedir(),".local","share","pnpm");if(process.argv[1]?.includes("pnpm")||process.argv[1]?.includes(e))return"pnpm";let t=so.join(gs.homedir(),".yarn");if(process.argv[1]?.includes("yarn")||process.argv[1]?.includes(t))return"yarn";let n=process.env.npm_config_user_agent||"";if(n.includes("pnpm"))return"pnpm";if(n.includes("yarn"))return"yarn"}catch(e){i.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:n,args:s}=this.getInstallCommand();i.debug(`Auto-updating from ${this.currentVersion} to ${e} using ${n}`);let o=Gl(n,s,{stdio:"pipe",shell:process.platform==="win32",detached:!1}),r="";o.stderr?.on("data",a=>{r+=a.toString()}),o.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(oo.green(`
654
+ ✓ Updated to v${e}`)+oo.gray(` - restart CLI to use new version
655
+ `))}),i.debug(`Successfully updated to ${e}`)):i.debug(`Update failed with code ${a}: ${r}`),t()}),o.on("error",a=>{i.debug("Auto-update spawn error:",a),t()}),setTimeout(()=>{this.updateCompleted||(o.kill(),i.debug("Update timed out"),t())},6e4)}catch(n){i.debug("Auto-update failed:",n),t()}})}isUserInteracting(){return process.stdin.isRaw?!0:process.stdin.listenerCount("keypress")>0}showPendingNotification(){if(this.updateCompleted){let e=this.loadCache();e?.latestVersion&&console.log(oo.green(`
656
+ ✓ Updated to v${e.latestVersion}`)+oo.gray(` - restart CLI to use new version
657
+ `))}}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 i.debug("Update check failed:",e),{hasUpdate:!1}}}async forceCheckAndUpdate(){try{pt.existsSync(this.cacheFilePath)&&pt.unlinkSync(this.cacheFilePath)}catch(e){i.debug("Failed to clear update cache:",e)}return this.checkAndUpdate()}getConfig(){return{...this.config}}setConfig(e){this.config={...this.config,...e}}};function Ni(){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 n of e)if(c.includes(n)&&!c.includes("node_modules"))return!0;return!1}import jl from"dotenv";import{fileURLToPath as Xl}from"url";import{dirname as Vl,join as Kl}from"path";import{readFileSync as Ql}from"fs";jl.config();var Jl=Xl(import.meta.url),Yl=Vl(Jl),Ri=JSON.parse(Ql(Kl(Yl,"..","package.json"),"utf8")),Zl=process.argv.includes("--no-update")||process.env.ORION_NO_UPDATE==="true";!Ni()&&!Zl&&ro.getInstance(Ri.version).checkAndUpdate().catch(()=>{});var Nt=new zl;Nt.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Ri.version).option("--no-update","Disable automatic update check");Nt.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await ms()}catch(c){console.error(pe.formatError(c.message)),process.exit(1)}});Nt.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(()=>(ps(),Pi)),n=t.getInstance();console.log("🔧 Initializing Orion services..."),await n.initialize(),await n.waitForDeviceRegistration();let s=Y.find(r=>r.name===e.model)||Y[0];console.log("💭 Sending message...");let o=await n.sendMessage(c,s,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(tn(o))}catch(t){pe.stopSpinner(!1),console.error(pe.formatError(t.message)),process.exit(1)}});var hs=Nt.command("auth").description("Authentication commands");hs.command("login").description("Login to Orion").action(async()=>{try{await new ot().login()}catch(c){console.error(pe.formatError(c.message)),process.exit(1)}});hs.command("logout").description("Logout from Orion").action(async()=>{try{await new ot().logout()}catch(c){console.error(pe.formatError(c.message)),process.exit(1)}});hs.command("status").description("Check authentication status").action(async()=>{try{await new ot().status()}catch(c){console.error(pe.formatError(c.message)),process.exit(1)}});Nt.command("models").description("List available AI models").action(()=>{pe.printHeader("Available Models");for(let c of Y)console.log(`${pe.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?ms().catch(c=>{console.error(pe.formatError(c.message)),process.exit(1)}):Nt.parse(process.argv);