@zinley/orion 1.2.6 → 1.2.7

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 +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -236,7 +236,7 @@ ${t}
236
236
  `,this.currentOutput+=n+`
237
237
  `,o.debug(`[PERSONAL AGENT] Captured frontend tool result: ${e} - Success: ${s}`),o.debug(`[PERSONAL AGENT] Complete output length: ${this.completeOutputWithToolResults.length}`),this.emit("frontend_tool_result",{toolName:e,output:t,success:s,toolId:i,wrappedContent:n})}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||ve(),text:t.text,completed:t.completed||!1,priority:t.priority,status:t.status||(t.completed?"completed":"pending"),activeForm:t.activeForm||t.text})),timestamp:new Date(e.timestamp||Date.now())},this.emit("todo_update",this.currentTodoList)}handleWebViewUpdate(e){Array.isArray(e)?this.activeWebViewURLs=e:e.urls?this.activeWebViewURLs=e.urls:e.url&&(this.activeWebViewURLs=[e.url]),this.emit("webview_update",this.activeWebViewURLs)}handleOperatorProgress(e){this.operatorTaskState={id:e.id||ve(),taskId:e.taskId||e.id||ve(),sessionId:e.sessionId||ve(),status:e.status||"pending",task:e.task||e.description||"",llm:e.llm,currentStep:e.currentStep,totalSteps:e.totalSteps||0,steps:e.steps||[],result:e.result,error:e.error,startTime:e.startTime||new Date},this.emit("operator_progress",this.operatorTaskState)}handleStop(e){e.reason==="CONVERSATION_COMPLETE"&&this.handleConversationComplete(),this.emit("BotResponseStopped",{reason:e.reason||"user_manual_stop"}),this.emit("stop",e)}async handleConversationComplete(){if(o.debug("[PERSONAL AGENT] Disconnecting WebSocket after conversation completion..."),V.getInstance().handleConversationComplete(),o.debug("[PERSONAL AGENT] WebSocket disconnected after conversation completion"),this.currentOutput.trim().length>0){let t={conversationId:null,content:this.currentOutput,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};o.debug(`[PERSONAL AGENT] Emitting conversation_complete with content length: ${this.currentOutput.length}`),o.debug(`[PERSONAL AGENT] Content preview: "${this.currentOutput.substring(0,100)}..."`),this.emit("conversation_complete",t),o.debug("[PERSONAL AGENT] Conversation saving handled by AdvancedChatCommand (like SnowX OverlayManager)")}this.resetState()}calculateTokensUsed(e){return e.reduce((t,s)=>typeof s.content=="string"?t+Math.ceil(s.content.length/4):t,0)}stopCurrentOperation(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.emit("stopped"),this.resetState()}async submitPrompt(e,t){let s=t?.selectedPersonalModel||this.currentModel?.name||"snowx-h4",{SNOWX_MODELS:i}=await Promise.resolve().then(()=>(we(),qt)),n=i.find(a=>a.name===s)||{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},r=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,r,n,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){o.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),V.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
238
238
 
239
- [STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{o.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(i){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",i)}await this.completeConversation(s,"STOP"),o.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),o.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.session_id=this.currentSessionId,o.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):o.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let n=(await Promise.resolve().then(()=>(ue(),Ae))).DeviceRegistrationService.getInstance().getCurrentDeviceId();n?(s.device_id=n,o.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):o.debug("[PERSONAL AGENT] No device_id available for stop request"),o.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Tt.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(o.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&o.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&o.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){o.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){o.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),V.getInstance().handleConversationComplete();let i={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",i),this.resetState(),o.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear()}getCurrentTodoList(){return this.currentTodoList}getActiveWebViewURLs(){return this.activeWebViewURLs}getOperatorTaskState(){return this.operatorTaskState}getCompleteOutput(){return this.completeOutputWithToolResults||this.currentOutput}get isProcessing(){return this.currentAbortController!==null||this.currentPromptId!==null}}});var Ss={};te(Ss,{FirebaseNativeService:()=>Me,TaskMode:()=>kt,TaskStatus:()=>It});import{getDatabase as fn,ref as Et,onValue as vn,update as bn,set as Sn,serverTimestamp as wn}from"firebase/database";import{EventEmitter as yn}from"events";var kt,It,Me,xt=F(()=>{"use strict";U();Ue();kt=(t=>(t.NEW="new",t.EXISTING="existing",t))(kt||{}),It=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s))(It||{}),Me=class c extends yn{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),o.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=pe.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=fn(e),o.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(o.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(o.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){o.error("[Firebase Native] Firebase not initialized properly");return}o.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;o.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let i=Et(this.database,s),n=this.auth?.currentUser;o.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!n,uid:n?.uid||"none",email:n?.email||"none"}),this.listenerHandle=vn(i,r=>{o.debug("[Firebase Native] Data change event received",{exists:r.exists(),key:r.key,taskCount:r.val()?Object.keys(r.val()).length:0}),this.handleTasksSnapshot(r)},r=>{o.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),o.debug("[Firebase Native] Firebase listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}handleTasksSnapshot(e){let t=e.val();if(!t){o.debug("[Firebase Native] No tasks in snapshot");return}let s=Object.entries(t);o.debug("[Firebase Native] Processing tasks from snapshot",{taskCount:s.length});for(let[i,n]of s){let r=n;if(o.debug("[Firebase Native] Checking task",{taskId:i,status:r.status,mode:r.mode,fromDevice:r.fromDeviceId,toDevice:r.toDeviceId}),r.status==="pending"){if(this.currentTaskId===i){o.debug("[Firebase Native] Already processing task - skipping",{taskId:i});continue}o.debug("[Firebase Native] Found PENDING task - processing",{taskId:i}),this.handleIncomingTask(i,r)}else o.debug("[Firebase Native] Task not pending - skipping",{taskId:i,status:r.status})}}async handleIncomingTask(e,t){o.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,o.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),o.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),o.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){o.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){o.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),o.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),o.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(ae(),Ee))).PersonalAgentService.getInstance()){o.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}o.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?o.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):o.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),o.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),o.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(i){o.error("[FIREBASE-NATIVE] Task execution failed:",i.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ae(),Ee)),s=t.getInstance();this.completedObserver=i=>{this.currentTaskId===e&&(o.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.message||i||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${n}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.reason;o.debug(`[RESULT MONITOR] Task ${e} stopped: ${n}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),o.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(ae(),Ee)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),o.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){o.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let i=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,n={status:t,updatedAt:"firebase_timestamp"};s&&(n.result=s),o.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:i,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(i,n),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:i,error:r.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Et(this.database,i),l={status:t,updatedAt:wn()};s&&(l.result=s),await bn(a,l),o.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else o.error("[Firebase Native] Database not available for fallback")}catch(a){o.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,i){let n=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;o.debug("[Firebase Native] Sending task to device",{taskId:n,targetDeviceId:t,mode:i});try{let r=Et(this.database,`users/${e}/devices/${t}/tasks/${n}`),a={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:i,timestamp:Date.now(),status:"pending"};return await Sn(r,a),o.debug("[Firebase Native] Task sent successfully",{taskId:n,targetDeviceId:t}),n}catch(r){throw r}}stopListening(){if(o.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,o.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){o.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,o.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Tn}from"events";var Ie,Dt=F(()=>{"use strict";ue();se();Ue();xt();ae();U();Ie=class c extends Tn{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];overlayManager=null;constructor(){super(),this.deviceRegistrationService=ne.getInstance(),this.authService=q.getInstance(),this.firebaseAPI=pe.getInstance(),this.firebaseNative=Me.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=K.getInstance();e.on("BotResponseCompleted",()=>{this.processNextQueuedTask()}),e.on("BotResponseStopped",()=>{this.processNextQueuedTask()}),e.on("BotResponseError",()=>{this.processNextQueuedTask()})}processNextQueuedTask(){setTimeout(()=>{if(K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)||this.pendingTasksQueue.length===0)return;let s=this.pendingTasksQueue.shift();this.executeTaskImmediately(s.taskId,s.prompt,s.mode)},500)}async startListening(e,t){let s=t||this.deviceRegistrationService.getCurrentDeviceId();if(!s){o.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,o.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let i=this.authService.getFirebaseAuth();if(!i?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(i.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",i.currentUser.uid,"Requested:",e),o.error("Refusing to start listener for different user");return}o.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(i){throw o.error("Failed to start listener:",i.message),i}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),o.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){o.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){o.error("No stored user ID found - cannot authenticate Firebase for listeners");return}o.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let i=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",i.user.uid)}}catch(s){o.warn("Firebase authentication failed:",s.message),o.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){o.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e.taskId),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,o.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),o.debug("Cross-device task UI flow triggered successfully")}catch(t){o.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){o.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(s){o.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),o.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let i=s[1],n=s[2];return i.length!==13||!Number.isInteger(Number(i))||n.length!==9?!1:/^[a-z0-9]+$/.test(n)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,i=t.prompt,n=t.mode,r=t.status;if(!s||!i||!n||r!=="pending")return;if(!this.validateTaskId(s)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",s),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",s);let a=n==="new"?"new":"existing";this.currentTaskId=s,await this.updateTaskStatus(s,"processing"),await this.executeTask(s,i,a)}catch(t){o.error("Error handling incoming task:",t.message)}}async executeTask(e,t,s){if(o.debug(`Executing task: ${e} with mode: ${s}`),o.debug(`Prompt to execute: ${t}`),K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),o.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}o.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}switch(s){case"new":"clearChat"in this.overlayManager&&typeof this.overlayManager.clearChat=="function"?this.overlayManager.clearChat(!1):(this.overlayManager.messages=[],this.overlayManager.fullConversationHistory=[],this.overlayManager.conversationId=null),await new Promise(i=>setTimeout(i,500));break;case"existing":break}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{o.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(i){o.error("Task execution failed:",i.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,i={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,i)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING ====="),console.log("🔔 [CROSS-DEVICE] Setting up monitoring for task:",e);let t=()=>{console.log("✅ [CROSS-DEVICE] BotResponseCompleted event received"),console.log("✅ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("✅ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("✅ [CROSS-DEVICE] Task IDs match - processing completion"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring completion")},s=n=>{console.log("❌ [CROSS-DEVICE] BotResponseError event received:",n),console.log("❌ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("❌ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("❌ [CROSS-DEVICE] Task IDs match - processing error"),this.cleanupObservers()):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring error")},i=n=>{console.log("🛑 [CROSS-DEVICE] BotResponseStopped event received:",n),console.log("🛑 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("🛑 [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("🛑 [CROSS-DEVICE] Task IDs match - processing stop"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring stop")};console.log("👂 [CROSS-DEVICE] Setting up event listeners..."),this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",i),console.log("✅ [CROSS-DEVICE] Result monitoring setup complete for task:",e),console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING END =====")}cleanupObservers(){console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS ====="),console.log("🧹 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("👂 [CROSS-DEVICE] Removing event listeners..."),this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),console.log("✅ [CROSS-DEVICE] Event listeners removed"),console.log("🧹 [CROSS-DEVICE] Clearing current task ID"),this.currentTaskId=null,console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS END =====")}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,s="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let i=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={taskId:i,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:ge,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${i}`;try{await this.firebaseAPI.writeRealtimeData(r,n),o.debug("Task submitted to device:",e)}catch(a){throw o.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([s,i])=>({id:s,...i})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return o.error("Failed to get available devices:",e.message),[]}}enable(){o.debug("[CROSS DEVICE] Service enabled")}disable(){o.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){o.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Es={};te(Es,{SnowXStreamHandlerService:()=>Pt});import{EventEmitter as An}from"events";var Pt,ks=F(()=>{"use strict";Pt=class extends An{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,s,i,n){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let g=this.byteBuffer.toString("utf8");this.buffer+=g,this.rawDataReceived+=g,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,i,n)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,i,n),this.printFinalStatistics(),!this.fullResponse&&!n){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let i,n=this.buffer.indexOf(`\r
239
+ [STOPPED] - Task was stopped by user`:s="Task was stopped by user before any response was generated.",this.currentPromptId)try{o.debug("[PERSONAL AGENT] Would update Firebase with completion status for STOP")}catch(i){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",i)}await this.completeConversation(s,"STOP"),o.debug("[PERSONAL AGENT] Comprehensive stop operation completed")}stopLocalOperationsOnly(){this.currentAbortController&&(this.currentAbortController.abort(),this.currentAbortController=null),this.resetState(),o.debug("[PERSONAL AGENT] Local operations stopped")}async notifyBackendStop(){try{let e=process.env.SNOWX_USER_ID||"default_user",t="https://snowx.ai/api-beta/api/stop/all",s={user_id:e,reason:"user_requested_stop"};this.currentSessionId?(s.session_id=this.currentSessionId,o.debug(`[PERSONAL AGENT] Including session_id for specific session stop: ${this.currentSessionId}`)):o.debug("[PERSONAL AGENT] No session_id available - will stop all user sessions");let n=(await Promise.resolve().then(()=>(ue(),Ae))).DeviceRegistrationService.getInstance().getCurrentDeviceId();n?(s.device_id=n,o.debug(`[PERSONAL AGENT] Including device_id for device-specific stop: ${n}`)):o.debug("[PERSONAL AGENT] No device_id available for stop request"),o.debug("[PERSONAL AGENT] Sending backend stop request");let r=await this.getFirebaseIdToken();r||o.warn("[PERSONAL AGENT] ⚠️ No Firebase ID token available for stop request");let a=await Tt.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r||this.getAuthToken()}`}});a.status===200&&(o.debug("[PERSONAL AGENT] Backend stop successful:",a.data),a.data.stopped_sessions&&o.debug("[PERSONAL AGENT] Stopped sessions:",a.data.stopped_sessions),a.data.stopped_tools&&o.debug("[PERSONAL AGENT] Stopped tools:",a.data.stopped_tools))}catch(e){o.debug("[PERSONAL AGENT] Backend stop request failed:",e.message)}}async completeConversation(e,t){o.debug(`[PERSONAL AGENT] Starting conversation completion for: ${t}`),V.getInstance().handleConversationComplete();let i={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",i),this.resetState(),o.debug(`[PERSONAL AGENT] Conversation completion finished for: ${t}`)}resetState(){this.currentOutput="",this.completeOutputWithToolResults="",this.currentPromptId=null,this.currentModel=null,this.currentTodoList=null,this.activeWebViewURLs=[],this.operatorTaskState=null,this.currentSessionId=null,this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear()}getCurrentTodoList(){return this.currentTodoList}getActiveWebViewURLs(){return this.activeWebViewURLs}getOperatorTaskState(){return this.operatorTaskState}getCompleteOutput(){return this.completeOutputWithToolResults||this.currentOutput}get isProcessing(){return this.currentAbortController!==null||this.currentPromptId!==null}}});var Ss={};te(Ss,{FirebaseNativeService:()=>Me,TaskMode:()=>kt,TaskStatus:()=>It});import{getDatabase as fn,ref as Et,onValue as vn,update as bn,set as Sn,serverTimestamp as wn}from"firebase/database";import{EventEmitter as yn}from"events";var kt,It,Me,xt=F(()=>{"use strict";U();Ue();kt=(t=>(t.NEW="new",t.EXISTING="existing",t))(kt||{}),It=(s=>(s.PENDING="pending",s.PROCESSING="processing",s.COMPLETED="completed",s))(It||{}),Me=class c extends yn{static instance;app=null;database=null;auth=null;listenerHandle=null;currentUserId=null;currentDeviceId=null;currentTaskId=null;firebaseAPI;get databaseInstance(){return this.database}completedObserver=null;errorObserver=null;stopObserver=null;constructor(){super(),o.debug("[Firebase Native] Service created, waiting for shared Firebase instances..."),this.firebaseAPI=pe.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=fn(e),o.debug(`[Firebase Native] Firebase instances configured with auth user: ${t?.currentUser?.uid||"none"}`)}ensureFirebaseReady(){return!this.database||!this.auth?(o.error("[Firebase Native] Firebase not initialized. Call setFirebaseInstances first."),!1):!0}static getInstance(){return c.instance||(c.instance=new c),c.instance}async startListening(e,t){if(o.debug("[Firebase Native] Starting task listener",{userId:e,deviceId:t}),!this.ensureFirebaseReady()){o.error("[Firebase Native] Firebase not initialized properly");return}o.debug("[Firebase Native] Firebase is ready"),this.stopListening(),this.currentUserId=e,this.currentDeviceId=t;let s=`users/${e}/devices/${t}/tasks`;o.debug("[Firebase Native] Creating Firebase reference",{taskPath:s});let i=Et(this.database,s),n=this.auth?.currentUser;o.debug("[Firebase Native] Current Firebase auth state",{authenticated:!!n,uid:n?.uid||"none",email:n?.email||"none"}),this.listenerHandle=vn(i,r=>{o.debug("[Firebase Native] Data change event received",{exists:r.exists(),key:r.key,taskCount:r.val()?Object.keys(r.val()).length:0}),this.handleTasksSnapshot(r)},r=>{o.error("[Firebase Native] Firebase listener error",{code:r.code||"unknown",message:r.message,authState:this.auth?.currentUser?.uid||"null"})}),o.debug("[Firebase Native] Firebase listener established",{taskPath:s,deviceId:t}),this.emit("listening",{userId:e,deviceId:t})}handleTasksSnapshot(e){let t=e.val();if(!t){o.debug("[Firebase Native] No tasks in snapshot");return}let s=Object.entries(t);o.debug("[Firebase Native] Processing tasks from snapshot",{taskCount:s.length});for(let[i,n]of s){let r=n;if(o.debug("[Firebase Native] Checking task",{taskId:i,status:r.status,mode:r.mode,fromDevice:r.fromDeviceId,toDevice:r.toDeviceId}),r.status==="pending"){if(this.currentTaskId===i){o.debug("[Firebase Native] Already processing task - skipping",{taskId:i});continue}o.debug("[Firebase Native] Found PENDING task - processing",{taskId:i}),this.handleIncomingTask(i,r)}else o.debug("[Firebase Native] Task not pending - skipping",{taskId:i,status:r.status})}}async handleIncomingTask(e,t){o.debug("[Firebase Native] Handling incoming task",{taskId:e,prompt:t.prompt.substring(0,100),mode:t.mode,status:t.status});try{this.currentTaskId=e,o.debug("[Firebase Native] Updating task status to PROCESSING",{taskId:e}),await this.updateTaskStatus(e,"processing"),o.debug("[Firebase Native] Starting task execution",{taskId:e}),await this.executeTask(e,t.prompt,t.mode),o.debug("[Firebase Native] Task execution initiated successfully",{taskId:e})}catch(s){o.error("[Firebase Native] Error processing task",{taskId:e,error:s.message,stack:s.stack}),await this.updateTaskStatus(e,"completed",`Error: ${s.message}`)}}async executeTask(e,t,s){o.debug(`[FIREBASE-NATIVE] Executing task: ${e} with mode: ${s}`),o.debug(`[FIREBASE-NATIVE] Prompt to execute: ${t}`),o.debug(`[FIREBASE-NATIVE] Setting up result monitoring for task: ${e}`),this.setupResultMonitoring(e);try{if(!(await Promise.resolve().then(()=>(ae(),Ee))).PersonalAgentService.getInstance()){o.error("[FIREBASE-NATIVE] PersonalAgentService not available - failing task"),this.cleanupObservers();return}o.debug("[FIREBASE-NATIVE] PersonalAgentService available, proceeding with task execution"),s==="new"?o.debug("[FIREBASE-NATIVE] Mode: NEW - Starting fresh conversation"):o.debug("[FIREBASE-NATIVE] Mode: EXISTING - Adding to current conversation"),o.debug(`[FIREBASE-NATIVE] Executing prompt through UI flow: ${t}`),this.emit("taskReceived",{taskId:e,prompt:t,mode:s==="new"?"new":"existing"}),o.debug("[FIREBASE-NATIVE] Task execution initiated through UI flow")}catch(i){o.error("[FIREBASE-NATIVE] Task execution failed:",i.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ae(),Ee)),s=t.getInstance();this.completedObserver=i=>{this.currentTaskId===e&&(o.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.message||i||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${n}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=i=>{if(this.currentTaskId!==e)return;let n=i?.reason;o.debug(`[RESULT MONITOR] Task ${e} stopped: ${n}`),setTimeout(()=>{this.cleanupObservers()},100)},s.on("BotResponseStopped",this.stopObserver),o.debug(`[RESULT MONITOR] Monitoring setup complete for task: ${e}`)}async cleanupObservers(){let{PersonalAgentService:e}=await Promise.resolve().then(()=>(ae(),Ee)),t=e.getInstance();this.completedObserver&&(t.off("BotResponseCompleted",this.completedObserver),this.completedObserver=null),this.errorObserver&&(t.off("BotResponseError",this.errorObserver),this.errorObserver=null),this.stopObserver&&(t.off("BotResponseStopped",this.stopObserver),this.stopObserver=null),o.debug("[CLEANUP] All observers cleaned up")}async updateTaskStatus(e,t,s){if(!this.currentUserId||!this.currentDeviceId){o.error("[Firebase Native] Cannot update task - no user/device info",{userId:this.currentUserId||"missing",deviceId:this.currentDeviceId||"missing"});return}let i=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,n={status:t,updatedAt:"firebase_timestamp"};s&&(n.result=s),o.debug("[Firebase Native] Attempting to update task status",{taskId:e,path:i,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(i,n),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(r){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:i,error:r.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Et(this.database,i),l={status:t,updatedAt:wn()};s&&(l.result=s),await bn(a,l),o.debug("[Firebase Native] Fallback succeeded - updated via Firebase SDK",{taskId:e})}else o.error("[Firebase Native] Database not available for fallback")}catch(a){o.error("[Firebase Native] Fallback also failed",{taskId:e,error:a.message})}}}async sendTaskToDevice(e,t,s,i){let n=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;o.debug("[Firebase Native] Sending task to device",{taskId:n,targetDeviceId:t,mode:i});try{let r=Et(this.database,`users/${e}/devices/${t}/tasks/${n}`),a={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:i,timestamp:Date.now(),status:"pending"};return await Sn(r,a),o.debug("[Firebase Native] Task sent successfully",{taskId:n,targetDeviceId:t}),n}catch(r){throw r}}stopListening(){if(o.debug("[Firebase Native] Stopping listeners",{userId:this.currentUserId||"none",deviceId:this.currentDeviceId||"none",hasMainListener:!!this.listenerHandle}),this.listenerHandle)try{this.listenerHandle(),this.listenerHandle=null,o.debug("[Firebase Native] Main task listener stopped successfully")}catch(e){o.error("[Firebase Native] Error stopping main listener",{error:e.message})}this.currentUserId=null,this.currentDeviceId=null,this.currentTaskId=null,o.debug("[Firebase Native] All listeners stopped and session cleared")}getCurrentSession(){return{userId:this.currentUserId,deviceId:this.currentDeviceId,taskId:this.currentTaskId}}}});import{EventEmitter as Tn}from"events";var Ie,Dt=F(()=>{"use strict";ue();se();Ue();xt();ae();U();Ie=class c extends Tn{static instance;deviceRegistrationService;authService;firebaseAPI;firebaseNative;currentUserId=null;currentDeviceId=null;currentTaskId=null;isCurrentlyListening=!1;pollingInterval=null;pendingTasksQueue=[];overlayManager=null;constructor(){super(),this.deviceRegistrationService=ne.getInstance(),this.authService=q.getInstance(),this.firebaseAPI=pe.getInstance(),this.firebaseNative=Me.getInstance(),this.firebaseNative.on("taskReceived",e=>{this.handleNativeTaskReceived(e)}),this.authService.on("SnowXSignOut",()=>{this.stopListening()}),this.setupTaskCompletionListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupTaskCompletionListener(){let e=K.getInstance();e.on("BotResponseCompleted",()=>{this.processNextQueuedTask()}),e.on("BotResponseStopped",()=>{this.processNextQueuedTask()}),e.on("BotResponseError",()=>{this.processNextQueuedTask()})}processNextQueuedTask(){setTimeout(()=>{if(K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)||this.pendingTasksQueue.length===0)return;let s=this.pendingTasksQueue.shift();this.executeTaskImmediately(s.taskId,s.prompt,s.mode)},500)}async startListening(e,t){let s=t||this.deviceRegistrationService.getCurrentDeviceId();if(!s){o.error("No device ID available - cannot start listening");return}this.currentUserId=e,this.currentDeviceId=s,o.debug(`Starting listener - User: ${e}, Device: ${s}`),this.isCurrentlyListening&&this.stopListening();try{await this.ensureFirebaseAuthenticated(e);let i=this.authService.getFirebaseAuth();if(!i?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(i.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",i.currentUser.uid,"Requested:",e),o.error("Refusing to start listener for different user");return}o.debug("User ID validated - Firebase UID matches requested user ID"),this.setupFirebaseListeners(e,s)}catch(i){throw o.error("Failed to start listener:",i.message),i}}setupFirebaseListeners(e,t){this.isCurrentlyListening=!0,this.firebaseNative.startListening(e,t),o.debug(`CrossDevice started listening for cross-device tasks: /users/${e}/devices/${t}/tasks`)}async ensureFirebaseAuthenticated(e){let t=this.authService.getFirebaseAuth();if(t?.currentUser){o.debug("[CrossDevice] Firebase already authenticated - UID:",t.currentUser.uid);return}if(!this.authService.isAuthenticated()){o.error("No stored user ID found - cannot authenticate Firebase for listeners");return}o.debug("Found stored user ID, getting custom token from API...");try{let s=await this.authService.getCustomTokenFromAPI(e);if(t){let i=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",i.user.uid)}}catch(s){o.warn("Firebase authentication failed:",s.message),o.warn("Listeners may not work properly without Firebase Auth")}}async handleNativeTaskReceived(e){o.debug("Native Firebase task received:",e.taskId);try{if(!this.validateTaskId(e.taskId)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",e.taskId),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",e.taskId),this.currentTaskId=e.taskId,o.debug("Triggering UI flow for cross-device task:",e.taskId),this.overlayManager&&(this.overlayManager.currentInput=e.prompt),this.emit("CrossDeviceTaskSendMessage",{taskId:e.taskId,prompt:e.prompt,mode:e.mode}),o.debug("Cross-device task UI flow triggered successfully")}catch(t){o.error("Error executing native task:",t.message)}}async processIncomingTask(e,t){if(!(!this.currentUserId||!this.currentDeviceId)){o.debug("Processing task:",e,"Mode:",t.mode),await this.updateTaskStatus(e,"processing");try{this.overlayManager&&(t.mode==="new"&&await this.overlayManager.startNewConversation(),this.currentTaskId=e,this.setupResultMonitoring(e),this.overlayManager.messageHandler&&await this.overlayManager.messageHandler.sendMessage(t.prompt))}catch(s){o.error("Failed to process task:",s.message)}}}stopListening(){this.isCurrentlyListening=!1,this.firebaseNative.stopListening(),this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),o.debug("Stopped native Firebase listeners for cross-device tasks")}validateTaskId(e){if(!/^task_\d{13}_[a-z0-9]{9}$/.test(e))return!1;let s=e.split("_");if(s.length!==3||s[0]!=="task")return!1;let i=s[1],n=s[2];return i.length!==13||!Number.isInteger(Number(i))||n.length!==9?!1:/^[a-z0-9]+$/.test(n)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,i=t.prompt,n=t.mode,r=t.status;if(!s||!i||!n||r!=="pending")return;if(!this.validateTaskId(s)){o.warn("🚨 [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("🚨 [SECURITY] Task ID:",s),o.warn("🚨 [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("🚨 [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("✅ [SECURITY] Task ID validation passed:",s);let a="existing";this.currentTaskId=s,await this.updateTaskStatus(s,"processing"),await this.executeTask(s,i,a)}catch(t){o.error("Error handling incoming task:",t.message)}}async executeTask(e,t,s){if(o.debug(`Executing task: ${e} with mode: ${s}`),o.debug(`Prompt to execute: ${t}`),K.getInstance().isProcessing||(this.overlayManager?.isLoading??!1)){o.debug(`System is busy - queueing cross-device task: ${e}`);let r={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(r),o.debug(`Task ${e} added to queue. Queue length: ${this.pendingTasksQueue.length}`),await this.updateTaskStatus(e,"processing");return}o.debug(`System is not busy - executing task immediately: ${e}`),await this.executeTaskImmediately(e,t,s)}async executeTaskImmediately(e,t,s){try{if(!this.overlayManager){this.cleanupObservers();return}this.setupResultMonitoring(e),this.overlayManager.currentInput=t,process.nextTick(()=>{o.debug("Emitting CrossDeviceTaskSendMessage - TaskId:",e,"Mode:",s),this.emit("CrossDeviceTaskSendMessage",{taskId:e,prompt:t,mode:s})})}catch(i){o.error("Task execution failed:",i.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,i={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,i)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING ====="),console.log("🔔 [CROSS-DEVICE] Setting up monitoring for task:",e);let t=()=>{console.log("✅ [CROSS-DEVICE] BotResponseCompleted event received"),console.log("✅ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("✅ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("✅ [CROSS-DEVICE] Task IDs match - processing completion"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring completion")},s=n=>{console.log("❌ [CROSS-DEVICE] BotResponseError event received:",n),console.log("❌ [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("❌ [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("❌ [CROSS-DEVICE] Task IDs match - processing error"),this.cleanupObservers()):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring error")},i=n=>{console.log("🛑 [CROSS-DEVICE] BotResponseStopped event received:",n),console.log("🛑 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("🛑 [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("🛑 [CROSS-DEVICE] Task IDs match - processing stop"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("⏭️ [CROSS-DEVICE] Task IDs do not match - ignoring stop")};console.log("👂 [CROSS-DEVICE] Setting up event listeners..."),this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",i),console.log("✅ [CROSS-DEVICE] Result monitoring setup complete for task:",e),console.log("🔔 [CROSS-DEVICE] ===== SETUP RESULT MONITORING END =====")}cleanupObservers(){console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS ====="),console.log("🧹 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("👂 [CROSS-DEVICE] Removing event listeners..."),this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),console.log("✅ [CROSS-DEVICE] Event listeners removed"),console.log("🧹 [CROSS-DEVICE] Clearing current task ID"),this.currentTaskId=null,console.log("🧹 [CROSS-DEVICE] ===== CLEANUP OBSERVERS END =====")}isListening(){return this.isCurrentlyListening}getListeningPath(){return!this.currentUserId||!this.currentDeviceId?null:`/users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks`}getDeviceId(){return this.deviceRegistrationService.getCurrentDeviceId()}testValidateTaskId(e){return this.validateTaskId(e)}async submitPromptToDevice(e,t,s="new"){if(!this.currentUserId)throw new Error("Not authenticated - cannot submit task");let i=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={taskId:i,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:ge,status:"pending"},r=`users/${this.currentUserId}/devices/${e}/tasks/${i}`;try{await this.firebaseAPI.writeRealtimeData(r,n),o.debug("Task submitted to device:",e)}catch(a){throw o.error("Failed to submit task:",a.message),a}}async getAvailableDevices(){if(!this.currentUserId)return[];try{let e=`users/${this.currentUserId}/devices`,t=await this.firebaseAPI.getRealtimeData(e)||{};return Object.entries(t).map(([s,i])=>({id:s,...i})).filter(s=>s.isOnline&&s.id!==this.currentDeviceId)}catch(e){return o.error("Failed to get available devices:",e.message),[]}}enable(){o.debug("[CROSS DEVICE] Service enabled")}disable(){o.debug("[CROSS DEVICE] Service disabled"),this.stopListening()}isEnabled(){return this.isCurrentlyListening}destroy(){o.debug("[CROSS DEVICE] Service destroyed"),this.stopListening(),this.removeAllListeners()}}});var Es={};te(Es,{SnowXStreamHandlerService:()=>Pt});import{EventEmitter as An}from"events";var Pt,ks=F(()=>{"use strict";Pt=class extends An{buffer="";fullResponse="";totalBytesReceived=0;linesProcessed=0;dataLinesFound=0;contentChunksReceived=0;rawDataReceived="";byteBuffer=Buffer.alloc(0);thinkingContent="";regularContent="";isInThinkingBlock=!1;thinkingBuffer="";isCancelled=!1;constructor(){super()}async processStreamingResponse(e,t,s,i,n){let r=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let g=this.byteBuffer.toString("utf8");this.buffer+=g,this.rawDataReceived+=g,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,i,n)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,i,n),this.printFinalStatistics(),!this.fullResponse&&!n){l(new Error("No response received"));return}a()}),e.on("error",u=>{l(u)})})}processBufferedLines(e,t,s){if(this.isCancelled)return;let i,n=this.buffer.indexOf(`\r
240
240
  `);if(n!==-1)i=n;else{let r=this.buffer.indexOf(`
241
241
  `);if(r!==-1)i=r;else{let a=this.buffer.indexOf("\r");if(a!==-1)i=a;else return}}for(;i!==-1;){if(this.isCancelled)return;let r=this.buffer.substring(0,i);this.linesProcessed++,this.buffer.substring(i,i+2)===`\r
242
242
  `?this.buffer=this.buffer.substring(i+2):this.buffer=this.buffer.substring(i+1);let a=r.trim();if(!a){i=this.findNextLineEnd();continue}if(a.startsWith(":")){i=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),i=this.findNextLineEnd()}}processDataLine(e,t,s,i){if(this.isCancelled)return;this.dataLinesFound++;let n=e.substring(6).trim();if(n==="[DONE]"){this.emit("streamEnd");return}if(n)try{let r=JSON.parse(n);if(r.choices&&r.choices.length>0){let a=r.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)i?.(l);a.delta.content&&(this.contentChunksReceived++,this.processThinkingContent(a.delta.content,t,s))}}catch{}}processThinkingContent(e,t,s){if(!this.isCancelled)for(this.thinkingBuffer+=e;;)if(this.isInThinkingBlock){let i=this.thinkingBuffer.indexOf("</think>");if(i!==-1){let n=this.thinkingBuffer.substring(0,i);n&&(this.thinkingContent+=n,s?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(i+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",s?.(this.thinkingContent));break}else{let i=this.thinkingBuffer.indexOf("<think>");if(i!==-1){let n=this.thinkingBuffer.substring(0,i);n&&(this.regularContent+=n,this.fullResponse+=n,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(i+7),this.isInThinkingBlock=!0;continue}this.thinkingBuffer&&(this.regularContent+=this.thinkingBuffer,this.fullResponse+=this.thinkingBuffer,this.thinkingBuffer="",t(this.regularContent));break}}handleNonSSEResponse(e,t,s){if(this.rawDataReceived.startsWith("data: ")){let i=this.rawDataReceived.substring(6).trim();try{let n=JSON.parse(i);n.choices&&n.choices.length>0&&n.choices[0].delta.content&&this.processThinkingContent(n.choices[0].delta.content,e,t)}catch{}}else try{let i=JSON.parse(this.rawDataReceived);i.choices?.[0]?.message?.content&&this.processThinkingContent(i.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zinley/orion",
3
- "version": "1.2.6",
3
+ "version": "1.2.7",
4
4
  "description": "A fully autonomous on-device agent that lives in your terminal.",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",