@zinley/orion 1.1.8

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 (3) hide show
  1. package/README.md +48 -0
  2. package/dist/index.js +336 -0
  3. package/package.json +71 -0
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # Orion CLI
2
+
3
+ A fully autonomous on-device agent that lives in your terminal. With 200+ tools, Orion CLI delivers the same powerful capabilities as Orion Desktop.
4
+
5
+ <img src="https://github.com/Zinley-dev/orion-cli-1/blob/main/cli-demo.gif?raw=1" />
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm i @zinley/orion
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```bash
16
+ ./orion
17
+ ```
18
+
19
+ Works across directories - run from anywhere, no navigation required.
20
+
21
+ ## Interactive CLI Integration
22
+
23
+ Orion can interactively use Claude Code, Gemini CLI, or any interactive CLI app—whether AI-powered or not. Just tell Orion what you need, and it will handle it seamlessly. No additional setup required—Orion manages the entire interaction with your favorite tools.
24
+
25
+ <img src="https://github.com/Zinley-dev/orion-cli-1/blob/main/merged_video.gif?raw=1" />
26
+
27
+ ## Dashboard
28
+
29
+ Visit [meetorion.app/dashboard](https://meetorion.app/dashboard) to:
30
+ - Enable integrations
31
+ - Configure secure secret keys
32
+ - Set up agent confirmation for sensitive actions
33
+
34
+ ## Resources
35
+
36
+ - [Documentation](https://docs.meetorion.app/get-started/welcome)
37
+ - [Discord Community](https://discord.com/invite/XuTEW9Ggga)
38
+ - [Privacy Policy](https://meetorion.app/privacy)
39
+ - [Security](https://meetorion.app/security)
40
+ - [Terms of Service](https://meetorion.app/terms)
41
+
42
+ ## Reporting Issues
43
+
44
+ Use `/bug` within Orion or file a GitHub issue.
45
+
46
+ ## Privacy
47
+
48
+ We collect usage data and feedback to improve Orion. Your data is protected with limited retention periods and restricted access. See our [Privacy Policy](https://meetorion.app/privacy) for details.
package/dist/index.js ADDED
@@ -0,0 +1,336 @@
1
+ #!/usr/bin/env node
2
+ var Os=Object.defineProperty;var F=(c,e)=>()=>(c&&(e=c(c=0)),e);var te=(c,e)=>{for(var t in e)Os(c,t,{get:e[t],enumerable:!0})};var Bt={};te(Bt,{AccountStatus:()=>Lt,SNOWX_MODELS:()=>X,SignUpMethod:()=>Ut,SnowXProvider:()=>lt,TaskStatus:()=>Wt,TodoStatus:()=>Mt});var lt,X,Mt,Wt,Ut,Lt,we=F(()=>{"use strict";lt=(u=>(u.GPT="GPT",u.BEDROCK="BEDROCK",u.ANTHROPIC="ANTHROPIC",u.OPENAI="OPENAI",u.FOUNDRY="FOUNDRY",u.DEEPSEEK="deepseek",u.GOOGLE="google",u.X_AI="x-ai",u.QWEN="qwen",u))(lt||{}),X=[{name:"snowx-5h",displayName:"GPT-5 High",provider:"GPT",apiModelName:"gpt-5-high",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-5c",displayName:"GPT-5",provider:"GPT",apiModelName:"gpt-5",maxTokens:32768,contextWindow:1047576,supportsVision:!0},{name:"snowx-c4.1",displayName:"Claude Opus 4.1",provider:"BEDROCK",apiModelName:"us.anthropic.claude-opus-4-20250514-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-c4",displayName:"Claude Opus 4",provider:"ANTHROPIC",apiModelName:"claude-opus-4",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-c5",displayName:"Claude Sonnet 4.5",provider:"ANTHROPIC",apiModelName:"claude-sonnet-4-5",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c3",displayName:"Claude 4 Sonnet",provider:"ANTHROPIC",apiModelName:"claude-4-sonnet-20250514",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-c1",displayName:"Claude 3.7 Sonnet",provider:"BEDROCK",apiModelName:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",maxTokens:4096,contextWindow:2e5,supportsVision:!0},{name:"snowx-h4",displayName:"Claude Haiku 4.5",provider:"ANTHROPIC",apiModelName:"claude-3-5-haiku-20241022",maxTokens:8192,contextWindow:2e5,supportsVision:!0},{name:"snowx-o3-pro",displayName:"GPT o3-pro",provider:"GPT",apiModelName:"o3-pro",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"high"},{name:"snowx-o3",displayName:"GPT o3",provider:"GPT",apiModelName:"o3",maxTokens:1e5,contextWindow:2e5,supportsVision:!0,reasoningEffort:"medium"},{name:"snowx-o4-mini",displayName:"GPT o4-mini",provider:"GPT",apiModelName:"o4-mini",maxTokens:65536,contextWindow:128e3,supportsVision:!0,reasoningEffort:"low"},{name:"snowx-4.1",displayName:"GPT-4.1",provider:"GPT",apiModelName:"gpt-4.1",maxTokens:4096,contextWindow:128e3,supportsVision:!0},{name:"snowx-g1",displayName:"Gemini 2.5 Pro",provider:"google",apiModelName:"gemini-2.0-flash-exp",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g2",displayName:"Gemini Flash 2.5",provider:"google",apiModelName:"gemini-2.0-flash-exp",maxTokens:8192,contextWindow:1e6,supportsVision:!0},{name:"snowx-g4fr",displayName:"Grok-4 Fast Reasoning",provider:"x-ai",apiModelName:"grok-4-fast-reasoning",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-g4f",displayName:"Grok-4 Fast",provider:"x-ai",apiModelName:"grok-4-fast",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-d31",displayName:"DeepSeek-V3.1",provider:"deepseek",apiModelName:"DeepSeek-V3.1",maxTokens:8192,contextWindow:64e3,supportsVision:!1},{name:"snowx-q3",displayName:"Qwen3 Coder 480B A35B",provider:"qwen",apiModelName:"Qwen3-Coder-480B-A35B",maxTokens:8192,contextWindow:128e3,supportsVision:!1},{name:"snowx-q3-325",displayName:"Qwen3 235B A22B 2507",provider:"qwen",apiModelName:"Qwen3-235B-A22B-2507",maxTokens:8192,contextWindow:128e3,supportsVision:!1}],Mt=(s=>(s.PENDING="pending",s.IN_PROGRESS="in_progress",s.COMPLETED="completed",s))(Mt||{}),Wt=(a=>(a.STARTED="started",a.RUNNING="running",a.COMPLETED="completed",a.FINISHED="finished",a.FAILED="failed",a.STOPPED="stopped",a.CANCELLED="cancelled",a))(Wt||{}),Ut=(t=>(t.EMAIL_PASSWORD="email_password",t.GOOGLE="google",t))(Ut||{}),Lt=(s=>(s.ACTIVE="active",s.SUSPENDED="suspended",s.PENDING="pending",s))(Lt||{})});var ut,o,U=F(()=>{"use strict";ut=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(`\u274C ${e}`,...t)}warn(e,...t){this.logLevel>=1&&console.warn(`\u26A0\uFE0F ${e}`,...t)}info(e,...t){this.logLevel>=2&&console.log(`\u2139\uFE0F ${e}`,...t)}success(e,...t){this.logLevel>=2&&console.log(`\u2705 ${e}`,...t)}debug(e,...t){this.debugMode&&this.logLevel>=3&&console.log(`\u{1F50D} [DEBUG] ${e}`,...t)}status(e,...t){console.log(e,...t)}system(e){console.log(e)}},o=ut.getInstance();process.env.DEBUG==="true"&&(o.setDebugMode(!0),o.setLogLevel(3))});var ie={};te(ie,{UserDefaults:()=>pe});import Ne from"fs";import dt from"path";import Fs from"os";var pt,pe,Y=F(()=>{"use strict";U();pt=class c{static instance;preferencesPath;preferences={};constructor(){let e=dt.join(Fs.homedir(),".orion");this.preferencesPath=dt.join(e,"preferences.json"),this.loadPreferences()}static getInstance(){return c.instance||(c.instance=new c),c.instance}loadPreferences(){try{if(Ne.existsSync(this.preferencesPath)){let e=Ne.readFileSync(this.preferencesPath,"utf8");this.preferences=JSON.parse(e),o.debug(`Loaded preferences from ${this.preferencesPath}`)}}catch{o.debug("Failed to load preferences, using defaults"),this.preferences={}}}savePreferences(){try{let e=dt.dirname(this.preferencesPath);Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0}),Ne.writeFileSync(this.preferencesPath,JSON.stringify(this.preferences,null,2)),o.debug(`Saved preferences to ${this.preferencesPath}`)}catch(e){o.debug(`Failed to save preferences: ${e.message}`)}}set(e,t){this.preferences[e]=t,this.savePreferences(),o.debug(`Set preference: ${e} = ${t}`)}string(e){let t=this.preferences[e];return typeof t=="string"?t:null}integer(e){let t=this.preferences[e];return typeof t=="number"?t:null}boolean(e){let t=this.preferences[e];return typeof t=="boolean"?t:null}removeObject(e){delete this.preferences[e],this.savePreferences(),o.debug(`Removed preference: ${e}`)}remove(e){this.removeObject(e)}getAllKeys(){return Object.keys(this.preferences)}},pe=pt.getInstance()});var ue,gt=F(()=>{"use strict";we();Y();U();ue=class{static getDisplayName(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}static getRequiredTier(e){switch(e){case"snowx-c4.1":case"snowx-c4":case"snowx-o3-pro":return 2;case"snowx-4.1":case"snowx-g2":case"snowx-5c":case"snowx-c1":case"snowx-h4":case"snowx-d31":case"snowx-q3":case"snowx-q3-325":return 0;case"snowx-5h":case"snowx-c5":case"snowx-c3":case"snowx-o3":case"snowx-o4-mini":case"snowx-g1":case"snowx-g4fr":case"snowx-g4f":default:return 1}}static getCurrentUserTier(){let e=pe.integer("userSubscriptionTier");return e!==null&&e>=0&&e<=2?e:0}static setUserTier(e){pe.set("userSubscriptionTier",e),o.debug(`User tier updated to: ${e} (${this.getDisplayName(e)})`)}static isModelAccessible(e,t){let s=this.getRequiredTier(e),r=t>=s;return o.debug(`Access check for ${e}: User tier=${t} (${this.getDisplayName(t)}), Required=${s} (${this.getDisplayName(s)}), Access=${r}`),r}static isModelAccessibleForCurrentUser(e){let t=this.getCurrentUserTier();return this.isModelAccessible(e,t)}static getAccessibleModels(e){return X.filter(t=>this.isModelAccessible(t.name,e))}static getAccessibleModelsForCurrentUser(){let e=this.getCurrentUserTier();return this.getAccessibleModels(e)}static getAccessDeniedMessage(e){switch(this.getRequiredTier(e)){case 1:return"This model requires a Plus subscription. Please upgrade to access.";case 2:return"This model requires a Pro subscription. Please upgrade to access.";default:return"This model is not available with your current subscription."}}static getModelDisplayNameWithTier(e){return e.displayName}}});import $s from"axios";import{EventEmitter as _s}from"events";var me,ge,Ue=F(()=>{"use strict";me="firebase_timestamp",ge=class c extends _s{static instance;client;baseURL=process.env.SNOWX_FIREBASE_API||"https://snowx.ai/api-beta/api/fb";accessTokenKey="snowx_access_token";constructor(){super(),this.client=$s.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(()=>(Y(),ie));return e.string(this.accessTokenKey)}async getFirebaseIdToken(){let{AuthService:e}=await Promise.resolve().then(()=>(se(),Gt));return await e.getInstance().getFirebaseIdToken()}async addAuthorizationHeader(e){let t=await this.getFirebaseIdToken();if(t)e.Authorization=`Bearer ${t}`;else{let s=await this.getAccessToken();s&&(e.Authorization=s)}}async createDocument(e,t,s){let r={"Content-Type":"application/json"};await this.addAuthorizationHeader(r);let n={collection:e,docId:t,data:s};try{let a=(await this.client.post("/documents",n,{headers:r})).data;if(!a.success){let l=a.error||"Unknown error";throw console.error("\u274C [SnowXFirebaseAPI] API returned success=false:",l),new Error(l)}}catch(i){throw console.error("\u274C [SnowXFirebaseAPI] createDocument failed:"),console.error("\u274C [SnowXFirebaseAPI] Error status:",i.response?.status),console.error("\u274C [SnowXFirebaseAPI] Error data:",i.response?.data),console.error("\u274C [SnowXFirebaseAPI] Full error:",i),i}}async createConversation(e,t){return this.createDocument("snowx_conversations",e,t)}async updateConversation(e,t){return this.updateDocument("snowx_conversations",e,t)}async getDocuments(e,t){let s={};await this.addAuthorizationHeader(s);let r={collection:e};t&&(r.limit=t.toString());try{let i=(await this.client.get("/documents",{params:r,headers:s})).data;if(i.success)return Array.isArray(i.doc)?i.doc:[];{let a=i.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async queryDocuments(e,t,s,r,n,i,a){let l={};await this.addAuthorizationHeader(l);let u={collection:e,field:t,operator:s,value:String(r)};n&&(u.limit=n.toString()),i&&(u.orderBy=i),a&&(u.orderDirection=a);try{let h=(await this.client.get("/documents/query",{params:u,headers:l})).data;if(h.success)return Array.isArray(h.doc)?h.doc:h.doc&&typeof h.doc=="object"?[h.doc]:[];{let m=h.error||"Unknown error";throw new Error(m)}}catch(g){throw g}}async getDocument(e,t){let s={};await this.addAuthorizationHeader(s);let r={collection:e};try{let i=(await this.client.get(`/documents/${t}`,{params:r,headers:s})).data;return i.success?i.doc:null}catch(n){throw n}}async updateDocument(e,t,s){let r={"Content-Type":"application/json"};await this.addAuthorizationHeader(r);let n={collection:e,data:s};try{let a=(await this.client.patch(`/documents/${t}`,n,{headers:r})).data;if(!a.success){let l=a.error||"Unknown error";throw new Error(l)}}catch(i){throw i}}async deleteDocument(e,t){let s={};await this.addAuthorizationHeader(s);let r={collection:e};try{let i=(await this.client.delete(`/documents/${t}`,{params:r,headers:s})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async createDocumentInSubcollection(e,t,s,r,n){let i=`${e}/${t}/${s}`;return this.createDocument(i,r,n)}async getUserConversations(e,t){return this.queryDocuments("snowx_conversations","userId","==",e,t,"updatedAt","desc")}async saveConversationMessages(e,t){let s=`snowx_conversations/${e}/messages`;try{let r=await this.getDocuments(s);for(let n of r)n.id&&await this.deleteDocument(s,n.id);for(let[n,i]of t.entries()){if(i.role==="system"||i.isStreaming)continue;let a=`message_${n}_${Date.now()}`,l={id:a,role:i.role,content:i.content,timestamp:i.timestamp||new Date,order:n,conversationId:e};try{await this.createDocument(s,a,l)}catch{}}}catch(r){throw r}}async getConversationMessages(e){let t=`snowx_conversations/${e}/messages`;return(await this.getDocuments(t)).sort((r,n)=>{if(r.order!==void 0&&n.order!==void 0)return r.order-n.order;let i=new Date(r.timestamp||0).getTime(),a=new Date(n.timestamp||0).getTime();return i-a})}async updateRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={path:e,updates:t};try{let i=(await this.client.put("/realtime",r,{headers:s})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async getRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=(await this.client.get("/realtime",{params:s,headers:t})).data;if(n.success)return n.doc;{let i=n.error||"Unknown error";throw new Error(i)}}catch(r){throw r}}async deleteRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let n=(await this.client.delete("/realtime",{params:s,headers:t})).data;if(!n.success){let i=n.error||"Unknown error";throw new Error(i)}}catch(r){throw r}}async getUserProfile(e){return await this.getDocument("users",e)}async createUserProfile(e,t){await this.createDocument("users",e,t)}async updateUserProfile(e,t){await this.updateDocument("users",e,t)}async getConversations(e,t=20){return await this.queryDocuments("snowx_conversations","userId","==",e,t)}async deleteConversation(e){await this.deleteDocument("snowx_conversations",e)}async getUserUsage(e){return await this.getDocument("usage",e)}async updateUserUsage(e,t){await this.createDocument("usage",e,t)}async readRealtimeData(e){let t={};await this.addAuthorizationHeader(t);let s={path:e};try{let r=await this.client.get("/realtime",{params:s,headers:t}),n=r.data;if(n.success)return r.data.data;{let i=n.error||"Unknown error";throw new Error(i)}}catch(r){throw r}}async writeRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={path:e,data:t};try{let i=(await this.client.post("/realtime",r,{headers:s})).data;if(!i.success){let a=i.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}async pushRealtimeData(e,t){let s={"Content-Type":"application/json"};await this.addAuthorizationHeader(s);let r={path:e,data:t};try{let i=(await this.client.post("/realtime/push",r,{headers:s})).data;if(i.success){if(i.key)return i.key;throw new Error("No key returned")}else{let a=i.error||"Unknown error";throw new Error(a)}}catch(n){throw n}}setAuthToken(e){console.warn("\u26A0\uFE0F setAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}clearAuthToken(){console.warn("\u26A0\uFE0F clearAuthToken is deprecated - using dynamic token from UserDefaults like SnowX")}}});var Ae={};te(Ae,{DeviceRegistrationService:()=>ne});import{EventEmitter as Ms}from"events";import{v4 as qt}from"uuid";import mt from"os";import Xt from"fs/promises";import Ws from"path";import{execSync as ht}from"child_process";import Us from"crypto";var ne,de=F(()=>{"use strict";Ue();se();U();ne=class c extends Ms{static instance;api;authService;devicesCollection="devices";isRegistering=!1;registrationPromise=null;currentUserId=null;currentDeviceId=null;configDir;constructor(){super(),this.api=ge.getInstance(),this.authService=q.getInstance(),this.configDir=Ws.join(mt.homedir(),".orion-cli"),this.setupAuthenticationListener()}static getInstance(){return c.instance||(c.instance=new c),c.instance}setupAuthenticationListener(){o.debug("[DeviceRegistration] Setting up authentication listeners..."),this.authService.on("AuthenticationComplete",t=>{o.debug(`[DeviceRegistration] Received AuthenticationComplete for user: ${t}`),this.handleUserAuthentication(t)}),this.authService.on("SnowXSignOut",()=>{o.debug("[DeviceRegistration] Received SnowXSignOut"),this.handleUserLogout()});let e=this.authService.getUserId();o.debug(`[DeviceRegistration] Initial auth check - userId: ${e}`),e&&(o.debug("[DeviceRegistration] User already authenticated, starting device registration..."),this.handleUserAuthentication(e))}async handleUserAuthentication(e){o.debug(`[DeviceRegistration] handleUserAuthentication called for user: ${e}`),o.debug(`[DeviceRegistration] Current state - userId: ${this.currentUserId}, deviceId: ${this.currentDeviceId}`),this.currentUserId!==e&&this.currentUserId&&(o.debug(`[DeviceRegistration] Different user detected - clearing session for old user: ${this.currentUserId}`),this.clearCurrentSession()),this.currentUserId=e,o.debug("[DeviceRegistration] Computing hardware-based device ID...");try{this.currentDeviceId=await this.getOrCreateDeviceIdForUser(e),o.debug(`[DeviceRegistration] \u2705 Hardware-based device ID: ${this.currentDeviceId}`)}catch(t){throw o.debug("[DeviceRegistration] \u274C FAILED to get device ID:",t.message),t}o.debug("[DeviceRegistration] Registering device..."),await this.autoRegisterDevice(e),o.debug("[DeviceRegistration] Device registration completed")}async handleUserLogout(){this.clearCurrentSession()}clearCurrentSession(){this.currentUserId=null,this.currentDeviceId=null}async autoRegisterDevice(e){try{if(!this.currentDeviceId)return;let t=this.getComputerName();await this.registerDevice(e,this.currentDeviceId,t)}catch(t){o.debug("Auto-registration failed:",t.message)}}async getOrCreateDeviceIdForUser(e){let t=await this.getHardwareDeviceId();return o.debug(`[DEVICE REG] Device ID: ${t}`),t}getComputerName(){return mt.hostname()||"Unknown CLI Device"}async getHardwareDeviceId(){let e=mt.platform();try{let t=null;switch(e){case"darwin":try{let a=ht("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);a&&a[1]&&(t=a[1],o.debug(`[DEVICE REG] macOS IOPlatformUUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get IOPlatformUUID, trying serial number...");try{let l=ht("ioreg -l | grep IOPlatformSerialNumber",{encoding:"utf8"}).match(/"IOPlatformSerialNumber"\s*=\s*"([^"]+)"/);l&&l[1]&&(t=l[1],o.debug(`[DEVICE REG] macOS serial number: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get serial number")}}break;case"linux":try{t=await Xt.readFile("/etc/machine-id","utf-8").then(i=>i.trim()),o.debug(`[DEVICE REG] Linux machine-id from /etc: ${t}`)}catch{try{t=await Xt.readFile("/var/lib/dbus/machine-id","utf-8").then(a=>a.trim()),o.debug(`[DEVICE REG] Linux machine-id from /var/lib/dbus: ${t}`)}catch{o.debug("[DEVICE REG] Failed to get Linux machine-id")}}break;case"win32":try{let a=ht("wmic csproduct get UUID",{encoding:"utf8"}).split(`
3
+ `).filter(l=>l.trim()&&l.trim()!=="UUID");a.length>0&&(t=a[0].trim(),o.debug(`[DEVICE REG] Windows UUID: ${t}`))}catch{o.debug("[DEVICE REG] Failed to get Windows UUID")}break;default:o.debug(`[DEVICE REG] Unsupported platform: ${e}`)}if(t&&t.trim()){let i=Us.createHash("sha256").update(t).digest("hex"),a=[i.substring(0,8),i.substring(8,12),i.substring(12,16),i.substring(16,20),i.substring(20,32)].join("-");return o.debug(`[DEVICE REG] Generated hardware-based UUID: ${a}`),a}let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie)),r="snowx_fallback_device_id",n=s.string(r);return n?o.debug(`[DEVICE REG] Using EXISTING fallback UUID: ${n}`):(n=qt(),s.set(r,n),o.debug(`[DEVICE REG] Generated NEW fallback UUID: ${n}`)),n}catch(t){o.debug(`[DEVICE REG] Error getting hardware ID: ${t.message}`);let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie)),r="snowx_fallback_device_id",n=s.string(r);return n?o.debug(`[DEVICE REG] Using EXISTING fallback UUID (error case): ${n}`):(n=qt(),s.set(r,n),o.debug(`[DEVICE REG] Generated NEW fallback UUID (error case): ${n}`)),n}}async registerDevice(e,t,s){if(this.isRegistering)return this.registrationPromise||Promise.resolve();this.isRegistering=!0,this.registrationPromise=this.performRegistration(e,t,s);try{await this.registrationPromise}finally{this.isRegistering=!1,this.registrationPromise=null}}async performRegistration(e,t,s){try{let r=await this.api.getDocument(this.devicesCollection,e);if(r&&r.devices){let n=r.devices;if(n.some(a=>a.deviceId===t)){let a=n.map(l=>l.deviceId===t?{...l,lastSeenAt:me,computerName:s,type:"on-device"}:l);await this.api.updateDocument(this.devicesCollection,e,{devices:a})}else{let a={deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:me,lastSeenAt:me};n.push(a),await this.api.updateDocument(this.devicesCollection,e,{devices:n})}}else{let i={userId:e,devices:[{deviceId:t,computerName:s,type:"on-device",platform:"cli",registeredAt:me,lastSeenAt:me}],createdAt:new Date,updatedAt:new Date};await this.api.createDocument(this.devicesCollection,e,i)}o.debug("[DeviceRegistration] Emitting DeviceRegistrationComplete event for user:",e),this.emit("DeviceRegistrationComplete",{userId:e,deviceId:t,computerName:s})}catch(r){throw r}}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("\u26A0\uFE0F [DEVICE REG] No device ID found, skipping device removal");return}let s=await this.api.getDocument(this.devicesCollection,e);if(!s||!s.devices||!Array.isArray(s.devices)){console.log("\u26A0\uFE0F [DEVICE REG] No devices document found for user");return}let r=s.devices;if(!r.some(a=>a.deviceId===t)){console.log(`\u26A0\uFE0F [DEVICE REG] Device ${t} not found in registration list`);return}let i=r.filter(a=>a.deviceId!==t);i.length===0?await this.api.deleteDocument(this.devicesCollection,e):await this.api.updateDocument(this.devicesCollection,e,{devices:i})}catch(t){console.error(`\u274C [DEVICE REG] Failed to remove device registration: ${t.message}`)}}async getUserDeviceId(e){return this.currentDeviceId?this.currentDeviceId:await this.getHardwareDeviceId()}}});var Gt={};te(Gt,{AuthService:()=>q});import{EventEmitter as Ls}from"events";import{signInAnonymously as Bs,signInWithEmailAndPassword as Gs,createUserWithEmailAndPassword as qs,signOut as Xs,onAuthStateChanged as Hs,updateProfile as Vs,signInWithCustomToken as zs}from"firebase/auth";import ye from"axios";import ft from"fs/promises";import Ht from"path";import js from"os";var q,se=F(()=>{"use strict";gt();U();q=class c extends Ls{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=Ht.join(js.homedir(),".orion-cli","auth.json")}static getInstance(){return c.instance||(c.instance=new c),c.instance}async initializeTokenFile(){try{let e=Ht.dirname(this.tokenFilePath);await ft.mkdir(e,{recursive:!0}),await this.loadStoredToken()}catch{}}async loadStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(Y(),ie)),t=e.string("snowx_auth_token"),s=e.string("snowx_access_token");if(!t||!s)try{let r=await ft.readFile(this.tokenFilePath,"utf-8"),n=JSON.parse(r);n.expiresAt>Date.now()&&(console.log("\u{1F504} Migrating authentication from file to UserDefaults..."),e.set("snowx_auth_token",n.userId),e.set("snowx_access_token",n.token),t=n.userId,s=n.token,await ft.unlink(this.tokenFilePath),console.log("\u2705 Migration completed - old auth file removed"))}catch{}if(t&&s){let r={token:s,userId:t,email:void 0,tier:0,expiresAt:Date.now()+2592e6};this.authToken=r,o.debug("Session restored from UserDefaults");try{let n=await this.getUserProfile();n&&n.tier!==void 0?this.authToken.tier=n.tier:await this.updateUserTierFromToken(r)}catch(n){console.warn("\u26A0\uFE0F Failed to fetch user profile during session restore:",n instanceof Error?n.message:"Unknown error"),await this.updateUserTierFromToken(r)}this.emit("authenticated",r)}}catch(e){console.warn("\u26A0\uFE0F Failed to load stored session:",e)}}async saveToken(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Y(),ie));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("\u274C Failed to save auth token:",t)}}async clearStoredToken(){try{let{UserDefaults:e}=await Promise.resolve().then(()=>(Y(),ie));e.remove("snowx_auth_token"),e.remove("snowx_access_token"),this.authToken=null}catch(e){console.error("\u274C Failed to clear auth token:",e)}}setFirebaseAuth(e){this.auth=e,Hs(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}ue.setUserTier(t);let{UserDefaults:s}=await Promise.resolve().then(()=>(Y(),ie));s.set("userSubscriptionTier",e.tier||0),s.set("isTrialUser",!1),o.debug(`User tier updated: ${ue.getDisplayName(t)} (${e.tier})`),o.debug(`Cached user tier in UserDefaults: ${e.tier}`)}async signInAnonymously(){if(!this.auth)return console.error("\u274C Firebase auth not initialized"),!1;try{let e=await Bs(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("\u274C Failed to sign in anonymously:",e),!1}}async signInWithEmail(e,t){if(!this.auth)return console.error("\u274C Firebase auth not initialized"),!1;try{let s=await Gs(this.auth,e,t);return this.currentUser=s.user,!0}catch(s){return console.error("\u274C Failed to sign in with email:",s.message),!1}}async signUpWithEmail(e,t,s){if(!this.auth)return console.error("\u274C Firebase auth not initialized"),!1;try{let r=await qs(this.auth,e,t);return this.currentUser=r.user,s&&await Vs(r.user,{displayName:s}),!0}catch(r){return console.error("\u274C Failed to sign up with email:",r.message),!1}}async signOut(){try{let e=this.getUserId();if(e)try{let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(de(),Ae));await t.getInstance().removeDeviceRegistration(e)}catch(t){console.warn("\u26A0\uFE0F [AUTH] Device registration cleanup failed:",t)}if(this.emit("SnowXSignOut"),this.auth)try{await Xs(this.auth)}catch(t){console.warn("\u26A0\uFE0F [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("\u274C [AUTH] Failed to sign out:",e),!1}}async getCurrentDeviceId(){if(!this.getUserId())return null;let{DeviceRegistrationService:t}=await Promise.resolve().then(()=>(de(),Ae));return t.getInstance().getCurrentDeviceId()}async clearAllSnowXUserDefaults(e){try{let{UserDefaults:t}=await Promise.resolve().then(()=>(Y(),ie)),s=["snowx_auth_token","snowx_access_token","snowx_device_id","selectedAIModel","selectedPersonalModel","selected-tts-voice","workingDirectory","enableSpeechRecognition","speechRecognitionLanguage","enableTTSOutput","systemPrompt","enableHotkey","hotkeyKey","hotkeyModifiers","fontSize","windowOpacity","enableConversationTrimming","conversationTrimThreshold","working-directory","privacy-mode-enabled","custom-user-preferences","conversationTrimMode","showTrimNotifications","userSubscriptionTier","isTrialUser","trialEndDate"];for(let i of s)t.remove(i);if(e){let i=`snowx_device_id_${e}`;t.remove(i)}let n=t.getAllKeys().filter(i=>i.startsWith("snowx_device_id_"));for(let i of n)t.remove(i)}catch(t){console.warn("\u26A0\uFE0F [AUTH] Failed to clear some user preferences:",t)}}async authenticateWithSnowX(e){try{let t;if(e?t=await ye.post(`${this.snowxAuthEndpoint}/login`,e):t=await ye.post(`${this.snowxAuthEndpoint}/guest`),t.data?.token){let s={token:t.data.token,userId:t.data.userId||"anonymous",email:t.data.email,tier:t.data.tier??0,expiresAt:Date.now()+(t.data.expiresIn||86400)*1e3};return await this.saveToken(s),!0}return!1}catch(t){return console.error("\u274C Failed to authenticate with Orion:",t.response?.data?.message||t.message),!1}}async refreshToken(){if(!this.authToken)return!1;try{let e=await ye.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("\u26A0\uFE0F 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(()=>(Y(),ie));return e.string("snowx_access_token")}async getFirebaseIdToken(){if(!this.currentUser)return null;try{return await this.currentUser.getIdToken()}catch(e){return console.error("\u274C Failed to get Firebase ID token:",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("\u26A0\uFE0F 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(){return!!this.currentUser}async autoAuthenticate(){if(await this.initializeTokenFile(),this.isAuthenticated()){let e=this.getUserId();if(e)return o.debug("Using existing authentication token"),o.debug("[AuthService] Emitting AuthenticationComplete event (existing token) for userId:",e),await this.authenticateFirebaseWithStoredToken(),this.emit("AuthenticationComplete",e),!0}return!1}async authenticateFirebaseWithStoredToken(){if(!(!this.auth||!this.authToken)){if(this.currentUser&&this.currentUser.uid===this.authToken.userId){console.log("\u{1F525} Firebase already authenticated for user:",this.authToken.userId);return}try{o.debug("Getting Firebase custom token for user:",this.authToken.userId);let e=await this.getCustomTokenFromAPIInternal(this.authToken.userId),t=await zs(this.auth,e);o.debug(`Firebase Auth successful - UID: ${t.user.uid}`),this.currentUser=t.user}catch(e){console.warn("\u26A0\uFE0F Firebase authentication failed:",e)}}}async getCustomTokenFromAPIInternal(e){o.debug(`Getting custom token from API for user: ${e}`);let t="https://snowx.ai/api-beta/api/fb/custom-token",s={userId:e},r=this.authToken?.token,n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);let i=await ye.post(t,s,{headers:n,timeout:1e4});if(i.status!==200){let l=i.data?.message||`HTTP ${i.status}`;throw new Error(`Custom token API failed: ${l}`)}let a=i.data;if(!a?.success||!a?.customToken)throw new Error("Invalid custom token response from API");return o.debug("Successfully received custom token from SnowX API"),a.customToken}async authenticateWithAccessToken(e){try{let t=await ye.get("https://snowx.ai/api-beta/users/me",{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},timeout:1e4});if(t.data?.data){let s=t.data.data,r=s.id||s.uid||s.user_id||s.userId||s.email;if(!r)throw new Error("No user ID found in API response");let n={token:e,userId:r,email:s.email,tier:s.subscription?.tier??0,expiresAt:Date.now()+720*60*60*1e3};return await this.saveToken(n),this.userProfile=s,await this.updateUserTierFromToken(n),await this.authenticateFirebaseWithStoredToken(),this.emit("authStateChanged",n),this.emit("AuthenticationComplete",r),!0}return!1}catch(t){return console.error("\u274C 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 getUserInfo(){if(!this.authToken?.token)return console.warn("\u26A0\uFE0F No auth token available"),null;try{let e=await ye.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("\u26A0\uFE0F Access token is invalid or expired"),await this.clearStoredToken()),e}}async canAccessModel(e){let t=await this.getUserTier(),s=t===1?1:t===2?2:0;return ue.isModelAccessible(e,s)}async getRateLimits(){switch(await this.getUserTier()){case 0:return{requestsPerMinute:5,requestsPerHour:50};case 1:return{requestsPerMinute:20,requestsPerHour:500};case 2:return{requestsPerMinute:50,requestsPerHour:1e3};default:return{requestsPerMinute:2,requestsPerHour:20}}}async getUserProfile(){if(!this.authToken?.token)return console.warn("\u26A0\uFE0F No auth token available for profile fetch"),null;try{let e=await ye.get(`https://snowx.ai/api-beta/api/fb/documents/${this.authToken.userId}?collection=users`,{headers:{Authorization:`${this.authToken.token}`,"Content-Type":"application/json"},timeout:1e4});if(e.data?.success&&e.data?.doc){let t=e.data.doc,s=t.subscription?.tier??0;return this.authToken.email=t.email,this.authToken.tier=s,await this.saveToken(this.authToken),await this.updateUserTierFromToken(this.authToken),{id:this.authToken.userId,email:t.email,tier:s}}return console.warn("\u26A0\uFE0F Empty response from profile API"),null}catch(e){return console.warn(`\u26A0\uFE0F 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}}});import{EventEmitter as Qs}from"events";var he,Le=F(()=>{"use strict";U();he=class c extends Qs{static instance;queuedMessages=[];isProcessingQueue=!1;maxQueueSize=5;constructor(){super()}static getInstance(){return c.instance||(c.instance=new c),c.instance}canAddToQueue(){return this.queuedMessages.length<this.maxQueueSize}addToQueue(e){if(!this.canAddToQueue())return!1;let t={id:this.generateId(),...e,timestamp:new Date};return this.queuedMessages.push(t),this.emit("queue:updated",this.queuedMessages),o.debug(`[QUEUE] Message added to queue. Total: ${this.queuedMessages.length}`),!0}removeFromQueue(e){e<this.queuedMessages.length&&(this.queuedMessages.splice(e,1),this.emit("queue:updated",this.queuedMessages))}removeFromQueueById(e){this.queuedMessages=this.queuedMessages.filter(t=>t.id!==e),this.emit("queue:updated",this.queuedMessages)}clearQueue(){this.queuedMessages=[],this.emit("queue:updated",this.queuedMessages),o.debug("[QUEUE] Queue cleared")}getNextMessage(){return this.queuedMessages[0]||null}processNextMessage(){if(this.queuedMessages.length===0)return null;let e=this.queuedMessages.shift();return this.emit("queue:updated",this.queuedMessages),e||null}startProcessing(){this.isProcessingQueue=!0,this.emit("queue:processing-started")}stopProcessing(){this.isProcessingQueue=!1,this.emit("queue:processing-stopped")}getQueuedMessages(){return[...this.queuedMessages]}getQueueCount(){return this.queuedMessages.length}hasQueuedMessages(){return this.queuedMessages.length>0}getRemainingSlots(){return this.maxQueueSize-this.queuedMessages.length}getQueueStatusText(){return this.queuedMessages.length===0?"Queue empty":this.queuedMessages.length===1?"1 message queued":`${this.queuedMessages.length} messages queued`}getPreview(e){return e.content.length<=60?e.content:e.content.substring(0,60)+"..."}generateId(){return`queue-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}});var Be,Vt=F(()=>{"use strict";U();Be=class{tools=new Map;register(e){for(let t of e.toolNames){let s=t.toLowerCase();this.tools.set(s,e),o.debug(`[ToolRegistry] Registered tool: ${t}`)}}getTool(e){return this.tools.get(e.toLowerCase())}async executeTool(e,t,s,r){let n=this.getTool(e);if(!n)throw new Error(`Unknown tool: ${e}`);return await n.execute(t,e,s,r)}getAllToolNames(){return Array.from(this.tools.keys())}}});var zt={};te(zt,{ToolDisplay:()=>B});import L from"chalk";var B,fe=F(()=>{"use strict";B=class c{static customUIMode=!1;static enableCustomUI(){c.customUIMode=!0}static disableCustomUI(){c.customUIMode=!1}static start(e,t,s){if(c.customUIMode)return;let r=this.getToolPrefix(e);if(console.log(L.cyan(`
4
+ ${r} ${L.bold(e)}`)),t&&console.log(L.gray(` ${t}`)),s){let n=s.length>120?s.substring(0,120)+L.gray("..."):s;console.log(L.white(` ${n}`))}}static getToolPrefix(e){let t=e.toLowerCase();return t.includes("bash")||t.includes("command")?"\u25B8":t.includes("write")?"\u2192":t.includes("edit")?"\u270E":t.includes("read")?"\u25C6":t.includes("search")||t.includes("grep")?"\u2315":"\u2022"}static result(e){if(c.customUIMode)return;let{toolName:t,output:s,success:r,executionTime:n,truncateLines:i=50}=e,a=s||"";s&&(t.toLowerCase().includes("edit")?a=this.formatEditOutput(s,i):t.toLowerCase().includes("write")?a=this.formatWriteOutput(s,i):t.toLowerCase().includes("bash")||t.toLowerCase().includes("command")?a=this.formatBashOutput(s,i):a=this.formatGenericOutput(s,i)),a&&a.trim()&&console.log(a);let l=r?L.green("\u2713"):L.red("\u2717"),u=r?L.green("SUCCESS"):L.red("FAILED"),g=n?L.gray(` (${n}ms)`):"";console.log(`${l} ${u}${g}
5
+ `)}static formatEditOutput(e,t){if(e.includes("- ")&&e.includes("+ ")){let a=e.split(`
6
+ `),u=a.slice(0,20).map(g=>L.gray(" ")+g).join(`
7
+ `);return a.length>20&&(u+=`
8
+ `+L.gray(` ... (${a.length-20} more lines)`)),u}let s=e.split(`
9
+ `),r=e.match(/(?:File path|Path|Editing):\s*(.+?)(?:\n|$)/i),n="";r&&(n+=L.gray(" ")+L.dim(r[1])+`
10
+ `);let i=s.filter(a=>a.toLowerCase().includes("replaced")||a.includes("\u2192")||a.includes("->"));return i.length>0?(n+=i.slice(0,10).map(a=>L.gray(" ")+L.dim(a)).join(`
11
+ `),i.length>10&&(n+=`
12
+ `+L.gray(` ... (${i.length-10} more changes)`)),n):this.truncateOutput(e,Math.min(15,t))}static formatWriteOutput(e,t){return this.truncateOutput(e,Math.min(15,t))}static formatBashOutput(e,t){return this.truncateOutput(e,Math.min(30,t))}static formatGenericOutput(e,t){return this.truncateOutput(e,Math.min(20,t))}static truncateOutput(e,t){let s=e.split(`
13
+ `).filter(i=>i.trim());if(s.length===0)return"";if(s.length<=t)return s.map(i=>L.gray(" ")+L.dim(i)).join(`
14
+ `);let n=s.slice(0,t).map(i=>L.gray(" ")+L.dim(i)).join(`
15
+ `);return n+=`
16
+ `+L.gray(` ... (${s.length-t} more lines)`),n}static error(e,t){c.customUIMode||(console.log(`
17
+ ${L.red("\u2717")} ${L.red.bold(e)} ${L.red("ERROR")}`),console.log(L.gray(" ")+L.white(t)),console.log(""))}}});var Ge,jt=F(()=>{"use strict";U();fe();Ge=class{toolNames=["read","Read"];async execute(e,t,s,r){let n=s.file_path||s.path,i=s.offset,a=s.limit;if(!n)throw new Error("Missing file_path or path argument");o.debug(`[ReadFileTool] Reading file: ${n}${i!==void 0?`, offset: ${i}`:""}${a!==void 0?`, limit: ${a}`:""}`);let l=Date.now();B.start("Read",s.description,n);try{let u=await import("fs/promises");try{await u.access(n)}catch{return[{type:"text",text:`Error: File does not exist at path: ${n}`}]}let g=await u.stat(n);if(g.isDirectory())return[{type:"text",text:`Error: Path is a directory, not a file: ${n}`}];let h=await u.readFile(n,"utf-8"),m=h.length,w=h.split(`
18
+ `),S=w.length,p=Math.max(i??0,0),v=87500;if(m>v&&i===void 0&&a===void 0){let E=g.size/1024,_=E/1024,N=_>=1?`${_.toFixed(2)} MB`:`${E.toFixed(2)} KB`;return[{type:"text",text:`Error: File is too large to read completely.
19
+
20
+ File Information:
21
+ - Path: ${n}
22
+ - Size: ${N} (${m} characters)
23
+ - Total Lines: ${S}
24
+ - Character Limit: ${v.toLocaleString()}
25
+
26
+ Suggested Solutions:
27
+ 1. Read specific lines using offset and limit:
28
+ Read(path: "${n}", offset: 0, limit: 2000)
29
+
30
+ 2. Search for specific content:
31
+ Grep(pattern: "your_search_term", path: "${n}")
32
+
33
+ 3. Read in chunks:
34
+ - Lines 0-2000: Read(path: "${n}", offset: 0, limit: 2000)
35
+ - Lines 2000-4000: Read(path: "${n}", offset: 2000, limit: 2000)
36
+ - And so on...
37
+
38
+ The file has ${S.toLocaleString()} total lines. You can read approximately 2000 lines at a time safely.`}]}if(S===0||h.length===0)return[{type:"text",text:"File is empty (0 lines)"}];if(p>=S)return[{type:"text",text:`Error: Offset ${p} is beyond file length. File has ${S} total lines. Try a smaller offset (0 to ${S-1}).`}];let f=a!==void 0?Math.min(p+a,S):S,I=w.slice(p,f),P=I.map((E,_)=>`${(p+_+1).toString().padStart(6," ")} ${E}`).join(`
39
+ `),D=P;if(i!==void 0||a!==void 0){let E=`
40
+
41
+ [Read ${I.length} lines (${p+1}-${f}) of ${S} total lines]`;D=P+E}let C=Date.now()-l;return B.result({toolName:"Read",filePath:n,output:D,success:!0,executionTime:C}),[{type:"text",text:D}]}catch(u){o.debug(`[ReadFileTool] Failed to read file: ${u.message}`);let g;u.code==="ENOENT"?g=`Error: File does not exist at path: ${n}`:u.code==="EACCES"?g=`Error: Permission denied. Cannot read file: ${n}`:u.code==="EISDIR"?g=`Error: Path is a directory, not a file: ${n}`:g=`Error reading file: ${u.message}`;let h=Date.now()-l;return B.result({toolName:"Read",filePath:n,output:g,success:!1,executionTime:h}),[{type:"text",text:g}]}}}});import vt from"fs/promises";import Ks from"form-data";import bt from"axios";import St from"path";var qe,Qt=F(()=>{"use strict";U();fe();qe=class{toolNames=["read_special_file","ReadSpecialFile"];baseEndpoint="https://snowx.ai/md";maxPollAttempts=60;pollInterval=2e3;supportedExtensions=["pdf","docx","doc","xlsx","xls","pptx","ppt","mp3","mp4","wav","html","htm"];async execute(e,t,s,r){let n=s.path;if(!n)throw new Error("Missing path argument");o.debug(`[ReadSpecialFileTool] Converting file: ${n}`);let i=Date.now();B.start("ReadSpecialFile",s.description,n);try{try{await vt.access(n)}catch{return[{type:"text",text:`Error: File does not exist at path: ${n}`}]}let a=St.extname(n).substring(1).toLowerCase();if(!this.supportedExtensions.includes(a)){let P=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), and web files (html, htm). For plain text files, use the run_command tool with 'cat' instead.
42
+
43
+ Supported file types: ${P}`}]}let l=await vt.stat(n),u=St.basename(n);o.debug(`[ReadSpecialFileTool] Converting ${a.toUpperCase()} file: ${u} (${l.size} bytes)`);let g=await this.uploadToBatchAPI(n,u);o.debug(`[ReadSpecialFileTool] Uploaded successfully, request_id: ${g}`);let h=await this.pollBatchStatus(g);o.debug("[ReadSpecialFileTool] Conversion completed");let m=h.files[0];if(!m||m.status==="failed"){let P=m?.error||"Unknown conversion error";return[{type:"text",text:`Error converting ${a.toUpperCase()} file: ${P}`}]}let w=await this.fetchFileContent(m.file_id);if(!w.markdown_content)return[{type:"text",text:"Error: No markdown content returned from conversion service"}];let S=l.size/1024,p=S/1024,v=p>=1?`${p.toFixed(2)} MB`:`${S.toFixed(2)} KB`,f=`# File: ${u}
44
+ **Type:** ${a.toUpperCase()}
45
+ **Size:** ${v}
46
+ **Conversion:** \u2705 Successful
47
+
48
+ ---
49
+
50
+ ${w.markdown_content}`,I=Date.now()-i;return B.result({toolName:"ReadSpecialFile",filePath:n,output:`Successfully converted ${u} (${v})`,success:!0,executionTime:I}),[{type:"text",text:f}]}catch(a){o.debug(`[ReadSpecialFileTool] Failed to convert file: ${a.message}`);let l=`Error converting file: ${a.message}
51
+
52
+ This could be due to:
53
+ \u2022 File corruption or invalid format
54
+ \u2022 Network connectivity issues
55
+ \u2022 Unsupported document structure
56
+ \u2022 File is password-protected or encrypted
57
+
58
+ For plain text files (.txt, .json, .py, etc.), use the run_command tool with 'cat' instead.`,u=Date.now()-i;return B.result({toolName:"ReadSpecialFile",filePath:n,output:l,success:!1,executionTime:u}),[{type:"text",text:l}]}}async uploadToBatchAPI(e,t){let s=await vt.readFile(e),r=St.extname(t).substring(1).toLowerCase(),n=new Ks;n.append("files",s,{filename:t,contentType:this.getMimeType(r)});try{let i=await bt.post(`${this.baseEndpoint}/convert-batch`,n,{headers:n.getHeaders(),timeout:3e4});if(i.status!==202)throw new Error(`Upload failed with HTTP ${i.status}`);return i.data.request_id}catch(i){throw i.response?new Error(`Upload failed (HTTP ${i.response.status}): ${JSON.stringify(i.response.data)}`):new Error(`Upload failed: ${i.message}`)}}async pollBatchStatus(e){for(let t=1;t<=this.maxPollAttempts;t++)try{let r=(await bt.get(`${this.baseEndpoint}/batch/${e}`,{timeout:1e4})).data;if(o.debug(`[ReadSpecialFileTool] Poll ${t} - Status: ${r.files[0]?.status}, Progress: ${r.completed}/${r.total_files}`),r.completed+r.failed>=r.total_files)return r;await this.sleep(this.pollInterval)}catch(s){throw s.response?.status===404?new Error("Batch request not found or expired"):new Error(`Status check failed: ${s.message}`)}throw new Error(`Conversion timeout after ${this.maxPollAttempts*this.pollInterval/1e3} seconds`)}async fetchFileContent(e){try{let t=await bt.get(`${this.baseEndpoint}/files/${e}`,{timeout:1e4});if(t.data.status==="failed")throw new Error(t.data.error||"Unknown conversion error");return t.data}catch(t){throw t.response?.status===404?new Error("File not found or expired"):new Error(`Failed to fetch content: ${t.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 Xe,Kt=F(()=>{"use strict";U();fe();Xe=class{toolNames=["write","Write","write_file"];async execute(e,t,s,r){let n=s.file_path,i=s.content,a=s.edits;if(!n)throw new Error("Missing file_path argument");let l=Date.now();return B.start("Write",s.description,n),i!=null?await this.executeSimpleWrite(n,i,l):await this.executeEditsMode(n,a,l)}async executeSimpleWrite(e,t,s){o.debug(`[WriteFileTool] Writing file with content: ${e}`);try{let r=await import("fs/promises"),i=(await import("path")).dirname(e);await r.mkdir(i,{recursive:!0}),await r.writeFile(e,t,"utf-8");let a=t.split(`
59
+ `),l="";for(let h=0;h<Math.min(a.length,8);h++)l+=`+ ${a[h]}
60
+ `;a.length>8&&(l+=`+ ...
61
+
62
+ (${a.length-8} more lines)`);let u=l.trim();o.debug(`[WriteFileTool] Successfully wrote ${t.length} characters`);let g=Date.now()-s;return B.result({toolName:"Write",filePath:e,output:u,success:!0,executionTime:g}),[{type:"text",text:u}]}catch(r){o.debug(`[WriteFileTool] Failed to write file: ${r.message}`);let n=`Error writing file: ${r.message}`,i=Date.now()-s;return B.result({toolName:"Write",filePath:e,output:n,success:!1,executionTime:i}),[{type:"text",text:n}]}}async executeEditsMode(e,t,s){if(!t||!Array.isArray(t)||t.length===0)throw new Error("Missing content or edits array");if(t.length>50)throw new Error("Too many edit operations. Maximum 50 edits allowed per operation.");o.debug(`[WriteFileTool] Writing file: ${e} with ${t.length} edits`);try{let r=await import("fs/promises"),n=await import("path");if(!e||typeof e!="string")throw new Error("Invalid file_path parameter");if(e.startsWith("~/"))throw new Error(`Home directory shortcut not allowed ('${e}'). Use full absolute path instead.`);if(!e.startsWith("/")&&!e.includes(":\\"))throw new Error(`File path appears to be relative ('${e}'). Use full absolute path starting from root.`);for(let w=0;w<t.length;w++){let S=t[w];if(!S||typeof S!="object")throw new Error(`Edit operation ${w+1} must be an object with 'search' and 'replace' fields`);if(!S.hasOwnProperty("search")||typeof S.search!="string")throw new Error(`Edit operation ${w+1} missing required 'search' field (must be string)`);if(!S.hasOwnProperty("replace")||typeof S.replace!="string")throw new Error(`Edit operation ${w+1} missing required 'replace' field (must be string)`)}let i=t[0].search==="",a;if(i)if(o.debug("[WriteFileTool] Creating new file"),a="",t.length===1&&t[0].search===""){a=t[0].replace;let w=n.dirname(e);await r.mkdir(w,{recursive:!0}),await r.writeFile(e,a,"utf-8");let S=a.split(`
63
+ `),p="";for(let v=0;v<Math.min(S.length,8);v++)p+=`+ ${S[v]}
64
+ `;return S.length>8&&(p+=`+ ...
65
+
66
+ (${S.length-8} more lines)`),o.debug(`[WriteFileTool] Created new file with ${a.length} characters`),[{type:"text",text:p.trim()}]}else throw new Error("For new files, only one edit with empty search string is allowed");else{o.debug("[WriteFileTool] Reading existing file");try{a=await r.readFile(e,"utf-8"),o.debug(`[WriteFileTool] Read ${a.length} characters from existing file`)}catch(w){throw w.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: ${w.message}`)}}let l=0,u=a,g=[];for(let w=0;w<t.length;w++){let S=t[w];if(o.debug(`[WriteFileTool] Applying edit ${w+1}/${t.length}`),S.search==="")if(i){g.push({index:w+1,success:!0,message:"Skipped (empty search string for new file)",replacementCount:0});continue}else{o.debug("[WriteFileTool] Rewriting entire existing file"),u=S.replace,g.push({index:w+1,success:!0,message:"Successfully rewrote entire file",replacementCount:1}),l++;continue}let p=u.indexOf(S.search);if(p!==-1)u=u.substring(0,p)+S.replace+u.substring(p+S.search.length),o.debug("[WriteFileTool] Replaced first occurrence"),g.push({index:w+1,success:!0,message:"Successfully replaced first occurrence",replacementCount:1}),l++;else{let v=`Search string not found: '${S.search}'`;return g.push({index:w+1,success:!1,message:v,replacementCount:0}),[{type:"text",text:`Error: Search string not found in edit ${w+1}: '${S.search}'\\n\\nEdit Summary:\\n- Total edits: ${g.length}\\n- Successful: ${g.filter(I=>I.success).length}\\n- Failed: ${g.filter(I=>!I.success).length}\\n\\nIndividual Edit Results:\\n`+g.map(I=>`${I.success?"\u2705":"\u274C"} Edit ${I.index}: ${I.message}`).join("\\n")}]}}await r.writeFile(e,u,"utf-8"),o.debug(`[WriteFileTool] Successfully wrote ${u.length} characters to file`);let h=u.split(`
67
+ `),m="";for(let w=0;w<Math.min(h.length,8);w++)m+=`+ ${h[w]}
68
+ `;return h.length>8&&(m+=`+ ...
69
+
70
+ (${h.length-8} more lines)`),[{type:"text",text:m.trim()}]}catch(r){return o.debug(`[WriteFileTool] Failed to write file: ${r.message}`),[{type:"text",text:`Error writing file: ${r.message}`}]}}}});var He,Jt=F(()=>{"use strict";U();fe();He=class{toolNames=["edit","Edit"];async execute(e,t,s,r){let n=s.file_path,i=s.old_string,a=s.new_string,l=s.replace_all===!0;if(!n)throw new Error("Missing file_path argument");if(i==null)throw new Error("Missing old_string argument");if(a==null)throw new Error("Missing new_string argument");o.debug(`[EditFileTool] Editing file: ${n}`);let u=Date.now();B.start("Edit",s.description,n);try{let g=await import("fs/promises"),h=await g.readFile(n,"utf-8"),m,w=0;if(l)for(m=h;m.includes(i);)m=m.replace(i,a),w++;else h.includes(i)?(m=h.replace(i,a),w=1):m=h;if(w===0){let I=`No matches found for the specified old_string in file: ${n}`,P=Date.now()-u;return B.result({toolName:"Edit",filePath:n,output:I,success:!1,executionTime:P}),[{type:"text",text:I}]}await g.writeFile(n,m,"utf-8");let S=`Successfully edited file: Replaced ${w} occurrence(s)`;o.debug(`[EditFileTool] ${S}`);let p=Date.now()-u,v=(await import("chalk")).default,f=`${v.red("- "+i.split(`
71
+ `).slice(0,5).join(`
72
+ - `))}
73
+ ${v.green("+ "+a.split(`
74
+ `).slice(0,5).join(`
75
+ + `))}
76
+
77
+ Replaced ${w} occurrence(s)`;return B.result({toolName:"Edit",filePath:n,output:f,success:!0,executionTime:p}),[{type:"text",text:S}]}catch(g){o.debug(`[EditFileTool] Failed to edit file: ${g.message}`);let h=`Error editing file: ${g.message}`,m=Date.now()-u;return B.result({toolName:"Edit",filePath:n,output:h,success:!1,executionTime:m}),[{type:"text",text:h}]}}}});var Ve,Yt=F(()=>{"use strict";U();Ve=class{toolNames=["upload_file"];async execute(e,t,s,r){let n=s.file_path;if(!n)throw new Error("Missing file_path argument");return o.debug(`[UploadFileTool] Upload file not implemented for CLI: ${n}`),[{type:"text",text:`Upload file functionality not available in CLI version: ${n}`}]}}});var Zt=F(()=>{"use strict"});function Re(c){let t=c.trim().toLowerCase().split(/\s+/)[0]||"",s=new Set(["echo","pwd","date","whoami","id","hostname","uname","which","type","true","false","yes","printf"]),r=new Set(["ls","cat","head","tail","wc","grep","awk","sed","sort","uniq","cut","tr","basename","dirname","stat","file","du","df","free","uptime","ps"]),n=new Set(["make","cmake","npm","yarn","pip","cargo","mvn","gradle","docker","git","rsync","scp","ssh","curl","wget","find","locate","tar","zip","unzip","brew","apt","yum"]);return s.has(t)||r.has(t)&&c.length<100?Te.fast:n.has(t)?Te.extended:c.length<20?Te.fast:c.includes("|")||c.includes(">")||c.includes("<")?c.length<200?Te.default:Te.extended:Te.default}var Te,wt=F(()=>{"use strict";Zt();Te={fast:{activityTimeout:2e3,maxTimeout:5e3,initialTimeout:1e3},default:{activityTimeout:1e4,maxTimeout:6e4,initialTimeout:5e3},extended:{activityTimeout:3e4,maxTimeout:3e5,initialTimeout:1e4}}});import{spawn as Js}from"child_process";var Pe,es=F(()=>{"use strict";wt();Pe=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async executeCommand(e,t,s,r,n="new",i){let a=i||Re(e);return this.executeInNewProcess(e,a)}async executeInNewProcess(e,t){return new Promise(s=>{let r=Js("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"]}),n="",i="",a=!1,l=setTimeout(()=>{r.killed||(a=!0,console.log("\u23F0 Timeout reached, sending SIGTERM..."),r.kill("SIGTERM"),setTimeout(()=>{r.killed||(console.log("\u274C Process didn't respond to SIGTERM, sending SIGKILL..."),r.kill("SIGKILL"))},5e3))},t.maxTimeout);r.stdout.on("data",u=>{n+=u.toString()}),r.stderr.on("data",u=>{i+=u.toString()}),r.on("close",u=>{clearTimeout(l);let g=(n+i).trim(),h=3e4;if(g.length>h){let m=g.substring(0,h),S=m.split(`
78
+ `).length,p=g.length;g=m+`
79
+
80
+ [Output truncated at `+h+` characters]
81
+ [Showing first `+S+` lines of output]
82
+ [Total output was `+p+" characters]",console.log("\u26A0\uFE0F Output truncated: "+p+" chars -> "+h+" chars")}a?(console.log("\u23F0 Command timed out"),s({output:g+`
83
+
84
+ \u274C Command timed out after `+t.maxTimeout+" milliseconds",exitCode:-15,isSuccess:!1})):s({output:g,exitCode:u||0,isSuccess:(u||0)===0})}),r.on("error",u=>{clearTimeout(l),s({output:"Process execution failed: "+u.message+`
85
+ Command: `+e,exitCode:-1,isSuccess:!1})})})}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}`:t="Unknown error"}return`Exit code: ${e} (${t})`}static parseSessionMode(e){if(e.toLowerCase()==="new")return"new";throw new Error(`Invalid session mode: ${e}. Only 'new' mode is supported`)}}});var yt={};te(yt,{ToolCallingService:()=>Oe});import{EventEmitter as Ys}from"events";import ts from"axios";import{exec as Zs,spawn as ss}from"child_process";import{promisify as en}from"util";import z from"fs/promises";import re from"fs";import Ce from"path";import tn from"os";var xi,Oe,ze=F(()=>{"use strict";es();wt();xi=en(Zs),Oe=class _ToolCallingService extends Ys{static instance;tools=new Map;executionHistory=[];maxResponseCharacters=87500;shellSessionManager=Pe.getInstance();currentUserId="orion-cli-user";fileStateCache=new Map;backgroundProcesses=new Map;backgroundProcessCounter=0;constructor(){super(),this.initializeDefaultTools()}static getInstance(){return _ToolCallingService.instance||(_ToolCallingService.instance=new _ToolCallingService),_ToolCallingService.instance}initializeDefaultTools(){this.registerTool({name:"web_search",description:"Search the web for information on a given topic",parameters:{type:"object",properties:{query:{type:"string",description:"The search query"},num_results:{type:"number",description:"Number of results to return (default: 5)",default:5}},required:["query"]},handler:this.webSearch.bind(this),category:"web",enabled:!0}),this.registerTool({name:"read_file",description:"Read the contents of a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to read"}},required:["file_path"]},handler:this.readFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"write_file",description:"Write content to a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: write or append",enum:["write","append"],default:"write"}},required:["file_path","content"]},handler:this.writeFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"list_directory",description:"List the contents of a directory",parameters:{type:"object",properties:{directory_path:{type:"string",description:"Path to the directory to list"},include_hidden:{type:"boolean",description:"Include hidden files and directories",default:!1}},required:["directory_path"]},handler:this.listDirectory.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Bash",description:"Execute shell commands with support for background execution, timeouts, and output truncation",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},description:{type:"string",description:"Human-readable description of what the command does"},timeout:{type:"number",description:"Timeout in milliseconds (default: auto-detected based on command)"},run_in_background:{type:"boolean",description:"Run command in background and return immediately",default:!1}},required:["command"]},handler:this.bashCommand.bind(this),category:"system",enabled:!0}),this.registerTool({name:"execute_command",description:`Execute shell commands with persistent session support and interactive prompt handling. Supports both single-shot and persistent execution modes for multi-step workflows.
86
+
87
+ \u{1F527} SESSION MODE SELECTION (REQUIRED):
88
+ \u2022 Use session: "existing" for workflows that need persistent state:
89
+ - Multi-step operations (cd to directory, then run commands)
90
+ - Setting environment variables that subsequent commands need
91
+ - Authentication flows (sudo password caching)
92
+ - Package installation and configuration
93
+ - Development workflows (build, test, deploy sequences)
94
+ \u2022 Use session: "new" for isolated operations:
95
+ - One-off information gathering (ls, ps, df)
96
+ - Independent commands that don't affect other operations
97
+ - When you want to avoid contaminating the persistent session
98
+
99
+ \u26A1 INTERACTIVE PROMPT SUPPORT:
100
+ \u2022 Automatic detection of y/n, password, sudo, and confirmation prompts
101
+ \u2022 Smart analysis of prompt type and context for intelligent responses
102
+ \u2022 Use provide_input tool to respond to detected interactive prompts
103
+ \u2022 Seamless handling of complex authentication and confirmation flows`,parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},session:{type:"string",enum:["new","existing"],description:'Session mode: "new" for isolated execution, "existing" for persistent shell session'},timeout:{type:"number",description:"Timeout in milliseconds (default: 300000)",default:3e5}},required:["command","session"]},handler:this.executeCommandWithSession.bind(this),category:"system",enabled:!0}),this.registerTool({name:"provide_input",description:`Provide input to an interactive prompt that was detected during shell command execution. This tool is used in conjunction with execute_command when a command pauses for user input (y/n, passwords, confirmations, etc.).
104
+
105
+ \u{1F514} INTERACTIVE PROMPT HANDLING:
106
+ \u2022 Automatic Detection: When execute_command encounters interactive prompts, it pauses execution
107
+ \u2022 Smart Analysis: System analyzes prompt type and context for intelligent responses
108
+ \u2022 Decision Support: LLM receives prompt details to make appropriate decisions
109
+ \u2022 Input Provision: This tool sends the chosen response back to the waiting command
110
+ \u2022 Continuation: Command execution resumes after input is provided
111
+
112
+ \u{1F3AF} TYPICAL WORKFLOW:
113
+ 1. User runs command with execute_command (session: "existing")
114
+ 2. Command encounters interactive prompt and pauses
115
+ 3. System detects prompt and analyzes context
116
+ 4. LLM receives prompt details and makes decision
117
+ 5. LLM uses provide_input to send appropriate response
118
+ 6. Command execution continues with provided input
119
+ 7. Normal command completion and result return`,parameters:{type:"object",properties:{input:{type:"string",description:'The input to provide to the interactive prompt. Should be appropriate for the prompt type (e.g., "y", "n", password, text, etc.)'}},required:["input"]},handler:this.provideInput.bind(this),category:"system",enabled:!0}),this.registerTool({name:"calculate",description:"Perform mathematical calculations",parameters:{type:"object",properties:{expression:{type:"string",description:"Mathematical expression to evaluate"}},required:["expression"]},handler:this.calculate.bind(this),category:"computation",enabled:!0}),this.registerTool({name:"http_request",description:"Make an HTTP request to a URL",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to request"},method:{type:"string",description:"HTTP method",enum:["GET","POST","PUT","DELETE"],default:"GET"},headers:{type:"object",description:"HTTP headers"},body:{type:"string",description:"Request body for POST/PUT requests"}},required:["url"]},handler:this.httpRequest.bind(this),category:"web",enabled:!0}),this.registerTool({name:"get_current_time",description:"Get the current date and time",parameters:{type:"object",properties:{format:{type:"string",description:"Date format (iso, local, unix)",enum:["iso","local","unix"],default:"iso"},timezone:{type:"string",description:"Timezone (e.g., America/New_York, UTC)",default:"local"}}},handler:this.getCurrentTime.bind(this),category:"system",enabled:!0}),this.registerTool({name:"Edit",description:"Performs exact string replacements in files with comprehensive validation",parameters:{type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]},handler:this.editFile.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Grep",description:"A powerful search tool built on ripgrep for searching file contents",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "**/*.tsx")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content shows matching lines, files_with_matches shows file paths (default), count shows match counts",default:"files_with_matches"},case_insensitive:{type:"boolean",description:"Case insensitive search",default:!1}},required:["pattern"]},handler:this.grepFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"Glob",description:"Fast file pattern matching tool that works with any codebase size",parameters:{type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:"The directory to search in. Defaults to current working directory."}},required:["pattern"]},handler:this.globFiles.bind(this),category:"file",enabled:!0}),this.registerTool({name:"NotebookEdit",description:"Edit Jupyter notebook (.ipynb) cells with cell-level precision",parameters:{type:"object",properties:{notebook_path:{type:"string",description:"The absolute path to the Jupyter notebook file to edit"},cell_id:{type:"string",description:"The ID of the cell to edit"},new_source:{type:"string",description:"The new source for the cell"},cell_type:{type:"string",enum:["code","markdown"],description:"The type of the cell (code or markdown)"},edit_mode:{type:"string",enum:["replace","insert","delete"],description:"The type of edit to make (replace, insert, delete). Defaults to replace.",default:"replace"}},required:["notebook_path","new_source"]},handler:this.editNotebook.bind(this),category:"file",enabled:!0})}registerTool(c){this.tools.set(c.name,c)}unregisterTool(c){let e=this.tools.delete(c);return e}async executeTool(c){let e=Date.now(),t=c.function.name;this.emit("tool_execution_start",{toolName:t,toolCall:c});let s={};try{s=JSON.parse(c.function.arguments)}catch(n){throw new Error(`Invalid arguments for tool '${t}': ${n}`)}let{ToolDisplay:r}=await Promise.resolve().then(()=>(fe(),zt));r.start(t,s.description,s.command||s.file_path);try{let n=this.tools.get(t);if(!n)throw new Error(`Tool '${t}' not found`);if(!n.enabled)throw new Error(`Tool '${t}' is disabled`);let i=await n.handler(s),a=Date.now()-e,l=this.handleLargeResponse(i,t);return this.executionHistory.push({toolName:t,args:s,result:l,timestamp:new Date,executionTime:a}),this.executionHistory.length>100&&(this.executionHistory=this.executionHistory.slice(-100)),this.emit("tool_execution_complete",{toolName:t,result:l,executionTime:a}),r.result({toolName:t,command:s.command,filePath:s.file_path,description:s.description,output:this.extractOutputForDisplay(l),success:l.success,executionTime:a}),await this.captureFrontendToolResult(t,l),l}catch(n){let i=Date.now()-e,a={success:!1,error:n.message};return this.emit("tool_execution_error",{toolName:t,error:n,executionTime:i}),r.error(t,n.message),await this.captureFrontendToolResult(t,a),a}}extractOutputForDisplay(c){return c.success?c.result?typeof c.result=="string"?c.result:typeof c.result=="object"&&"stdout"in c.result?c.result.stdout||c.result.stderr||"":typeof c.result=="object"&&"content"in c.result?c.result.content||"":JSON.stringify(c.result,null,2):"":c.error||"Unknown error"}async captureFrontendToolResult(c,e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ae(),Ee)),s=t.getInstance(),r=this.extractOutputForDisplay(e);s.captureFrontendToolResult(c,r,e.success)}async webSearch(c){try{let e=`https://api.duckduckgo.com/?q=${encodeURIComponent(c.query)}&format=json&no_html=1&skip_disambig=1`,s=(await ts.get(e,{timeout:1e4,headers:{"User-Agent":"Orion-CLI/1.0"}})).data,r=[];if(s.AbstractText&&r.push({title:s.Heading||"Instant Answer",content:s.AbstractText,url:s.AbstractURL||"",type:"instant_answer"}),s.RelatedTopics&&s.RelatedTopics.length>0)for(let n of s.RelatedTopics.slice(0,c.num_results||5))n.Text&&r.push({title:n.Text.split(" - ")[0]||"Related Topic",content:n.Text,url:n.FirstURL||"",type:"related_topic"});return{success:!0,result:{query:c.query,results:r,total_results:r.length}}}catch(e){return{success:!1,error:`Web search failed: ${e.message}`}}}async readFile(c){try{let e=await z.readFile(c.file_path,"utf-8");return this.cacheFileState(c.file_path,e),{success:!0,result:{file_path:c.file_path,content:e,size:e.length}}}catch(e){return{success:!1,error:`Failed to read file: ${e.message}`}}}async writeFile(c){try{let{file_path:e,content:t,mode:s="write"}=c;if(e.endsWith(".ipynb")&&re.existsSync(e)){let n=await z.readFile(e,"utf-8"),i=JSON.parse(n);if(i.cells.length>0&&i.cells[0].id){let a=i.cells.findIndex(l=>l.id===i.cells[0].id);if(a!==-1)return i.cells[a].source=t,await z.writeFile(e,JSON.stringify(i,null,2),"utf-8"),{success:!0,result:{file_path:e,bytes_written:t.length,message:"Notebook cell written successfully"}}}}re.existsSync(e)&&s!=="append"&&await this.validateFileNotModified(e);let r=Ce.dirname(e);return await z.mkdir(r,{recursive:!0}),s==="append"?await z.appendFile(e,t):await z.writeFile(e,t),this.cacheFileState(e,t),{success:!0,result:{file_path:e,bytes_written:t.length,mode:s}}}catch(e){return{success:!1,error:`Failed to write file: ${e.message}`}}}async listDirectory(c){try{let e=await z.readdir(c.directory_path,{withFileTypes:!0}),t=[];for(let s of e){if(!c.include_hidden&&s.name.startsWith("."))continue;let r=await z.stat(Ce.join(c.directory_path,s.name));t.push({name:s.name,type:s.isDirectory()?"directory":"file",size:r.size,modified:r.mtime.toISOString()})}return{success:!0,result:{directory_path:c.directory_path,entries:t,total_count:t.length}}}catch(e){return{success:!1,error:`Failed to list directory: ${e.message}`}}}async executeCommandWithSession(c){try{let e=Pe.parseSessionMode(c.session),t=Re(c.command),s={activityTimeout:c.timeout||t.activityTimeout,maxTimeout:c.timeout||t.maxTimeout,initialTimeout:t.initialTimeout},r=await this.shellSessionManager.executeCommand(c.command,`tool-${Date.now()}`,this.currentUserId,c.session||"new",e,s);return{success:r.isSuccess,result:{command:c.command,stdout:r.output,stderr:"",exit_code:r.exitCode}}}catch(e){return{success:!1,error:`Command execution failed: ${e.message}`,result:{command:c.command,stdout:"",stderr:e.message||"",exit_code:-1}}}}async provideInput(c){return{success:!1,error:'Interactive input is not supported. Only "new" session mode is available, which does not support persistent interactive sessions.',result:{message:"Interactive input not supported",requested_input:c.input}}}async calculate(args){try{let sanitized=args.expression.replace(/[^0-9+\-*/.() ]/g,"");if(sanitized!==args.expression)throw new Error("Invalid characters in expression");let result=eval(sanitized);return{success:!0,result:{expression:args.expression,result,type:typeof result}}}catch(c){return{success:!1,error:`Calculation failed: ${c.message}`}}}async httpRequest(c){try{let e=await ts({method:c.method||"GET",url:c.url,headers:c.headers,data:c.body,timeout:1e4,maxRedirects:5});return{success:!0,result:{url:c.url,status:e.status,headers:e.headers,data:typeof e.data=="string"?e.data.substring(0,1e4):e.data}}}catch(e){return{success:!1,error:`HTTP request failed: ${e.message}`,result:{url:c.url,status:e.response?.status||0,error_details:e.response?.data}}}}async getCurrentTime(c){try{let e=new Date,t={};switch(c.format){case"unix":t.timestamp=Math.floor(e.getTime()/1e3);break;case"local":t.datetime=e.toLocaleString();break;case"iso":default:t.datetime=e.toISOString();break}return t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,t.format=c.format||"iso",{success:!0,result:t}}catch(e){return{success:!1,error:`Failed to get current time: ${e.message}`}}}async bashCommand(c){try{let{command:e,timeout:t,run_in_background:s=!1}=c;if(s){this.backgroundProcessCounter++;let i=`bg-${this.backgroundProcessCounter}`,a=ss("/bin/bash",["-c",e],{env:process.env,stdio:["ignore","pipe","pipe"],detached:!0}),l={process:a,command:e,startTime:new Date,stdout:"",stderr:""};a.stdout.on("data",g=>{let h=g.toString();if(h){let m=this.backgroundProcesses.get(i);m&&(m.stdout+=h,this.backgroundProcesses.set(i,m))}}),a.stderr.on("data",g=>{let h=g.toString();if(h){let m=this.backgroundProcesses.get(i);m&&(m.stderr+=h,this.backgroundProcesses.set(i,m))}}),a.on("close",g=>{let h=this.backgroundProcesses.get(i);h&&(h.exitCode=g||0,this.backgroundProcesses.set(i,h),console.log(`\u2705 Background process ${i} finished with exit code: ${g}`))}),this.backgroundProcesses.set(i,l);let u=`Command started in background with ID: ${i}
120
+ PID: ${a.pid}
121
+ Command: ${e}
122
+
123
+ Note: The process will continue running in the background.
124
+ Output will be collected automatically.`;return console.log(`\u2705 Started background process ${i} (PID: ${a.pid})`),{success:!0,result:{process_id:i,pid:a.pid,message:u}}}let r=t?{activityTimeout:t,maxTimeout:t,initialTimeout:t}:Re(e),n=await this.shellSessionManager.executeCommand(e,`tool-${Date.now()}`,this.currentUserId,"new","new",r);return{success:n.isSuccess,result:{command:e,stdout:n.output,stderr:"",exit_code:n.exitCode}}}catch(e){return{success:!1,error:`Bash command failed: ${e.message}`}}}async editFile(c){try{let{file_path:e,old_string:t,new_string:s,replace_all:r=!1}=c;if(t===s)throw new Error("No changes to make: old_string and new_string are identical");if(e.endsWith(".ipynb")&&re.existsSync(e)){let a=await z.readFile(e,"utf-8"),l=JSON.parse(a);for(let u=0;u<l.cells.length;u++){let g=l.cells[u],h=Array.isArray(g.source)?g.source.join(""):g.source;if(h.includes(t)){let m=r?h.replaceAll(t,s):h.replace(t,s);return l.cells[u].source=m,await z.writeFile(e,JSON.stringify(l,null,2),"utf-8"),{success:!0,result:{file_path:e,replacements:r?h.split(t).length-1:1,message:"Notebook cell edited successfully"}}}}throw new Error("String not found in notebook. The old_string does not exist in any cell.")}await this.validateFileNotModified(e);let n=await z.readFile(e,"utf-8");if(!n.includes(t))throw new Error("String not found in file. Check for whitespace/indentation differences.");let i=r?n.replaceAll(t,s):n.replace(t,s);if(i===n)throw new Error("Edit failed: File content unchanged after replacement");return await z.writeFile(e,i,"utf-8"),this.cacheFileState(e,i),{success:!0,result:{file_path:e,replacements:r?n.split(t).length-1:1,message:"File edited successfully"}}}catch(e){return{success:!1,error:`Edit failed: ${e.message}`}}}async grepFiles(c){try{let{pattern:e,path:t=process.cwd(),glob:s,output_mode:r="files_with_matches",case_insensitive:n=!1}=c,i=[];return n&&i.push("-i"),r==="files_with_matches"?i.push("-l"):r==="count"&&i.push("-c"),s&&i.push("--glob",s),i.push(e,t),new Promise(a=>{let l=ss("rg",i,{stdio:["ignore","pipe","pipe"]}),u="",g="";l.stdout.on("data",h=>{u+=h.toString()}),l.stderr.on("data",h=>{g+=h.toString()}),l.on("close",h=>{if(h!==0&&h!==1){a({success:!1,error:`ripgrep failed: ${g||"Unknown error"}`});return}let m=u.trim().split(`
125
+ `).filter(S=>S),w=m.length;a({success:!0,result:{pattern:e,num_files:w,files:m,output:u.trim()}})}),l.on("error",h=>{a({success:!1,error:`Failed to execute ripgrep: ${h.message}. Make sure ripgrep is installed.`})})})}catch(e){return{success:!1,error:`Grep failed: ${e.message}`}}}async globFiles(c){try{let{pattern:e,path:t=process.cwd()}=c,r=(a=>{let l=a;return l=l.replace(/[.+^${}()|[\]\\]/g,"\\$&"),l=l.replace(/\*\*/g,"<DOUBLESTAR>"),l=l.replace(/\*/g,"[^/]*"),l=l.replace(/<DOUBLESTAR>/g,".*"),l=l.replace(/\?/g,"."),new RegExp(`^${l}$`)})(e),n=[],i=async a=>{try{let l=await z.readdir(a,{withFileTypes:!0});for(let u of l){if(u.name.startsWith("."))continue;let g=Ce.join(a,u.name),h=Ce.relative(t,g);u.isDirectory()?await i(g):(r.test(h)||r.test(u.name))&&n.push(g)}}catch{}};return await i(t),{success:!0,result:{pattern:e,num_files:n.length,files:n}}}catch(e){return{success:!1,error:`Glob failed: ${e.message}`}}}async editNotebook(c){try{let{notebook_path:e,cell_id:t,new_source:s,cell_type:r="code",edit_mode:n="replace"}=c;if(!re.existsSync(e))throw new Error(`Notebook file does not exist: ${e}`);if(!e.endsWith(".ipynb"))throw new Error("File must be a Jupyter notebook (.ipynb file)");let i=await z.readFile(e,"utf-8"),a=JSON.parse(i);switch(n){case"replace":{if(!t)throw new Error("cell_id is required for replace mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells[l].source=s;break}case"insert":{if(!r)throw new Error("cell_type is required for insert mode");let l={id:Math.random().toString(36).substring(2,15),cell_type:r,source:s,metadata:{},execution_count:r==="code"?null:void 0,outputs:r==="code"?[]:void 0};if(t){let u=a.cells.findIndex(g=>g.id===t);a.cells.splice(u+1,0,l)}else a.cells.unshift(l);break}case"delete":{if(!t)throw new Error("cell_id is required for delete mode");let l=a.cells.findIndex(u=>u.id===t);if(l===-1)throw new Error(`Cell with id ${t} not found`);a.cells.splice(l,1);break}default:throw new Error(`Invalid edit_mode: ${n}`)}return await z.writeFile(e,JSON.stringify(a,null,2),"utf-8"),{success:!0,result:{notebook_path:e,edit_mode:n,cell_id:t,message:"Notebook edited successfully"}}}catch(e){return{success:!1,error:`NotebookEdit failed: ${e.message}`}}}cacheFileState(c,e){try{let t=re.statSync(c);this.fileStateCache.set(c,{content:e,modificationDate:t.mtime,filePath:c})}catch{}}async validateFileNotModified(c){let e=this.fileStateCache.get(c);if(!e){if(re.existsSync(c)){let s=await z.readFile(c,"utf-8");this.cacheFileState(c,s)}return}if(re.statSync(c).mtime.getTime()!==e.modificationDate.getTime())throw new Error("File has been modified since last read. Read it again before editing.")}getAvailableTools(){let c=[];for(let[e,t]of this.tools.entries())t.enabled&&c.push({type:"function",function:{name:e,description:t.description,parameters:t.parameters}});return c}getToolsByCategory(c){return this.getAvailableTools().filter(e=>this.tools.get(e.function.name)?.category===c)}enableTool(c){let e=this.tools.get(c);return e?(e.enabled=!0,!0):!1}disableTool(c){let e=this.tools.get(c);return e?(e.enabled=!1,!0):!1}getExecutionHistory(c=10){return this.executionHistory.slice(-c)}getExecutionStats(){let c=this.executionHistory.length,e=this.executionHistory.filter(i=>i.result.success).length,t=c-e,s=c>0?this.executionHistory.reduce((i,a)=>i+a.executionTime,0)/c:0,r=new Map;this.executionHistory.forEach(i=>{r.set(i.toolName,(r.get(i.toolName)||0)+1)});let n=r.size>0?Array.from(r.entries()).reduce((i,a)=>a[1]>i[1]?a:i)[0]:null;return{total:c,successful:e,failed:t,averageTime:Math.round(s),mostUsed:n}}clearHistory(){this.executionHistory=[]}setUserId(c){this.currentUserId=c}getCurrentUserId(){return this.currentUserId}cleanupUserSession(c){console.log(`[ToolCalling] Session cleanup not needed for 'new' mode (session: ${c||"none"})`)}handleLargeResponse(c,e){if(!c.success||!c.result)return c;let t=typeof c.result=="string"?c.result:JSON.stringify(c.result);if(t.length>this.maxResponseCharacters){let s=this.createTempFile(t,e);return s?{success:!0,result:this.generatePreview(t,s)}:{success:!0,result:this.truncateOutput(t)}}return c}createTempFile(c,e){try{let t=tn.tmpdir(),s=Ce.join(t,"orion_tool_responses");re.existsSync(s)||re.mkdirSync(s,{recursive:!0});let r=Math.floor(Date.now()/1e3),n=Math.random().toString(36).substring(2,10),i=`${e}_${r}_${n}.txt`,a=Ce.join(s,i);return re.writeFileSync(a,c,"utf8"),a}catch{return null}}generatePreview(c,e){let t=c.substring(0,1e4),s=`\u{1F4C4} Response too large (${c.length} characters > 87,500 limit), saved to temporary file.
126
+
127
+ `;return s+=`\u{1F4C1} TEMP FILE PATH: ${e}
128
+ `,s+=`\u{1F50D} Use read_file, grep, cat, or other tools to access the full content.
129
+
130
+ `,s+=`\u{1F4DD} PREVIEW (first 10,000 characters):
131
+ `,s+=`${"\u2500".repeat(50)}
132
+ `,s+=t,c.length>1e4&&(s+=`
133
+ ${"\u2500".repeat(50)}`,s+=`
134
+ ... (${c.length-1e4} more characters available in temp file)`),s+=`
135
+
136
+ \u{1F4A1} To read full content: use tools like 'read_file' with path above`,s}truncateOutput(c){return c.length<=this.maxResponseCharacters?c:c.substring(0,this.maxResponseCharacters)+`
137
+
138
+ ... (truncated due to size limit)`}stopAllRunningTools(){}}});var je,ns=F(()=>{"use strict";U();je=class{toolNames=["bash","Bash","run_command"];async execute(e,t,s,r){let n=s.command,i=s.session||"new",a=s.description,l=s.timeout,u=s.run_in_background;if(!n)throw new Error("Missing command argument");if(n.trim().length===0)throw new Error("Command cannot be empty");if(i!=="new"&&i!=="existing")throw new Error(`Invalid session mode '${i}' - must be 'new' or 'existing'`);if(l!==void 0){if(l<=0)throw new Error(`Timeout must be positive. Received: ${l}ms`);if(l>6e5)throw new Error(`Timeout cannot exceed 600000ms (10 minutes). Received: ${l}ms`)}let g=l||12e4;o.debug(`[RunCommandTool] Executing bash command: ${n.substring(0,50)}${n.length>50?"...":""}`),a&&o.debug(`[RunCommandTool] Description: ${a}`),o.debug(`[RunCommandTool] Session: ${i}, Timeout: ${g}ms, Background: ${u||!1}`);try{let h=(await Promise.resolve().then(()=>(ze(),yt))).ToolCallingService.getInstance(),m={id:e,type:"function",function:{name:"execute_command",arguments:JSON.stringify({command:n,session:i,timeout:g})}},w=await h.executeTool(m),S="";if(w.success){let p=(w.result?.stdout||"").trim(),v=w.result?.exitCode??0;if(S=`Command: ${n}
139
+ `,S+=`Exit Code: ${v}
140
+
141
+ `,p.length>0){let f=p.split(`
142
+ `),I=f.slice(0,15);S+=I.join(`
143
+ `),f.length>15&&(S+=`
144
+
145
+ ... (showing first 15 of ${f.length} lines)`)}else S+="(no output)";return[{type:"text",text:S}]}else{let p=w.error||"Unknown error",v=w.result?.exitCode??1;return S=`Command: ${n}
146
+ `,S+=`Exit Code: ${v}
147
+
148
+ `,S+=`Error:
149
+ ${p}`,[{type:"text",text:S}]}}catch(h){return o.debug(`[RunCommandTool] Failed to execute bash command: ${h.message}`),[{type:"text",text:`Command: ${n}
150
+ Error: ${h.message}`}]}}ensureMeaningfulOutput(e,t,s){let r=(e||"").trim();return r.length===0?s?`\u2705 Command '${t}' executed successfully.
151
+
152
+ \u2139\uFE0F No output was produced, which may be expected for this operation. This typically means:
153
+ \u2022 The command completed without errors
154
+ \u2022 The operation doesn't produce console output (e.g., file operations, silent commands)
155
+ \u2022 The command ran but had nothing to report
156
+
157
+ If you expected output, the command may need different parameters or the operation may have failed silently.`:`\u274C Command '${t}' failed but no error message was provided.
158
+
159
+ \u2139\uFE0F This usually indicates:
160
+ \u2022 The command was terminated unexpectedly
161
+ \u2022 An error occurred without producing error output
162
+ \u2022 The operation encountered an unknown failure
163
+
164
+ Consider:
165
+ \u2022 Checking the command syntax and parameters
166
+ \u2022 Verifying file permissions and paths
167
+ \u2022 Running the command with verbose flags for more details`:r}}});var Qe,os=F(()=>{"use strict";U();Qe=class{toolNames=["grep","Grep"];async execute(e,t,s,r){let n=s.pattern,i=s.output_mode||"files_with_matches",a=s.path||process.cwd(),l=s.glob,u=s.type,g=s["-i"]===!0,h=s["-n"]===!0,m=s["-A"],w=s["-B"],S=s["-C"],p=s.multiline===!0,v=s.head_limit;if(!n)throw new Error("Missing pattern argument");if(n.trim().length===0)throw new Error("Pattern cannot be empty");o.debug(`[GrepTool] Grep search: pattern="${n}", path="${a}", output_mode="${i}"`);try{let{exec:f}=await import("child_process"),{promisify:I}=await import("util"),P=I(f),D="rg",C=!0;try{await P("which rg")}catch{o.debug("[GrepTool] ripgrep not found, falling back to grep"),D="grep -r",C=!1}if(C){switch(g&&(D+=" -i"),h&&(D+=" -n"),i){case"files_with_matches":D+=" -l";break;case"count":D+=" -c";break;case"content":default:break}S!==void 0?D+=` -C ${S}`:(m!==void 0&&(D+=` -A ${m}`),w!==void 0&&(D+=` -B ${w}`)),p&&(D+=" -U --multiline-dotall"),D+=` "${n.replace(/"/g,'\\"')}"`,l&&(D+=` --glob="${l}"`),u&&(D+=` --type=${u}`),D+=` "${a}"`}else{switch(g&&(D+=" -i"),h&&(D+=" -n"),i){case"files_with_matches":D+=" -l";break;case"count":D+=" -c";break}S!==void 0?D+=` -C ${S}`:(m!==void 0&&(D+=` -A ${m}`),w!==void 0&&(D+=` -B ${w}`)),D+=` "${n.replace(/"/g,'\\"')}"`,l&&(D+=` --include="${l}"`),D+=` "${a}"`}v!==void 0&&v>0&&(D+=` | head -n ${v}`),o.debug(`[GrepTool] Executing: ${D}`);let{stdout:E,stderr:_}=await P(D,{maxBuffer:10*1024*1024});if(!E&&!_)return[{type:"text",text:"No matches found"}];let N=E||_;if(i==="content"&&N){let k=`
168
+
169
+ [Found ${N.trim().split(`
170
+ `).length} matching line(s)]`;return[{type:"text",text:N+k}]}return[{type:"text",text:N}]}catch(f){return f.code===1?[{type:"text",text:"No matches found"}]:(o.debug(`[GrepTool] Grep failed: ${f.message}`),f.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 Ke,is=F(()=>{"use strict";U();Ke=class{toolNames=["glob","Glob"];async execute(e,t,s,r){let n=s.pattern,i=s.path||process.cwd();if(!n)throw new Error("Missing pattern argument");o.debug(`[GlobTool] Glob search: pattern="${n}", path="${i}"`);try{let{exec:a}=await import("child_process"),{promisify:l}=await import("util"),u=l(a),g=n.replace(/\*\*/g,"*"),h=process.platform==="win32"?`dir /s /b "${i}\\${g}"`:`find "${i}" -name "${g}" 2>/dev/null`,{stdout:m}=await u(h);if(!m||m.trim().length===0)return[{type:"text",text:"No files found matching pattern"}];let w=m.trim().split(`
171
+ `);return[{type:"text",text:`Found ${w.length} file(s):
172
+ ${w.join(`
173
+ `)}`}]}catch(a){return o.debug(`[GlobTool] Glob failed: ${a.message}`),[{type:"text",text:"No files found matching pattern"}]}}}});var Je,rs=F(()=>{"use strict";U();Je=class{toolNames=["open_url"];async execute(e,t,s,r){let n=s.url;if(!n)throw new Error("Missing url argument");o.debug(`[OpenUrlTool] Opening URL: ${n}`),r.activeWebViewURLs.includes(n)||(r.activeWebViewURLs.push(n),o.debug(`[OpenUrlTool] Added to active URLs: ${n}`));try{let{exec:i}=await import("child_process"),a=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";return i(`${a} "${n}"`,l=>{l?o.debug(`[OpenUrlTool] Failed to open URL in browser: ${l.message}`):o.debug(`[OpenUrlTool] URL opened in default browser: ${n}`)}),[{type:"text",text:`\u2705 URL opened in default browser: ${n}`}]}catch(i){return o.debug(`[OpenUrlTool] Failed to open URL: ${i.message}`),[{type:"text",text:`\u274C Failed to open URL: ${i.message}`}]}}}});var Ye,as=F(()=>{"use strict";U();Ye=class{toolNames=["manage_device_knowledge"];async execute(e,t,s,r){let n=s.action;return o.debug(`[ManageDeviceKnowledgeTool] Device knowledge management not implemented: ${n}`),[{type:"text",text:`Device knowledge management not available in CLI version: ${n}`}]}}});var Ze,cs=F(()=>{"use strict";U();Ze=class{toolNames=["operator_status"];async execute(e,t,s,r){let n=s.taskId,i=s.status,a=s.message;return o.debug(`[OperatorStatusTool] Operator status - Task ${n}: ${i} - ${a}`),[{type:"text",text:"Operator status updated successfully"}]}}});var et,ls=F(()=>{"use strict";U();et=class{toolNames=["provide_input"];async execute(e,t,s,r){let n=s.input;if(!n)throw new Error("Missing input argument");o.debug(`[ProvideInputTool] Delegating provide_input to backend: ${n.substring(0,20)}...`);try{let i=(await Promise.resolve().then(()=>(ze(),yt))).ToolCallingService.getInstance(),a={id:`provide_input_${Date.now()}`,type:"function",function:{name:"provide_input",arguments:JSON.stringify({input:n})}},l=await i.executeTool(a);return l.success?[{type:"text",text:l.result?.message||"Input provided successfully"}]:[{type:"text",text:`Error: ${l.error||"Failed to provide input"}`}]}catch(i){return o.debug(`[ProvideInputTool] Failed to delegate provide_input: ${i.message}`),[{type:"text",text:`Error: ${i.message}`}]}}}});function us(c){c.register(new Ge),c.register(new qe),c.register(new Xe),c.register(new He),c.register(new Ve),c.register(new je),c.register(new Qe),c.register(new Ke),c.register(new Je),c.register(new Ye),c.register(new Ze),c.register(new et)}var ds=F(()=>{"use strict";jt();Qt();Kt();Jt();Yt();ns();os();is();rs();as();cs();ls()});var tt,ps=F(()=>{"use strict";tt=class{constructor(e,t,s,r,n){this.userId=e;this.sessionId=t;this.toolCallId=s;this.runningProcesses=r;this.activeWebViewURLs=n}}});var gs={};te(gs,{FrontendWebSocketService:()=>V});import{EventEmitter as sn}from"events";import nn from"ws";var V,Fe=F(()=>{"use strict";U();de();se();Le();Vt();ds();ps();V=class c extends sn{static instance;webSocket=null;serverHost;deviceId=null;userId=null;sessionId=null;deviceRegistrationService;authService;toolRegistry;isConnected=!1;connectionError=null;isConnecting=!1;runningProcesses=new Map;activeWebViewURLs=[];isConversationActive=!1;heartbeatTimer=null;constructor(e="ws.snowx.ai",t,s="node"){super(),this.serverHost=e,this.userId=t||null,this.deviceRegistrationService=ne.getInstance(),this.authService=q.getInstance(),this.deviceId=this.generateUniqueDeviceId(t,s),this.toolRegistry=new Be,us(this.toolRegistry),o.debug("[FRONTEND WS] Tool registry initialized with 11 frontend tools"),this.deviceId?o.debug(`[FRONTEND WS] Client initialized - Using consistent Device ID: ${this.deviceId}`):o.warn("[FRONTEND WS] Client initialized without device ID - will be set on authentication")}static getInstance(){return c.instance||(c.instance=new c),c.instance}generateUniqueDeviceId(e,t="node"){if(e){let s=this.deviceRegistrationService.getCurrentDeviceId();if(s)return s}return o.warn("[FRONTEND WS] No device ID available from DeviceRegistrationService"),null}async connectForConversation(e,t){if(e&&e!==this.userId&&(this.userId=e),this.userId){let r=this.generateUniqueDeviceId(this.userId,"node");if(r&&this.deviceId!==r)o.debug(`[FRONTEND WS] Device ID changed from ${this.deviceId} to ${r} (using consistent ID from DeviceRegistrationService)`),this.deviceId=r;else if(r)o.debug(`[FRONTEND WS] Using existing consistent device ID: ${this.deviceId}`);else return o.error("[FRONTEND WS] Cannot connect - no device ID available from DeviceRegistrationService"),!1}if(t)this.sessionId=t,o.debug(`[FRONTEND WS] \u{1F510} Session ID updated: ${t}`);else return o.error("[FRONTEND WS] \u274C No sessionId provided! Connection will fail."),!1;if(!this.deviceId)return o.error("[FRONTEND WS] Cannot connect - no device ID set"),!1;if(this.isConversationActive=!0,this.isConnected)return o.debug("[FRONTEND WS] Already connected for conversation"),!0;o.debug("[FRONTEND WS] Connecting for new conversation with deviceId_sessionId composite key"),this.connect(e);let s=await this.waitForConnection(3e4);return s?o.debug("[FRONTEND WS] Connected for conversation with secure composite key"):(o.debug("[FRONTEND WS] Failed to connect for conversation"),this.isConversationActive=!1),s}disconnectAfterConversation(){o.debug("[FRONTEND WS] Conversation ended, disconnecting immediately"),this.isConversationActive=!1,this.terminateAllRunningProcesses(),this.activeWebViewURLs=[],o.debug("[FRONTEND WS] Cleared active WebView URLs"),this.disconnect()}handleConversationComplete(){o.debug("[FRONTEND WS] Conversation completed, scheduling disconnect"),this.disconnectAfterConversation()}connect(e){if(this.isConnected||this.isConnecting){o.debug("[FRONTEND WS] Already connected or connecting");return}o.debug("[FRONTEND WS] === CONNECTION ATTEMPT ==="),o.debug(`[FRONTEND WS] Current state - Connected: ${this.isConnected}, Connecting: ${this.isConnecting}`),this.isConnecting=!0,this.connectionError=null;try{if(!this.sessionId){o.error("[FRONTEND WS] \u274C CRITICAL: No sessionId available for WebSocket URL!"),this.isConnecting=!1;return}let t=`wss://${this.serverHost}/frontend-tools?deviceId=${encodeURIComponent(this.deviceId||"")}&sessionId=${encodeURIComponent(this.sessionId)}`;o.debug(`[FRONTEND WS] Attempting connection to ${t}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId||"not set"}`),o.debug(`[FRONTEND WS] Session ID: ${this.sessionId}`),o.debug(`[FRONTEND WS] User ID: ${e||this.userId||"anonymous"}`),this.webSocket=new nn(t,{headers:{"User-Agent":"SnowX-CLI/1.0.1 (direct-websocket)"},protocolVersion:13,handshakeTimeout:3e4,perMessageDeflate:!1}),this.setupWebSocketHandlers()}catch(t){o.debug(`[FRONTEND WS] Connection failed: ${t.message}`),this.connectionError=t.message,this.isConnecting=!1,this.emit("connectionFailed",t)}}disconnect(){o.debug("[FRONTEND WS] === DISCONNECTING WEBSOCKET ==="),o.debug(`[FRONTEND WS] Current state - Connected: ${this.isConnected}, Connecting: ${this.isConnecting}`),this.stopHeartbeat(),this.webSocket&&(this.webSocket.close(),this.webSocket=null),this.isConnected=!1,this.isConnecting=!1,this.connectionError=null,o.debug("[FRONTEND WS] Disconnected successfully"),this.emit("disconnected")}async waitForConnection(e){return new Promise(t=>{if(this.isConnected){t(!0);return}let s=setTimeout(()=>{t(!1)},e),r=()=>{clearTimeout(s),this.off("connected",r),this.off("connectionFailed",n),t(!0)},n=()=>{clearTimeout(s),this.off("connected",r),this.off("connectionFailed",n),t(!1)};this.once("connected",r),this.once("connectionFailed",n)})}setupWebSocketHandlers(){this.webSocket&&(this.webSocket.on("open",()=>{o.debug("[FRONTEND WS] === CONNECTION OPENED ==="),o.debug(`[FRONTEND WS] WebSocket successfully connected to ${this.serverHost}`),o.debug(`[FRONTEND WS] Device ID: ${this.deviceId}`),this.isConnected=!0,this.isConnecting=!1,this.connectionError=null,this.startHeartbeat(),setTimeout(()=>{this.registerDevice()},1e3),this.emit("connected")}),this.webSocket.on("close",(e,t)=>{o.debug("[FRONTEND WS] === CONNECTION CLOSED ==="),o.debug(`[FRONTEND WS] Close code: ${e}`),o.debug(`[FRONTEND WS] Close reason: ${t}`),o.debug(`[FRONTEND WS] Was connected: ${this.isConnected}`),o.debug(`[FRONTEND WS] Conversation active: ${this.isConversationActive}`),this.isConnected=!1,this.isConnecting=!1,this.stopHeartbeat(),this.emit("disconnected")}),this.webSocket.on("error",e=>{o.debug("[FRONTEND WS] === WEBSOCKET ERROR ==="),o.debug(`[FRONTEND WS] Error: ${e.message}`),o.debug("[FRONTEND WS] Error details:",e),this.connectionError=e.message,this.isConnecting=!1,this.emit("connectionFailed",e)}),this.webSocket.on("message",e=>{try{let t=JSON.parse(e.toString());o.debug("[FRONTEND WS] === RECEIVED MESSAGE ==="),o.debug(`[FRONTEND WS] Message type: ${t.type}`),o.debug("[FRONTEND WS] Message:",JSON.stringify(t,null,2)),this.handleWebSocketMessage(t)}catch(t){o.debug(`[FRONTEND WS] Failed to parse message: ${t.message}`),o.debug("[FRONTEND WS] Raw data:",e.toString())}}))}handleWebSocketMessage(e){o.debug("[FRONTEND WS] === HANDLING MESSAGE ==="),o.debug(`[FRONTEND WS] Processing message type: ${e.type}`);let t=JSON.stringify(e),s=["prompt","instruction","system_prompt","user_prompt","template","claude","gpt","ai_model"];switch(s.some(n=>t.toLowerCase().includes(n))&&o.debug("PROMPT-BASED MESSAGE DETECTED:",{type:e.type,messageSize:t.length,promptKeywordsFound:s.filter(n=>t.toLowerCase().includes(n)),timestamp:new Date().toISOString()}),e.type){case"connection_established":o.debug("[FRONTEND WS] Connection established by server"),this.handleConnectionEstablished(e);break;case"tool_execution_request":o.debug("[FRONTEND WS] Tool execution request received"),this.handleToolExecutionRequest(e);break;case"stop_signal":o.debug("[FRONTEND WS] Stop signal received"),this.handleStopSignal(e);break;case"stop_all_tools":o.debug("[FRONTEND WS] Stop all tools signal received"),this.handleStopAllTools(e);break;case"checkpoint_request":o.debug("[FRONTEND WS] Checkpoint request received"),this.handleCheckpointRequest(e);break;case"shell_cleanup":o.debug("[FRONTEND WS] Shell cleanup signal received"),this.handleShellCleanup(e.data);break;case"ping":o.debug("[FRONTEND WS] Ping received, sending pong"),this.handlePing();break;case"pong":o.debug("[FRONTEND WS] Heartbeat pong received");break;default:o.debug(`[FRONTEND WS] Unknown message type: ${e.type}`),o.debug("[FRONTEND WS] Full message:",e)}}async handleToolExecutionRequest(e){let{data:t,metadata:s}=e,{id:r,tool_name:n,arguments:i}=t;o.debug("[FRONTEND WS] === EXECUTING TOOL ==="),o.debug(`[FRONTEND WS] Tool name: ${n}`),o.debug(`[FRONTEND WS] Tool ID: ${r}`),o.debug(`[FRONTEND WS] Tool call ID: ${s?.tool_call_id}`),o.debug("[FRONTEND WS] Arguments:",JSON.stringify(i,null,2)),o.debug(`[FRONTEND WS] Connection status: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`);let a=JSON.stringify(i),l=JSON.stringify(e),u=["prompt","instruction","system_prompt","user_prompt","template","claude","gpt","execute_model","ai_model","completion"];u.some(m=>a.toLowerCase().includes(m)||l.toLowerCase().includes(m))&&o.debug("SUSPICIOUS TOOL EXECUTION DETECTED:",{toolName:n,toolId:r,promptKeywordsFound:u.filter(m=>a.toLowerCase().includes(m)||l.toLowerCase().includes(m)),argsSize:a.length,timestamp:new Date().toISOString()}),["execute_prompt","run_ai","claude_execute","gpt_run","ai_completion","prompt_exec"].includes(n.toLowerCase())&&o.debug("SUSPICIOUS TOOL NAME DETECTED:",{toolName:n,toolId:r,timestamp:new Date().toISOString()});try{let m,w=!0,S,p=new tt(this.userId,this.sessionId,s?.tool_call_id||r,this.runningProcesses,this.activeWebViewURLs);try{m=await this.toolRegistry.executeTool(n,r,i,p),o.debug(`[FRONTEND WS] Tool executed successfully via registry: ${n}`)}catch(f){o.debug(`[FRONTEND WS] Tool execution failed: ${f.message}`),m=[{type:"text",text:`Error: ${f.message}`}],w=!1,S=f.message}let v={type:"tool_execution_response",data:{id:r,tool_call_id:s?.tool_call_id||r,tool_name:n,content:m,success:w,error:S}};o.debug("[FRONTEND WS] === SENDING TOOL RESPONSE ==="),o.debug(`[FRONTEND WS] Tool: ${n}`),o.debug(`[FRONTEND WS] Success: ${w}`),o.debug(`[FRONTEND WS] Response length: ${m.length} blocks`),o.debug(`[FRONTEND WS] Connection status before send: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`),this.sendMessage(v),await this.captureFrontendToolResultForHistory(n,m,w,S)}catch(m){o.debug("[FRONTEND WS] === TOOL EXECUTION FAILED ==="),o.debug(`[FRONTEND WS] Tool: ${n}`),o.debug(`[FRONTEND WS] Error: ${m.message}`),o.debug("[FRONTEND WS] Error stack:",m.stack),o.debug(`[FRONTEND WS] Connection status: ${this.isConnected?"CONNECTED":"DISCONNECTED"}`);let w=`Error: ${m.message}`;m.code&&(w+=`
174
+ Error Code: ${m.code}`),m.errno&&(w+=`
175
+ Errno: ${m.errno}`),m.syscall&&(w+=`
176
+ System Call: ${m.syscall}`),m.path&&(w+=`
177
+ Path: ${m.path}`),m.stack&&process.env.DEBUG&&(w+=`
178
+
179
+ Stack Trace:
180
+ ${m.stack}`);let S={type:"tool_execution_response",data:{id:r,tool_call_id:s?.tool_call_id||r,tool_name:n,content:[{type:"text",text:w}],success:!1,error:m.message}};o.debug("[FRONTEND WS] Sending error response"),this.sendMessage(S),await this.captureFrontendToolResultForHistory(n,[{type:"text",text:w}],!1,m.message)}}terminateAllRunningProcesses(){o.debug(`[FRONTEND WS] Terminating ${this.runningProcesses.size} running processes`);for(let[e,t]of this.runningProcesses)try{t.kill("SIGTERM"),o.debug(`[FRONTEND WS] Terminated process for tool: ${e}`)}catch(s){o.debug(`[FRONTEND WS] Failed to terminate process ${e}: ${s.message}`)}this.runningProcesses.clear()}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.isConnected&&this.sendMessage({type:"pong",timestamp:Date.now()})},3e4)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}handleConnectionEstablished(e){o.debug("[FRONTEND WS] Connection established by server"),this.registerDevice()}handleStopSignal(e){let s=e.data?.type;switch(o.debug(`[FRONTEND WS] Received stop signal: ${s}`),s){case"all":this.handleStopAll();break;case"tools":this.handleStopTools();break;default:o.debug(`[FRONTEND WS] Unknown stop type: ${s}`)}}handleStopAllTools(e){let t=e.user_id||"unknown",s=e.reason||"backend_stop_request";o.debug(`[FRONTEND WS] Stopping all tools for user: ${t}, reason: ${s}`),this.terminateAllRunningProcesses()}handleCheckpointRequest(e){o.debug("[FRONTEND WS] Handling checkpoint request");let{data:t}=e;if(!t){o.error("[FRONTEND WS] Missing data in checkpoint request");return}let{checkpoint_id:s,session_id:r}=t;if(!s||!r){o.error("[FRONTEND WS] Missing required checkpoint fields");return}o.debug(`[FRONTEND WS] Checkpoint ID: ${s}, Session ID: ${r}`);let n=he.getInstance(),i=n.getQueuedMessages(),a=i.map(g=>({content:g.content,timestamp:Math.floor(g.timestamp.getTime())})),l=a.length>0;o.debug(`[FRONTEND WS] Sending checkpoint response - Has feedback: ${l}, Count: ${a.length}`);let u={type:"checkpoint_response",data:{checkpoint_id:s,session_id:r,has_feedback:l,feedback:a}};this.sendMessage(u),l&&(o.info(`\u26A1 Sent ${a.length} feedback message(s) to AI`),this.emit("feedback:sent",i),n.clearQueue())}handleShellCleanup(e){o.debug("[FRONTEND WS] Received shell_cleanup signal from backend");let t=e?.sessionId;if(!t||typeof t!="string"){o.info('[FRONTEND WS] Shell cleanup received but no sessionId provided - ignoring (only "new" mode is supported, no cleanup needed)');return}o.debug(`[FRONTEND WS] Processing shell cleanup for session: ${t}`),o.info(`[FRONTEND WS] Session cleanup not needed for 'new' mode (session: ${t})`)}handleStopAll(){o.debug("[FRONTEND WS] Stopping all operations"),this.terminateAllRunningProcesses()}handleStopTools(){o.debug("[FRONTEND WS] Stopping running tools"),this.terminateAllRunningProcesses()}handlePing(){this.sendMessage({type:"pong",timestamp:Date.now()})}async registerSession(e,t){if(!this.isConnected){o.debug("[FRONTEND WS] Not connected, cannot register session");return}o.debug(`[FRONTEND WS] Registering session: ${e}`);let s={type:"register",traceId:e,userId:t||this.userId||"",deviceId:this.deviceId||"",timestamp:new Date().toISOString()};this.sendMessage(s),o.debug(`[FRONTEND WS] Session registered: ${e}`)}registerDevice(){let e={type:"device_registration",data:{deviceId:this.deviceId||"",userId:this.userId||"",deviceType:"node-cli",timestamp:new Date().toISOString()}};this.sendMessage(e),o.debug("[FRONTEND WS] Device registration sent")}sendMessage(e){if(o.debug("[FRONTEND WS] === SENDING MESSAGE ==="),o.debug(`[FRONTEND WS] Message type: ${e.type}`),o.debug(`[FRONTEND WS] WebSocket exists: ${!!this.webSocket}`),o.debug(`[FRONTEND WS] Is connected: ${this.isConnected}`),!this.webSocket||!this.isConnected){o.debug("[FRONTEND WS] \u274C Cannot send message - not connected"),o.debug(`[FRONTEND WS] WebSocket state: ${this.webSocket?this.webSocket.readyState:"null"}`);return}try{let t=JSON.stringify(e);o.debug(`[FRONTEND WS] Sending message (${t.length} chars):`,t.substring(0,200)+"..."),this.webSocket.send(t),o.debug("[FRONTEND WS] \u2705 Message sent successfully")}catch(t){o.debug(`[FRONTEND WS] \u274C Failed to send message: ${t.message}`),o.debug(`[FRONTEND WS] WebSocket state: ${this.webSocket?this.webSocket.readyState:"null"}`)}}async sendStopSignal(e,t="all"){if(!this.isConnected){o.debug("[FRONTEND WS] Not connected, cannot send stop signal");return}let s={type:"stop_request",data:{user_id:e,stop_type:t,timestamp:new Date().toISOString()}};this.sendMessage(s),o.debug(`[FRONTEND WS] Sent stop signal for user: ${e}, type: ${t}`)}async sendToolRequest(e){if(!this.isConnected)throw o.debug("[FRONTEND WS] Not connected, cannot send tool request"),new Error("WebSocket not connected");let t={type:"tool_execution_request",data:{id:e.id,tool_name:e.tool_name,arguments:e.arguments,timeout:e.timeout},metadata:{tool_call_id:e.tool_call_id,timestamp:new Date().toISOString()}};o.debug(`[FRONTEND WS] Sending tool request: ${e.tool_name}`),o.debug(`[FRONTEND WS] Tool ID: ${e.id}`),o.debug("[FRONTEND WS] Arguments:",e.arguments),this.sendMessage(t)}get currentDeviceId(){return this.deviceId}isWebSocketConnected(){return this.isConnected}isConversationInProgress(){return this.isConversationActive&&this.isConnected}getActiveWebViewURLs(){return[...this.activeWebViewURLs]}getConnectionStatus(){return{isConnected:this.isConnected,isConnecting:this.isConnecting,error:this.connectionError,deviceId:this.deviceId,userId:this.userId}}async captureFrontendToolResultForHistory(e,t,s,r){let n=t.map(u=>u.text||"").join(`
181
+ `),{PersonalAgentService:i}=await Promise.resolve().then(()=>(ae(),Ee)),a=i.getInstance(),l=r?`Error: ${r}`:n;a.captureFrontendToolResult(e,l,s),o.debug(`[FRONTEND WS] Captured tool result for conversation history: ${e}`)}destroy(){o.debug("[FRONTEND WS] Destroying WebSocket service"),this.terminateAllRunningProcesses(),this.disconnect(),this.removeAllListeners()}}});var ve,ms=F(()=>{"use strict";ve=class{static remove(e){if(!e||!e.includes("<context>"))return e;let t=e,s=/<context>[\s\S]*?<\/context>/gi;return t=t.replace(s,""),t=t.replace(/\n{3,}/g,`
182
+
183
+ `),t.trim()}static hasContextBlocks(e){return e.includes("<context>")}}});var Ee={};te(Ee,{PersonalAgentService:()=>K});import{EventEmitter as on}from"events";import Tt from"axios";import rn from"http";import an from"https";import{v4 as be}from"uuid";import oe from"fs";import $e from"path";import ke from"os";var _e,K,ae=F(()=>{"use strict";we();se();Fe();U();ms();_e=class{static classify(e){let t=e?.message?.toLowerCase()||e?.toString?.()?.toLowerCase()||"",s=e?.code;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":s==="ECONNREFUSED"||s==="ENOTFOUND"||s==="ETIMEDOUT"||s==="ECONNRESET"||s==="ERR_NETWORK"||t.includes("network")||t.includes("connection")||t.includes("timeout")||t.includes("unauthorized")||t.includes("authentication")||t.includes("forbidden")||s===401||s===403?"critical":"parsing"}},K=class c extends on{static instance;authService;apiEndpoint="https://snowx.ai/api-beta/api/chat/tool-calling";httpAgent;httpsAgent;currentTodoList=null;activeWebViewURLs=[];operatorTaskState=null;currentOutput="";completeOutputWithToolResults="";currentPromptId=null;currentAbortController=null;currentModel=null;currentSessionId=null;accumulatedToolCalls=new Map;processedToolCallIds=new Set;constructor(){super(),this.authService=q.getInstance(),this.httpAgent=new rn.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new an.Agent({keepAlive:!0,timeout:36e5}),o.debug("[PERSONAL AGENT] HTTP agents initialized with 3600s socket inactivity timeout")}getAuthToken(){return this.authService.getAuthToken()?.token||"Bo1vmos7jlVT7aDYODhMxcaGc8E3"}async getFirebaseIdToken(){return await this.authService.getFirebaseIdToken()}getDeviceInfo(){let e=process.platform,t=process.arch,s=process.version;return`${e} ${s} (CLI, ${t})`}getDeviceKnowledgeInstruction(){try{let e=this.getDeviceKnowledgePath();this.migrateDeviceKnowledgeIfNeeded(e);let t="";return oe.existsSync(e)?t=oe.readFileSync(e,"utf8"):t=this.initializeDeviceKnowledge(),`Current device knowledge: ${t}
184
+
185
+ Remember to update memory about device if any new information is learned during conversation.`}catch{return`Current device knowledge: No specific device knowledge available.
186
+
187
+ Remember to update memory about device if any new information is learned during conversation.`}}getDeviceKnowledgePath(){let e=$e.join(ke.homedir(),".orion-cli");return $e.join(e,"device-knowledge.md")}migrateDeviceKnowledgeIfNeeded(e){try{if(oe.existsSync(e))return;let t=$e.join(ke.homedir(),"Documents","orion","orion-device-knowledge.md");if(oe.existsSync(t)){o.info("\u{1F4E6} Migrating device knowledge to cross-platform location...");let s=$e.dirname(e);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let r=oe.readFileSync(t,"utf8");oe.writeFileSync(e,r,"utf8"),o.info(`\u2705 Device knowledge migrated to: ${e}`),o.info(` Old location: ${t} (can be safely deleted)`)}}catch(t){o.debug(`Migration skipped: ${t.message}`)}}initializeDeviceKnowledge(){try{let e=this.getDeviceKnowledgePath(),t=$e.dirname(e);oe.existsSync(t)||oe.mkdirSync(t,{recursive:!0});let s=ke.platform(),r=ke.arch(),n=ke.hostname(),i=ke.userInfo(),a=`# Device Knowledge
188
+
189
+ ## System Information
190
+ - **Platform**: ${s}
191
+ - **Architecture**: ${r}
192
+ - **Hostname**: ${n}
193
+ - **Username**: ${i.username}
194
+ - **Home Directory**: ${i.homedir}
195
+
196
+ ## Available Tools
197
+ - Terminal/shell commands via system execution
198
+ - File system operations (read, write, create directories)
199
+ - Network operations and API calls
200
+ - Process management
201
+
202
+ ## Learned Information
203
+ (This section will be updated as the assistant learns about this specific device)
204
+
205
+ ---
206
+ *Last updated: ${new Date().toISOString()}*
207
+ `;return oe.writeFileSync(e,a,"utf8"),a}catch{return"Basic device knowledge initialization failed."}}static getInstance(){return c.instance||(c.instance=new c),c.instance}async sendMessageWithToolCalling(e,t,s,r=.7,n=!0,i,a,l){this.currentPromptId=be(),this.currentOutput="",this.completeOutputWithToolResults="",this.currentModel=s;let u=l?.crossDeviceTaskId;u&&o.debug(`[PERSONAL AGENT] Executing cross-device task: ${u}`),l?.mode==="new"&&(t=[],o.debug("[PERSONAL AGENT] Starting new conversation (cross-device mode: new)")),this.accumulatedToolCalls.clear(),this.processedToolCallIds.clear();let g=i||this.authService.getUserId();o.debug("\u{1F50C} WebSocket will connect after receiving sessionId from API...");let m=(await Promise.resolve().then(()=>(de(),Ae))).DeviceRegistrationService.getInstance().getCurrentDeviceId();if(!m)throw o.error("No device ID available - device registration may have failed"),new Error("Device not registered - cannot submit prompt");let w={user_prompt:{role:"user",content:a&&a.length>0?[{type:"text",text:e},...a.map(S=>({type:"image_url",image_url:{url:S}}))]:[{type:"text",text:e}]},user_id:this.authService.getUserId()||this.getAuthToken(),device_id:m,model:s.name,type:"on-device",device_type:this.getDeviceInfo(),device_knowledge_instruction:this.getDeviceKnowledgeInstruction()};if(l?.conversationId)w.conversationId=l.conversationId,o.debug(`[PERSONAL AGENT] Sending request with conversationId: ${l.conversationId}`),o.debug("[PERSONAL AGENT] Backend will auto-load conversation history");else if(t&&t.length>0){let S=t.map(p=>{let v,f=p;f.metadata?.toolResults?v=f.metadata.toolResults:f.originalContent?v=f.originalContent:v=typeof p.content=="string"?p.content:JSON.stringify(p.content);let I=[{type:"text",text:v}];return f.imageUrls&&f.imageUrls.length>0&&I.push(...f.imageUrls.map(P=>({type:"image_url",image_url:{url:P}}))),{role:p.role,content:I}});for(let p=0;p<S.length;p++)S[p].role;w.messages=S,o.debug(`[PERSONAL AGENT] Sending request with ${S.length} messages (new conversation)`)}else o.debug("[PERSONAL AGENT] Sending request (first ever prompt, no history)");return n?this.performStreamingToolCall(w):this.performNonStreamingToolCall(w)}async performStreamingToolCall(e){let t=await this.getFirebaseIdToken();return t||o.warn("[PERSONAL AGENT] \u26A0\uFE0F No Firebase ID token available - request may fail with 401"),new Promise((s,r)=>{this.currentAbortController=new AbortController;let n="",i=Buffer.alloc(0),a="",l="",u=[],g=null,h=!1,m="";this.currentOutput="",this.completeOutputWithToolResults="";let w=new Map,S=new Set,p=this.authService.getUserId();Tt.post(this.apiEndpoint,e,{responseType:"stream",signal:this.currentAbortController.signal,timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}}).then(async v=>{let f=v.data,I=v.headers["x-session-id"]||v.headers["session-id"];if(I){g=I,this.currentSessionId=I,o.debug(`[PERSONAL AGENT] \u{1F194} SESSION ID CAPTURED: ${I}`);let P=(await Promise.resolve().then(()=>(Fe(),gs))).FrontendWebSocketService.getInstance();o.debug("[PERSONAL AGENT] \u{1F50C} Connecting WebSocket with sessionId..."),await P.connectForConversation(p||void 0,I)?o.debug("[PERSONAL AGENT] \u2705 WebSocket connected with deviceId_sessionId composite key"):o.debug("[PERSONAL AGENT] \u26A0\uFE0F WebSocket connection failed, continuing without frontend tool support")}else o.debug("[PERSONAL AGENT] \u26A0\uFE0F No X-Session-Id header found in response - WebSocket will not connect");f.on("data",P=>{try{i=Buffer.concat([i,P]);let _="",N=0;for(let A=0;A<i.length;A++)try{_=i.slice(0,A+1).toString("utf8"),N=A+1}catch{break}if(N>0){let A=i.slice(0,N);i=i.slice(N),n+=A.toString("utf8")}}catch{n+=P.toString()}let D=[/\r?\n/,/\r/],C=[],E=n;C=E.split(/\r?\n/),E=C.pop()||"",n=E;for(let _ of C){let N=_.trim();if(N.startsWith("data: ")){let A=N.slice(6).trim();if(A==="[DONE]"){this.handleConversationComplete(),this.emit("BotResponseCompleted",a),s(a);return}try{let k=JSON.parse(A);if(k.type==="session_start"&&k.conversationId){let T=k.conversationId,y=k.isNewConversation||!1,$=k.title;o.debug("[PERSONAL AGENT] Received conversationId in first chunk!"),o.debug(`[PERSONAL AGENT] conversationId: ${T}`),o.debug(`[PERSONAL AGENT] isNewConversation: ${y}`),$&&o.debug(`[PERSONAL AGENT] title: "${$}"`),this.emit("conversation_id_received",{conversationId:T,isNew:y,title:$||void 0});continue}if(k.type==="title_generated"&&k.title&&k.conversationId){let T=k.title,y=k.conversationId;o.debug("[PERSONAL AGENT] Received title_generated event!"),o.debug(`[PERSONAL AGENT] conversationId: ${y}`),o.debug(`[PERSONAL AGENT] title: "${T}"`),this.emit("conversation_title_updated",{conversationId:y,title:T});continue}if(k.tool_response&&k.tool_response.content){let T=k.tool_response.content,y=k.tool_response.id||"unknown",$=k.tool_response.name||"unknown";this.emit("tool_completed",{toolName:$,toolId:y,result:T,todos:k.tool_response.todos||null}),this.emit("toolComplete",$);let x="";Array.isArray(T)?x=T.map(W=>typeof W=="string"?W:W&&typeof W=="object"&&(W.text||W.content)||"").join(""):typeof T=="string"?x=T:x=JSON.stringify(T),(!x||x.trim().length===0)&&(x="(empty tool result)");let O=`<context>
208
+ ${x}
209
+ </context>`;u.push(O),a+=O+`
210
+ `,this.completeOutputWithToolResults+=O+`
211
+ `,this.currentOutput+=O+`
212
+ `;continue}if(k.tool_calls){o.debug("Processing tool calls:",k.tool_calls.length,"items");for(let[T,y]of k.tool_calls.entries())if(o.debug("Tool call ["+T+"]:"),y.id){o.debug("Processing tool call ID:",y.id);let $=w.get(y.id)||{};for(let[x,O]of Object.entries(y))if(x==="function"&&typeof O=="object"&&O!==null){let W=$.function||{};$.function={...W,...O}}else $[x]=O;if(w.set(y.id,$),$.function?.arguments&&$.function?.name){let x=$.function.arguments;x.endsWith("}")||x.endsWith('"}')?(o.debug("Complete tool call accumulated:",y.id,"-",$.function.name),o.debug("Arguments:",x.substring(0,100)+(x.length>100?"...":"")),S.has(y.id)||(S.add(y.id),this.handleCompleteToolCall($))):o.debug("Partial tool call:",y.id,"-",$.function.name)}}}else if(k.tool_response&&k.tool_response.content){let T=k.tool_response.content,y=k.tool_response.id||"unknown",$=k.tool_response.name||"unknown",x=k.tool_response.role||"unknown";o.debug("[PERSONAL AGENT] TOOL RESPONSE RECEIVED:"),o.debug(" Tool ID:",y),o.debug(" Tool Name:",$),o.debug(" Tool Role:",x),o.debug(" Content Length:",T.length),o.debug(" Content Preview:",T.substring(0,200)+"..."),this.emit("tool_completed",{toolName:$,toolId:y,result:T,todos:k.tool_response.todos||null}),this.emit("toolComplete",$),k.tool_response.todos&&Array.isArray(k.tool_response.todos)&&(o.debug("[PERSONAL AGENT] Tool response contains",k.tool_response.todos.length,"todo items"),this.handleTodoUpdate({items:k.tool_response.todos}));let O=`<context>
213
+ ${T}
214
+ </context>`;u.push(O),a+=O+`
215
+ `,this.completeOutputWithToolResults+=O+`
216
+ `,this.currentOutput+=O+`
217
+ `,o.debug("[PERSONAL AGENT] Stored tool result (hidden from user) - Total tool results:",u.length)}else if(k.content!==void 0){let T=k.content;if(T&&T.length>0&&o.debug(`[STREAMING] Received content chunk: "${T}" (length: ${T.length})`),T&&T.includes('{"tool_response"'))try{let y,$=!1;try{y=JSON.parse(T),$=!0}catch{let x=T.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(x){let O=x[0];y=JSON.parse(O),$=!1}}if(y&&y.tool_response&&y.tool_response.content){let x=y.tool_response.content,O=y.tool_response.id||"unknown",W=y.tool_response.name||"unknown";this.emit("tool_completed",{toolName:W,toolId:O,result:x,todos:y.tool_response.todos||null}),this.emit("toolComplete",W),y.tool_response.todos&&Array.isArray(y.tool_response.todos)&&this.handleTodoUpdate({items:y.tool_response.todos});let Q="";Array.isArray(x)?Q=x.map(ee=>ee.text||"").join(""):typeof x=="string"?Q=x:Q=JSON.stringify(x);let J=`<context>
218
+ ${Q}
219
+ </context>`;if(u.push(J),a+=J+`
220
+ `,this.completeOutputWithToolResults+=J+`
221
+ `,this.currentOutput+=J+`
222
+ `,!$){let ee=T.match(/\{"tool_response":\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^}]*\}/);if(ee){let G=T.replace(ee[0],"").trim();if(G.length>0){a+=G,l+=G,this.currentOutput+=G,this.completeOutputWithToolResults+=G;let H=ve.remove(G);this.emit("data",H)}}}continue}}catch{}if(T.includes("<think>")){h=!0;let y=T.split("<think>")[0];if(y){a+=y,l+=y,this.currentOutput+=y,this.completeOutputWithToolResults+=y;let $=ve.remove(y);this.emit("data",$)}}else if(T.includes("</think>")){h=!1,m+=T.split("</think>")[0],this.emit("thinking",m),m="";let y=T.split("</think>")[1]||"";if(y){a+=y,l+=y,this.currentOutput+=y,this.completeOutputWithToolResults+=y;let $=ve.remove(y);this.emit("data",$)}}else if(h)m+=T,this.emit("thinking",m);else{a+=T,l+=T,this.currentOutput+=T,this.completeOutputWithToolResults+=T;let y=ve.remove(T);this.emit("data",y)}}else if(k.type==="todo_update")this.handleTodoUpdate(k.data);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(a);return}}catch{o.debug("Treating as plain text"),a+=A,l+=A,this.currentOutput+=A,this.completeOutputWithToolResults+=A;let T=ve.remove(A);this.emit("data",T)}}}}),f.on("end",()=>{this.emit("done"),s(a)}),f.on("error",P=>{switch(o.debug("Streaming error, disconnecting WebSocket and cleaning up"),_e.classify(P)){case"parsing":let C={type:"tool_result",tool_call_id:`error_${be()}`,error:!0,content:`Streaming parsing error occurred: ${P.message}. Please check response format and retry.`};o.debug("\u{1F504} [PERSONAL AGENT] Parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(C)),V.getInstance().handleConversationComplete(),s(a);return;case"critical":V.getInstance().handleConversationComplete(),this.emit("error",P),r(P);break}})}).catch(v=>{if(v.code==="ERR_CANCELED")o.debug("Task was cancelled, disconnecting WebSocket"),V.getInstance().handleConversationComplete(),this.emit("canceled"),s(a);else switch(_e.classify(v)){case"parsing":let I={type:"tool_result",tool_call_id:`error_${be()}`,error:!0,content:`Request parsing error: ${v.message}. Please check request format and retry.`};o.debug("\u{1F504} [PERSONAL AGENT] Request parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(I)),V.getInstance().handleConversationComplete(),s(a);break;case"critical":o.debug("Request failed, disconnecting WebSocket"),V.getInstance().handleConversationComplete(),r(v);break}})})}async performNonStreamingToolCall(e){try{let t=await this.getFirebaseIdToken();t||o.warn("[PERSONAL AGENT] \u26A0\uFE0F No Firebase ID token available - request may fail with 401");let s=await Tt.post(this.apiEndpoint,e,{timeout:18e6,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent,headers:{"Content-Type":"application/json",Authorization:`Bearer ${t||this.getAuthToken()}`}});if(s.data?.content){if(this.currentOutput=s.data.content,this.completeOutputWithToolResults=s.data.completeOutput||s.data.content,s.data.toolResults)for(let r of s.data.toolResults)this.handleToolResult(r.tool,r.result);return s.data.content}throw new Error("No response content received")}catch(t){switch(_e.classify(t)){case"parsing":let r={type:"tool_result",tool_call_id:`error_${be()}`,error:!0,content:`Non-streaming API parsing error: ${t.message}. Please check request format and retry.`};return o.debug("\u{1F504} [PERSONAL AGENT] Non-streaming API parsing error returned as tool result for retry"),this.emit("tool_result",JSON.stringify(r)),"";case"critical":throw this.emit("error",t),new Error(`Tool calling API Error: ${t.message}`)}}}handleCompleteToolCall(e){this.emit("tool_use",e);let t=e.function?.name||"unknown",s=null;if(e.function?.arguments)try{s=JSON.parse(e.function.arguments)}catch{o.debug("[PERSONAL AGENT] Failed to parse tool arguments:",e.function.arguments);return}this.emit("toolExecuting",t),this.executeToolViaWebSocket(e.id,t,s)}async executeToolViaWebSocket(e,t,s){try{let r=V.getInstance(),n={id:e,tool_name:t,arguments:s||{},tool_call_id:e};await r.sendToolRequest(n)}catch(r){o.debug(`Failed to execute tool via WebSocket: ${r.message}`)}}handleToolResult(e,t){this.emit("tool_result",{tool:e,result:t}),o.debug(`Tool Result: ${e.name}`),t&&o.debug(` Result: ${JSON.stringify(t,null,2)}`)}handleWebSocketToolResponse(e){let{tool_name:t,content:s,success:r,error:n}=e;if(o.debug("[PERSONAL AGENT] WebSocket tool response:",t,"success:",r),r&&s){let a=`<context>
223
+ ${s.map(l=>l.text||"").join("")}
224
+ </context>`;this.completeOutputWithToolResults+=a+`
225
+ `,this.currentOutput+=a+`
226
+ `,o.debug("[PERSONAL AGENT] WebSocket tool result stored (hidden from user)")}else if(n){o.debug("[PERSONAL AGENT] WebSocket tool error:",n);let i=`<context>
227
+ Error: ${n}
228
+ </context>`;this.completeOutputWithToolResults+=i+`
229
+ `}}captureFrontendToolResult(e,t,s,r){let n=`<context>
230
+ Tool: ${e}
231
+ Success: ${s}
232
+ Output:
233
+ ${t}
234
+ </context>`;this.completeOutputWithToolResults+=n+`
235
+ `,this.currentOutput+=n+`
236
+ `,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:r,wrappedContent:n})}handleTodoUpdate(e){this.currentTodoList={todos:(e.items||e.todos||[]).map(t=>({id:t.id||be(),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||be(),taskId:e.taskId||e.id||be(),sessionId:e.sessionId||be(),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:r}=await Promise.resolve().then(()=>(we(),Bt)),n=r.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},i=t?.mode==="new"?[]:[];return this.sendMessageWithToolCalling(e,i,n,.7,!0,void 0,void 0,{mode:t?.mode,crossDeviceTaskId:t?.crossDeviceTaskId,conversationId:t?.conversationId})}getCurrentOutput(){return this.currentOutput||this.completeOutputWithToolResults}async stopStreaming(){o.debug("[PERSONAL AGENT] Starting comprehensive stop operation (like SnowX stopStreaming)"),this.stopLocalOperationsOnly(),V.getInstance().terminateAllRunningProcesses(),await this.notifyBackendStop();let t=this.completeOutputWithToolResults,s;if(t&&t.trim().length>0?s=t+`
237
+
238
+ [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(r){o.debug("[PERSONAL AGENT] Firebase update failed for STOP:",r)}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(()=>(de(),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 i=await this.getFirebaseIdToken();i||o.warn("[PERSONAL AGENT] \u26A0\uFE0F No Firebase ID token available for stop request");let a=await Tt.post(t,s,{timeout:1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i||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 r={conversationId:null,content:e,completeWithTools:this.completeOutputWithToolResults,todoList:this.currentTodoList,webViews:this.activeWebViewURLs,operatorState:this.operatorTaskState};this.emit("conversation_complete",r),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 vs={};te(vs,{FirebaseNativeService:()=>Me,TaskMode:()=>kt,TaskStatus:()=>It});import{getDatabase as gn,ref as Et,onValue as mn,update as hn,set as fn,serverTimestamp as vn}from"firebase/database";import{EventEmitter as bn}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 bn{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=ge.getInstance()}setFirebaseInstances(e,t){o.debug(`[Firebase Native] Setting shared Firebase instances from app: ${e.name}`),this.app=e,this.auth=t,this.database=gn(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 r=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=mn(r,i=>{o.debug("[Firebase Native] Data change event received",{exists:i.exists(),key:i.key,taskCount:i.val()?Object.keys(i.val()).length:0}),this.handleTasksSnapshot(i)},i=>{o.error("[Firebase Native] Firebase listener error",{code:i.code||"unknown",message:i.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[r,n]of s){let i=n;if(o.debug("[Firebase Native] Checking task",{taskId:r,status:i.status,mode:i.mode,fromDevice:i.fromDeviceId,toDevice:i.toDeviceId}),i.status==="pending"){if(this.currentTaskId===r){o.debug("[Firebase Native] Already processing task - skipping",{taskId:r});continue}o.debug("[Firebase Native] Found PENDING task - processing",{taskId:r}),this.handleIncomingTask(r,i)}else o.debug("[Firebase Native] Task not pending - skipping",{taskId:r,status:i.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(r){o.error("[FIREBASE-NATIVE] Task execution failed:",r.message),this.cleanupObservers()}}async setupResultMonitoring(e){let{PersonalAgentService:t}=await Promise.resolve().then(()=>(ae(),Ee)),s=t.getInstance();this.completedObserver=r=>{this.currentTaskId===e&&(o.debug(`[RESULT MONITOR] Task ${e} completed successfully`),setTimeout(()=>{this.cleanupObservers()},100))},s.on("BotResponseCompleted",this.completedObserver),this.errorObserver=r=>{if(this.currentTaskId!==e)return;let n=r?.message||r||"Unknown error occurred";o.debug(`[RESULT MONITOR] Task ${e} failed: ${n}`),this.cleanupObservers()},s.on("BotResponseError",this.errorObserver),this.stopObserver=r=>{if(this.currentTaskId!==e)return;let n=r?.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 r=`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:r,status:t,hasResult:!!s});try{o.debug("[Firebase Native] Sending update request to SnowX API",{taskId:e}),await this.firebaseAPI.updateRealtimeData(r,n),o.debug("[Firebase Native] Successfully updated task via SnowX API",{taskId:e,status:t})}catch(i){o.error("[Firebase Native] Failed to update task via SnowX API",{taskId:e,path:r,error:i.message}),o.debug("[Firebase Native] Attempting fallback to Firebase SDK",{taskId:e});try{if(this.database){let a=Et(this.database,r),l={status:t,updatedAt:vn()};s&&(l.result=s),await hn(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,r){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:r});try{let i=Et(this.database,`users/${e}/devices/${t}/tasks/${n}`),a={taskId:n,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:t,prompt:s,mode:r,timestamp:Date.now(),status:"pending"};return await fn(i,a),o.debug("[Firebase Native] Task sent successfully",{taskId:n,targetDeviceId:t}),n}catch(i){throw i}}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 Sn}from"events";var Ie,Dt=F(()=>{"use strict";de();se();Ue();xt();ae();U();Ie=class c extends Sn{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=ge.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 r=this.authService.getFirebaseAuth();if(!r?.currentUser){o.error("No authenticated Firebase user - cannot start listeners");return}if(r.currentUser.uid!==e){o.error("SECURITY: User ID mismatch! Firebase UID:",r.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(r){throw o.error("Failed to start listener:",r.message),r}}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 r=await this.authService.signInWithCustomToken(s);o.debug("Firebase authenticated successfully - UID:",r.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("\u{1F6A8} [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("\u{1F6A8} [SECURITY] Task ID:",e.taskId),o.warn("\u{1F6A8} [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("\u{1F6A8} [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("\u2705 [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 r=s[1],n=s[2];return r.length!==13||!Number.isInteger(Number(r))||n.length!==9?!1:/^[a-z0-9]+$/.test(n)}async handleIncomingTask(e){try{let t=e.val();if(!t)return;let s=t.id,r=t.prompt,n=t.mode,i=t.status;if(!s||!r||!n||i!=="pending")return;if(!this.validateTaskId(s)){o.warn("\u{1F6A8} [SECURITY] Invalid task ID format detected - possible security breach attempt"),o.warn("\u{1F6A8} [SECURITY] Task ID:",s),o.warn("\u{1F6A8} [SECURITY] Expected format: task_<13-digit-timestamp>_<9-char-random>"),o.warn("\u{1F6A8} [SECURITY] Rejecting task execution to prevent unauthorized access");return}o.debug("\u2705 [SECURITY] Task ID validation passed:",s);let a=n==="new"?"new":"existing";this.currentTaskId=s,await this.updateTaskStatus(s,"processing"),await this.executeTask(s,r,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 i={taskId:e,prompt:t,mode:s};this.pendingTasksQueue.push(i),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(r=>setTimeout(r,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(r){o.error("Task execution failed:",r.message)}}async updateTaskStatus(e,t){if(!this.currentUserId||!this.currentDeviceId)return;let s=`users/${this.currentUserId}/devices/${this.currentDeviceId}/tasks/${e}`,r={status:t,updatedAt:"firebase_timestamp"};try{await this.firebaseAPI.updateRealtimeData(s,r)}catch{try{this.firebaseNative&&this.firebaseNative.databaseInstance&&await this.firebaseNative.updateTaskStatus(e,t)}catch{}}}setupResultMonitoring(e){console.log("\u{1F514} [CROSS-DEVICE] ===== SETUP RESULT MONITORING ====="),console.log("\u{1F514} [CROSS-DEVICE] Setting up monitoring for task:",e);let t=()=>{console.log("\u2705 [CROSS-DEVICE] BotResponseCompleted event received"),console.log("\u2705 [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("\u2705 [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("\u2705 [CROSS-DEVICE] Task IDs match - processing completion"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("\u23ED\uFE0F [CROSS-DEVICE] Task IDs do not match - ignoring completion")},s=n=>{console.log("\u274C [CROSS-DEVICE] BotResponseError event received:",n),console.log("\u274C [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("\u274C [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("\u274C [CROSS-DEVICE] Task IDs match - processing error"),this.cleanupObservers()):console.log("\u23ED\uFE0F [CROSS-DEVICE] Task IDs do not match - ignoring error")},r=n=>{console.log("\u{1F6D1} [CROSS-DEVICE] BotResponseStopped event received:",n),console.log("\u{1F6D1} [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("\u{1F6D1} [CROSS-DEVICE] Monitoring task ID:",e),this.currentTaskId===e?(console.log("\u{1F6D1} [CROSS-DEVICE] Task IDs match - processing stop"),setTimeout(()=>{this.cleanupObservers()},100)):console.log("\u23ED\uFE0F [CROSS-DEVICE] Task IDs do not match - ignoring stop")};console.log("\u{1F442} [CROSS-DEVICE] Setting up event listeners..."),this.once("BotResponseCompleted",t),this.once("BotResponseError",s),this.once("BotResponseStopped",r),console.log("\u2705 [CROSS-DEVICE] Result monitoring setup complete for task:",e),console.log("\u{1F514} [CROSS-DEVICE] ===== SETUP RESULT MONITORING END =====")}cleanupObservers(){console.log("\u{1F9F9} [CROSS-DEVICE] ===== CLEANUP OBSERVERS ====="),console.log("\u{1F9F9} [CROSS-DEVICE] Current task ID:",this.currentTaskId),console.log("\u{1F442} [CROSS-DEVICE] Removing event listeners..."),this.removeAllListeners("BotResponseCompleted"),this.removeAllListeners("BotResponseError"),this.removeAllListeners("BotResponseStopped"),console.log("\u2705 [CROSS-DEVICE] Event listeners removed"),console.log("\u{1F9F9} [CROSS-DEVICE] Clearing current task ID"),this.currentTaskId=null,console.log("\u{1F9F9} [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 r=`task_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={taskId:r,fromDeviceId:this.currentDeviceId||"unknown",toDeviceId:e,prompt:t,mode:s,timestamp:me,status:"pending"},i=`users/${this.currentUserId}/devices/${e}/tasks/${r}`;try{await this.firebaseAPI.writeRealtimeData(i,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,r])=>({id:s,...r})).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 ys={};te(ys,{SnowXStreamHandlerService:()=>Rt});import{EventEmitter as kn}from"events";var Rt,Ts=F(()=>{"use strict";Rt=class extends kn{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,r,n){let i=t.includes("text/event-stream")||t.includes("text/plain");return new Promise((a,l)=>{e.on("data",u=>{if(this.isCancelled){a();return}this.totalBytesReceived+=u.length,this.byteBuffer=Buffer.concat([this.byteBuffer,u]);try{let g=this.byteBuffer.toString("utf8");this.buffer+=g,this.rawDataReceived+=g,this.byteBuffer=Buffer.alloc(0),this.processBufferedLines(s,r,n)}catch{this.byteBuffer.length>4&&(this.byteBuffer=Buffer.alloc(0))}}),e.on("end",()=>{if(this.rawDataReceived&&this.linesProcessed===0&&this.handleNonSSEResponse(s,r,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 r,n=this.buffer.indexOf(`\r
239
+ `);if(n!==-1)r=n;else{let i=this.buffer.indexOf(`
240
+ `);if(i!==-1)r=i;else{let a=this.buffer.indexOf("\r");if(a!==-1)r=a;else return}}for(;r!==-1;){if(this.isCancelled)return;let i=this.buffer.substring(0,r);this.linesProcessed++,this.buffer.substring(r,r+2)===`\r
241
+ `?this.buffer=this.buffer.substring(r+2):this.buffer=this.buffer.substring(r+1);let a=i.trim();if(!a){r=this.findNextLineEnd();continue}if(a.startsWith(":")){r=this.findNextLineEnd();continue}a.startsWith("data: ")&&this.processDataLine(a,e,t,s),r=this.findNextLineEnd()}}processDataLine(e,t,s,r){if(this.isCancelled)return;this.dataLinesFound++;let n=e.substring(6).trim();if(n==="[DONE]"){this.emit("streamEnd");return}if(n)try{let i=JSON.parse(n);if(i.choices&&i.choices.length>0){let a=i.choices[0];if(a.delta.tool_calls&&a.delta.tool_calls.length>0)for(let l of a.delta.tool_calls)r?.(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 r=this.thinkingBuffer.indexOf("</think>");if(r!==-1){let n=this.thinkingBuffer.substring(0,r);n&&(this.thinkingContent+=n,s?.(this.thinkingContent)),this.thinkingBuffer=this.thinkingBuffer.substring(r+8),this.isInThinkingBlock=!1;continue}this.thinkingBuffer&&(this.thinkingContent+=this.thinkingBuffer,this.thinkingBuffer="",s?.(this.thinkingContent));break}else{let r=this.thinkingBuffer.indexOf("<think>");if(r!==-1){let n=this.thinkingBuffer.substring(0,r);n&&(this.regularContent+=n,this.fullResponse+=n,t(this.regularContent)),this.thinkingBuffer=this.thinkingBuffer.substring(r+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 r=this.rawDataReceived.substring(6).trim();try{let n=JSON.parse(r);n.choices&&n.choices.length>0&&n.choices[0].delta.content&&this.processThinkingContent(n.choices[0].delta.content,e,t)}catch{}}else try{let r=JSON.parse(this.rawDataReceived);r.choices?.[0]?.message?.content&&this.processThinkingContent(r.choices[0].message.content,e,t)}catch{this.processThinkingContent(this.rawDataReceived,e,t)}}findNextLineEnd(){let e=this.buffer.indexOf(`\r
242
+ `);if(e!==-1)return e;let t=this.buffer.indexOf(`
243
+ `);if(t!==-1)return t;let s=this.buffer.indexOf("\r");return s!==-1?s:-1}printFinalStatistics(){this.fullResponse}cancel(){this.isCancelled=!0,this.emit("cancelled")}reset(){this.buffer="",this.fullResponse="",this.totalBytesReceived=0,this.linesProcessed=0,this.dataLinesFound=0,this.contentChunksReceived=0,this.rawDataReceived="",this.byteBuffer=Buffer.alloc(0),this.thinkingContent="",this.regularContent="",this.isInThinkingBlock=!1,this.thinkingBuffer="",this.isCancelled=!1}getStats(){return{totalBytesReceived:this.totalBytesReceived,linesProcessed:this.linesProcessed,dataLinesFound:this.dataLinesFound,contentChunksReceived:this.contentChunksReceived}}getFinalResponse(){return this.fullResponse||this.regularContent}getThinkingContent(){return this.thinkingContent}}});import In from"axios";import{EventEmitter as xn}from"events";import Dn from"http";import Nn from"https";var it,Cs=F(()=>{"use strict";se();it=class extends xn{client;baseURL="https://api.snowx.io/api/portkey";currentAbortController;httpAgent;httpsAgent;constructor(){super(),this.httpAgent=new Dn.Agent({keepAlive:!0,timeout:36e5}),this.httpsAgent=new Nn.Agent({keepAlive:!0,timeout:36e5}),this.client=In.create({baseURL:this.baseURL,headers:{"Content-Type":"application/json"},timeout:36e5,httpAgent:this.httpAgent,httpsAgent:this.httpsAgent})}getAuthHeaders(){let t=q.getInstance().getAuthToken();return t?.token?{Authorization:`Bearer ${t.token}`}:{}}async executeWithRetry(e,t=3){for(let s=0;s<t;s++)try{return await e()}catch(r){if(r.response?.status===429){if(s===t-1)throw new Error("Rate limit exceeded");let n=Math.pow(2,s);await new Promise(i=>setTimeout(i,n*1e3))}else throw r}throw new Error("Max retries exceeded")}buildRequest(e,t,s,r=.7,n=.9,i,a){return{model:t.apiModelName,provider:t.provider,messages:e,stream:s,temperature:t.name.includes("o4-mini")?void 0:r,max_tokens:t.maxTokens,agent:"default",top_p:t.name.includes("o4-mini")?void 0:n,reasoning_effort:t.reasoningEffort,tools:i,tool_choice:a}}async performNonStreamingRequest(e,t,s=.7,r=.9,n,i){let a=this.buildRequest(e,t,!1,s,r,n,i);try{let u=(await this.executeWithRetry(async()=>{let{data:g}=await this.client.post("/chat/completions",a,{headers:this.getAuthHeaders()});return g})).choices[0];return{content:u.message.content||"",toolCalls:u.message.tool_calls}}catch(l){throw this.emit("error",l),new Error(`API Error: ${l.message}`)}}async performStreamingRequest(e,t,s=.7,r=.9,n,i,a,l,u){let{SnowXStreamHandlerService:g}=await Promise.resolve().then(()=>(Ts(),ys)),h=this.buildRequest(e,t,!0,s,r,n,i);return new Promise((m,w)=>{this.currentAbortController=new AbortController;let S=[],p=new Map,v=new g;this.client.post("/chat/completions",h,{responseType:"stream",signal:this.currentAbortController.signal,headers:this.getAuthHeaders()}).then(async f=>{let I=f.data,P=f.headers["content-type"]||"",D=C=>{if(C?.index!==void 0){let E=C.index;p.has(E)||p.set(E,{});let _=p.get(E);C.id&&(_.id=C.id,_.type="function"),C.function&&(_.function||(_.function={name:"",arguments:""}),C.function.name&&(_.function.name=C.function.name),C.function.arguments&&(_.function.arguments+=C.function.arguments))}u?.(C),this.emit("tool_call_delta",C)};v.on("streamEnd",()=>{p.forEach((C,E)=>{C.id&&C.function?.name&&S.push(C)}),this.emit("done"),m({content:v.getFinalResponse(),toolCalls:S.length>0?S:void 0})}),v.on("cancelled",()=>{this.emit("canceled"),m({content:v.getFinalResponse(),toolCalls:S.length>0?S:void 0})});try{await v.processStreamingResponse(I,P,a||(()=>{}),l,D),p.forEach((C,E)=>{C.id&&C.function?.name&&S.push(C)}),this.emit("done"),m({content:v.getFinalResponse(),toolCalls:S.length>0?S:void 0})}catch(C){this.emit("error",C),w(C)}}).catch(f=>{f.code==="ERR_CANCELED"?(this.emit("canceled"),m({content:"",toolCalls:S.length>0?S:void 0})):w(f)})})}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 An}from"socket.io-client";import{EventEmitter as Rn}from"events";var rt,Es=F(()=>{"use strict";de();rt=class c extends Rn{static instance;socket=null;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=5;reconnectTimeout=null;userId=null;deviceId=null;deviceRegistrationService;constructor(){super(),this.deviceRegistrationService=ne.getInstance()}static getInstance(){return c.instance||(c.instance=new c),c.instance}async connect(e,t="https://snowx.ai"){let s=new Error().stack,r=s?.split(`
244
+ `)[2]?.trim()||"unknown caller";if(console.log("\u{1F50C} [WebSocket] === MAIN WEBSOCKET CONNECTION INITIATED ==="),console.log("\u{1F50C} [WebSocket] Called from:",r),console.log("\u{1F50C} [WebSocket] Call timestamp:",new Date().toISOString()),console.log("\u{1F50C} [WebSocket] Input userId:",e),console.log("\u{1F50C} [WebSocket] Input serverUrl:",t),console.log("\u{1F50C} [WebSocket] Current state:",{isConnected:this.isConnected,reconnectAttempts:this.reconnectAttempts,currentUserId:this.userId,currentDeviceId:this.deviceId}),console.log("\u{1F50C} [WebSocket] Full call stack:"),s?.split(`
245
+ `).slice(1,6).forEach((n,i)=>{console.log(`\u{1F50C} [WebSocket] ${i+1}. ${n.trim()}`)}),this.isConnected)return console.log("\u2705 [WebSocket] Already connected, returning true"),!0;if(this.userId=e,this.deviceId=this.deviceRegistrationService.getCurrentDeviceId(),console.log("\u{1F50C} [WebSocket] DeviceId:",this.deviceId),!this.deviceId)return console.error("\u274C WebSocket: No device ID available from DeviceRegistrationService"),!1;try{console.log("\u{1F50C} [WebSocket] Creating socket.io connection...");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 console.log("\u{1F50C} [WebSocket] Connection options:",JSON.stringify(n,null,2)),this.socket=An(t,n),this.setupEventHandlers(),new Promise((i,a)=>{let l=setTimeout(()=>{a(new Error("WebSocket connection timeout"))},1e4);this.socket?.on("connect",()=>{clearTimeout(l),this.isConnected=!0,this.reconnectAttempts=0,this.emit("connected"),i(!0)}),this.socket?.on("connect_error",u=>{clearTimeout(l),console.error("\u274C WebSocket connection error:",u),a(u)})})}catch(n){return console.error("\u274C 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("\u274C 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("\u274C WebSocket reconnection error:",e),this.emit("reconnection_error",e)}),this.socket.on("reconnect_failed",()=>{console.error("\u274C 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=>{console.log("\u{1F527} [WebSocket] Tool execution event:",{toolName:e.toolName,status:e.status,deviceId:e.deviceId,hasResult:!!e.result,timestamp:new Date().toISOString()}),this.emit("tool_execution",e)}),this.socket.on("operator_progress",e=>{console.log("\u2699\uFE0F [WebSocket] Operator progress event:",{operatorId:e.operatorId,progress:e.progress,status:e.status,hasPromptData:!!(e.prompt||e.promptTemplate),timestamp:new Date().toISOString()}),(e.prompt||e.promptTemplate)&&console.log("\u{1F6A8} [WebSocket] PROMPT-BASED OPERATOR DETECTED:",{hasPrompt:!!e.prompt,hasPromptTemplate:!!e.promptTemplate,promptPreview:(e.prompt||e.promptTemplate||"").substring(0,100)+"..."}),this.emit("operator_progress",e)}),this.socket.on("webview_update",e=>{console.log("\u{1F310} [WebSocket] Webview update event:",{type:e.type,url:e.url,hasContent:!!e.content,timestamp:new Date().toISOString()}),this.emit("webview_update",e)}),this.socket.on("todo_update",e=>{console.log("\u{1F4DD} [WebSocket] Todo update event:",{action:e.action,todoId:e.todoId,hasContent:!!e.content,timestamp:new Date().toISOString()}),this.emit("todo_update",e)}))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("\u274C 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){switch(console.log("\u{1F4F1} [WebSocket] Cross-device message received:",{type:e.type,sourceDevice:e.sourceDevice,targetDeviceId:e.targetDeviceId,dataKeys:Object.keys(e.data||{}),timestamp:new Date().toISOString()}),e.type){case"conversation_shared":console.log("\u{1F4AC} [WebSocket] Conversation shared:",e.data);break;case"model_sync":console.log("\u{1F916} [WebSocket] Model sync received:",e.data);break;case"clipboard_sync":console.log("\u{1F4CB} [WebSocket] Clipboard sync received:",e.data);break;default:console.log("\u2753 [WebSocket] Unknown cross-device message type:",e.type)}}handleConversationSync(e){console.log("\u{1F504} [WebSocket] Conversation sync received:",{action:e.action,conversationId:e.conversationId,timestamp:e.timestamp,dataSize:JSON.stringify(e.data||{}).length,deviceSource:this.deviceId}),e.action==="update"?console.log("\u270F\uFE0F [WebSocket] Conversation update sync processed"):e.action==="delete"?console.log("\u{1F5D1}\uFE0F [WebSocket] Conversation delete sync processed"):e.action==="create"&&console.log("\u2795 [WebSocket] Conversation create sync processed")}handleDeviceStatusUpdate(e){console.log("\u{1F4F1} [WebSocket] Device status update:",{deviceId:e.deviceId,status:e.status,deviceType:e.deviceType,platform:e.platform,timestamp:new Date().toISOString()})}handleNotification(e){console.log("\u{1F514} [WebSocket] Notification received:",{type:e.type,title:e.title,message:e.message,priority:e.priority,timestamp:new Date().toISOString()})}send(e,t){if(!this.isConnected||!this.socket){console.warn("\u26A0\uFE0F WebSocket not connected, message not sent:",e);return}let s={type:e,data:t,timestamp:Date.now(),userId:this.userId||void 0,deviceId:this.deviceId||void 0};console.log("\u{1F4E4} [WebSocket] Sending message:",{type:e,dataSize:JSON.stringify(t).length,userId:this.userId,deviceId:this.deviceId,timestamp:new Date().toISOString()}),this.socket.emit(e,s)}sendCrossDeviceMessage(e,t,s){this.send("cross_device_message",{targetDeviceId:e,messageType:t,data:s,sourceDevice:this.deviceId})}shareConversation(e,t){this.sendCrossDeviceMessage(t||null,"conversation_shared",{conversationId:e,action:"share"})}syncModel(e,t){this.sendCrossDeviceMessage(t||null,"model_sync",{model:e,action:"sync"})}sendTypingIndicator(e){this.send("typing_indicator",{isTyping:e,deviceId:this.deviceId})}syncConversation(e,t,s){this.send("conversation_sync",{conversationId:e,action:t,data:s,timestamp:Date.now()})}syncToolExecution(e,t,s){this.send("tool_execution",{toolName:e,status:t,result:s,deviceId:this.deviceId})}sendUserActivity(e){this.send("user_activity",{activity:e,timestamp:Date.now()})}isWebSocketConnected(){return this.isConnected}getDeviceId(){return this.deviceId}getConnectionStatus(){return{connected:this.isConnected,attempts:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts}}disconnect(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.socket&&(this.socket.disconnect(),this.socket=null),this.isConnected=!1,this.emit("disconnected","manual")}destroy(){this.disconnect(),this.removeAllListeners()}}});var ks,Is=F(()=>{"use strict";ks={apiKey:process.env.FIREBASE_API_KEY||"AIzaSyARpn1ypwsrIwB53shF2K0AKvHjNABcpBA",authDomain:process.env.FIREBASE_AUTH_DOMAIN||"snowx-31c33.firebaseapp.com",databaseURL:process.env.FIREBASE_DATABASE_URL||"https://snowx-31c33-default-rtdb.firebaseio.com",projectId:process.env.FIREBASE_PROJECT_ID||"snowx-31c33",storageBucket:process.env.FIREBASE_STORAGE_BUCKET||"snowx-31c33.firebasestorage.app",messagingSenderId:process.env.FIREBASE_MESSAGING_SENDER_ID||"679827069698",appId:process.env.FIREBASE_APP_ID||"1:679827069698:web:d4fd2c1c30d0b94ca04b5d",measurementId:process.env.FIREBASE_MEASUREMENT_ID||"G-1HZDCGCV7M"}});var Ds={};te(Ds,{ServiceManager:()=>We});import{EventEmitter as Pn}from"events";import{initializeApp as On,getApps as xs}from"firebase/app";import{getAuth as Fn}from"firebase/auth";var We,Pt=F(()=>{"use strict";ae();Cs();se();de();Es();Fe();Dt();ze();we();U();Is();We=class c extends Pn{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=K.getInstance(),this.networkClient=new it,this.authService=q.getInstance(),this.deviceRegistration=ne.getInstance(),this.webSocketService=rt.getInstance(),this.frontendWebSocketService=V.getInstance(),this.crossDeviceService=Ie.getInstance(),this.toolCalling=Oe.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(),await this.initializeAuth(),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 initializeAuth(){await this.authService.autoAuthenticate()||console.log(`
246
+ \u26A0\uFE0F Not authenticated. Please run "orion auth login" to authenticate.`)}async initializeFirebase(){try{let e=this.options.firebaseConfig||ks;if(xs().length===0?(this.firebaseApp=On(e),o.debug("Firebase app initialized")):(this.firebaseApp=xs()[0],o.debug("Using existing Firebase app")),this.firebaseAuth=Fn(this.firebaseApp),o.debug(`Firebase Auth initialized - current user: ${this.firebaseAuth.currentUser?.uid||"none"}`),this.authService.setFirebaseAuth(this.firebaseAuth),o.debug("AuthService connected to shared Firebase Auth instance"),this.firebaseApp&&this.firebaseAuth){let{FirebaseNativeService:t}=await Promise.resolve().then(()=>(xt(),vs));t.getInstance().setFirebaseInstances(this.firebaseApp,this.firebaseAuth),o.debug("FirebaseNativeService connected to shared Firebase instances")}setTimeout(()=>{o.debug(`AuthService Firebase current user after sharing: ${this.firebaseAuth?.currentUser?.uid||"none"}`)},1e3)}catch(e){o.debug("Firebase initialization failed - using access token authentication:",e)}}async initializeWebSocket(){}async ensureWebSocketConnection(){let t=new Error().stack?.split(`
247
+ `)[2]?.trim()||"unknown caller";if(console.log("\u{1F3AF} [SERVICE MANAGER] === WEBSOCKET CONNECTION REQUEST ==="),console.log("\u{1F3AF} [SERVICE MANAGER] Called from:",t),console.log("\u{1F3AF} [SERVICE MANAGER] Call timestamp:",new Date().toISOString()),console.log("\u{1F3AF} [SERVICE MANAGER] Current WebSocket status:",this.webSocketService.isWebSocketConnected()),this.webSocketService.isWebSocketConnected())return console.log("\u2705 [SERVICE MANAGER] WebSocket already connected, returning true"),!0;let s=this.authService.getUserId();if(console.log("\u{1F3AF} [SERVICE MANAGER] Retrieved userId:",s),!s)return console.warn("\u26A0\uFE0F [SERVICE MANAGER] No user ID available, cannot connect WebSocket"),!1;try{console.log("\u{1F3AF} [SERVICE MANAGER] Calling webSocketService.connect() with userId:",s);let r=await this.webSocketService.connect(s);return console.log("\u{1F3AF} [SERVICE MANAGER] WebSocket connection result:",r),!!r}catch(r){return console.log("\u274C [SERVICE MANAGER] WebSocket connection failed:",r),!1}}async initializeCrossDevice(){this.crossDeviceService.enable()}async initializeToolCalling(){["web_search","calculate","get_current_time","http_request"].forEach(t=>this.toolCalling.enableTool(t))}setupServiceConnections(){this.personalAgent.on("conversation_complete",e=>{this.emit("conversation_complete",e)}),this.personalAgent.on("todo_update",e=>{this.emit("todo_update",e),this.webSocketService.isWebSocketConnected()&&this.webSocketService.send("todo_update",e)}),this.personalAgent.on("tool_use",e=>{this.emit("tool_use",e),this.options.enableToolCalling&&(this.isFrontendTool(e.name)?this.executeFrontendTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}).catch(t=>{this.emit("tool_error",{toolCall:e,error:t})}):this.toolCalling.executeTool(e).then(t=>{this.emit("tool_result",{toolCall:e,result:t})}))}),this.authService.on("authenticated",e=>{this.emit("authenticated",e),this.options.enableWebSocket&&!this.webSocketService.isWebSocketConnected()&&this.initializeWebSocket()}),this.webSocketService.on("connected",()=>{this.emit("websocket_connected")}),this.webSocketService.on("cross_device_message",e=>{this.emit("cross_device_message",e)}),this.toolCalling.on("tool_execution_complete",e=>{this.emit("tool_execution_complete",e)})}async sendMessage(e,t=X[0],s={}){let{usePersonalAgent:r=!0,enableToolCalling:n=this.options.enableToolCalling,temperature:i=.7,stream:a=!0}=s;try{let l=[];if(r)return await this.personalAgent.sendMessageWithToolCalling(e,l,t,i,a,this.authService.getUserId()||void 0);{let u=n?this.toolCalling.getAvailableTools():void 0;return a?new Promise((g,h)=>{let m="";this.networkClient.on("data",w=>{m+=w}),this.networkClient.on("done",()=>{g(m)}),this.networkClient.on("error",h),this.networkClient.performStreamingRequest([...l,{role:"user",content:e}],t,i,.9,u)}):(await this.networkClient.performNonStreamingRequest([...l,{role:"user",content:e}],t,i,.9,u)).content}}catch(l){throw l}}getPersonalAgent(){return this.personalAgent}getNetworkClient(){return this.networkClient}getAuthService(){return this.authService}getDeviceRegistration(){return this.deviceRegistration}getWebSocketService(){return this.webSocketService}getCrossDeviceService(){return this.crossDeviceService}getToolCalling(){return this.toolCalling}getFrontendWebSocketService(){return this.frontendWebSocketService}isFrontendTool(e){return["run_command","bash","Bash","read","Read","write","Write","edit","Edit","grep","Grep","glob","Glob","write_file","read_file","upload_file","manage_device_knowledge","open_url","operator_status","take_screenshot"].includes(e)}async executeFrontendTool(e){let{name:t,input:s}=e;switch(t){case"bash":case"Bash":case"run_command":throw new Error("Bash/run_command execution handled directly by frontend-websocket service");case"read":case"read_file":throw new Error("Read/read_file handled directly by frontend-websocket service");case"write":case"write_file":throw new Error("Write/write_file handled directly by frontend-websocket service");case"edit":throw new Error("Edit handled directly by frontend-websocket service");case"grep":throw new Error("Grep handled directly by frontend-websocket service");case"glob":throw new Error("Glob handled directly by frontend-websocket service");case"upload_file":throw new Error("uploadFile method not implemented in FrontendWebSocketService");case"open_url":throw new Error("openURL method not implemented in FrontendWebSocketService");case"take_screenshot":throw new Error("takeScreenshot method not implemented in FrontendWebSocketService");case"operator_status":throw new Error("getOperatorStatus method not implemented in FrontendWebSocketService");case"manage_device_knowledge":throw new Error("manageDeviceKnowledge method not implemented in FrontendWebSocketService");default:throw new Error(`Unknown frontend tool: ${t}`)}}getStatus(){return{initialized:this.initialized,services:{auth:this.authService.isAuthenticated(),firebase:this.firebaseAuth!==null,websocket:this.webSocketService.isWebSocketConnected(),crossDevice:this.crossDeviceService.isEnabled(),toolCalling:this.options.enableToolCalling||!1},user:{authenticated:this.authService.isAuthenticated(),userId:this.authService.getUserId(),tier:this.authService.getCachedUserTier()}}}getAvailableModels(){return X.filter(e=>this.authService.canAccessModel(e.name))}enableService(e){switch(e){case"firebase":this.options.enableFirebase=!0,this.initialized&&this.initializeFirebase();break;case"websocket":this.options.enableWebSocket=!0,this.initialized&&this.initializeWebSocket();break;case"crossDevice":this.options.enableCrossDevice=!0,this.crossDeviceService.enable();break;case"toolCalling":this.options.enableToolCalling=!0;break}}disableService(e){switch(e){case"firebase":this.options.enableFirebase=!1;break;case"websocket":this.options.enableWebSocket=!1,this.webSocketService.disconnect();break;case"crossDevice":this.options.enableCrossDevice=!1,this.crossDeviceService.disable();break;case"toolCalling":this.options.enableToolCalling=!1;break}}async shutdown(){console.log("\u{1F6D1} ServiceManager shutdown initiated...");try{console.log("\u23F9\uFE0F Stopping active operations..."),this.personalAgent.stopCurrentOperation(),this.options.enableToolCalling&&(console.log("\u{1F527} Stopping all running tools..."),this.toolCalling.stopAllRunningTools?.()),console.log("\u{1F310} Disconnecting services..."),this.webSocketService.disconnect(),this.crossDeviceService.destroy(),console.log("\u{1F6AA} Signing out user..."),await this.authService.signOut(),this.initialized=!1,this.emit("shutdown"),console.log("\u2705 ServiceManager shutdown completed")}catch(e){console.error("\u274C ServiceManager shutdown error:",e)}}async waitForDeviceRegistration(e=1e4){let t=this.deviceRegistration.getCurrentDeviceId();if(t){console.log(`\u2705 Device ID already available: ${t}`);return}return console.log("\u23F3 Waiting for device registration to complete..."),new Promise((s,r)=>{let n=setTimeout(()=>{r(new Error(`Device registration timeout after ${e}ms`))},e),i=l=>{console.log(`\u2705 Device registration completed: ${l.deviceId}`),clearTimeout(n),this.deviceRegistration.off("DeviceRegistrationComplete",i),s()};this.deviceRegistration.on("DeviceRegistrationComplete",i);let a=this.deviceRegistration.getCurrentDeviceId();a&&(console.log(`\u2705 Device ID became available: ${a}`),clearTimeout(n),this.deviceRegistration.off("DeviceRegistrationComplete",i),s())})}}});import*as _t from"@sentry/node";_t.init({dsn:"https://9c4a287c781d5a4ea1ab453c3b1f8198@o4510140042117120.ingest.us.sentry.io/4510140071804933",sendDefaultPii:!0,tracesSampleRate:1,environment:process.env.NODE_ENV||"production"});import{Command as Gn}from"commander";import Mn from"react";import{render as Wn}from"ink";se();import d,{useState as bs,useEffect as xe,useCallback as Nt,useRef as wn}from"react";import{Box as R,Text as b,useInput as yn,useApp as Tn}from"ink";import Cn from"ink-spinner";import Ss from"ink-select-input";ae();U();import{exec as cn}from"child_process";import{promisify as ln}from"util";import*as nt from"fs/promises";import*as hs from"path";import*as fs from"os";var un=ln(cn),st=class c{static instance;constructor(){}static getInstance(){return c.instance||(c.instance=new c),c.instance}async captureScreen(){try{let e=hs.join(fs.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;
248
+ [System.Windows.Forms.SendKeys]::SendWait('{PRTSC}');
249
+ Start-Sleep -Milliseconds 100;
250
+ $img = [System.Windows.Forms.Clipboard]::GetImage();
251
+ $img.Save('${e.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Jpeg);`.replace(/\n/g," ")}"`;else return o.debug("[SCREENSHOT] Unsupported platform:",process.platform),null;await un(t);let s=await nt.readFile(e),r=s.toString("base64");return await nt.unlink(e).catch(()=>{}),o.debug(`[SCREENSHOT] Captured screenshot: ${s.length} bytes`),`data:image/jpeg;base64,${r}`}catch(e){return o.debug("[SCREENSHOT] Failed to capture screen:",e.message),process.platform==="linux"&&e.message.includes("scrot")?(console.log(`
252
+ \u26A0\uFE0F 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
253
+ `)):process.platform==="darwin"&&(console.log(`
254
+ \u26A0\uFE0F Screenshot capture failed. This might be due to security settings.`),console.log(`Terminal applications usually don't need special permissions for screencapture.
255
+ `)),null}}static isSupported(){let e=process.platform;return e==="darwin"||e==="linux"||e==="win32"}};import Z from"chalk";import dn from"ora";var j=class{static spinner=null;static formatUserMessage(e){return Z.cyan("You: ")+e}static formatAssistantMessage(e){return Z.green("Assistant: ")+e}static formatError(e){return Z.red("Error: ")+e}static formatWarning(e){return Z.yellow("Warning: ")+e}static formatInfo(e){return Z.blue("Info: ")+e}static formatSuccess(e){return Z.green("\u2713 ")+e}static showSpinner(e){this.spinner&&this.spinner.stop(),this.spinner=dn(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(Z.gray("\u2500".repeat(50)))}static printHeader(e){console.log(),console.log(Z.bold.cyan(e)),console.log(Z.gray("\u2500".repeat(e.length))),console.log()}static formatTimestamp(e){return Z.gray(`[${e.toLocaleTimeString()}]`)}static formatModelName(e){return Z.magenta(`[${e}]`)}static printStreamingStart(){process.stdout.write(Z.green("Assistant: "))}static printStreamingChunk(e){process.stdout.write(e)}static printStreamingEnd(){console.log()}};U();Le();import{EventEmitter as pn}from"events";import Ct from"chalk";var ot=class extends pn{delegate=null;personalAgentService=K.getInstance();currentStreamingTask=null;constructor(e){super(),this.delegate=e||null,this.setupPersonalAgentService()}setupPersonalAgentService(){let e=!0,t="",s=console.log;this.delegate?.usesCustomUI||(console.log=(...r)=>{let n=String(r[0]||"");(n.includes("\u25B8")||n.includes("\u2192")||n.includes("\u270E"))&&t&&(e&&(e=!1),t=""),s.apply(console,r)}),this.personalAgentService.on("data",r=>{if(t+=r,this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(!n.content||n.content===""?n.content=r:n.content+=r),i&&i.isStreaming&&(!i.content||i.content===""?i.content=r:i.content+=r)}}),this.personalAgentService.on("thinking",r=>{}),this.personalAgentService.on("toolExecuting",r=>{}),this.personalAgentService.on("tool_completed",r=>{if(!this.delegate?.usesCustomUI){let{toolName:n}=r;console.log(`
256
+ \u25B8 ${n}`),console.log("\u2713 SUCCESS")}}),this.personalAgentService.on("toolComplete",r=>{}),this.personalAgentService.on("todo_update",r=>{}),this.personalAgentService.on("operator_progress",r=>{}),this.personalAgentService.on("webview_update",r=>{}),this.personalAgentService.on("done",()=>{if(e&&(e=!1),t&&(t=""),e=!0,this.delegate){let r=this.delegate.messages[this.delegate.messages.length-1],n=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];r&&r.isStreaming&&(r.isStreaming=!1),n&&n.isStreaming&&(n.isStreaming=!1),this.delegate.isLoading=!1}}),this.personalAgentService.on("error",r=>{console.error(`
257
+ \u274C Error:`,r.message||r),e=!0,this.delegate&&(this.delegate.isLoading=!1)}),this.personalAgentService.on("conversation_complete",r=>{if(o.debug("[PERSONAL AGENT] Conversation completed"),this.delegate){let n=this.delegate.messages[this.delegate.messages.length-1],i=this.delegate.fullConversationHistory[this.delegate.fullConversationHistory.length-1];n&&n.isStreaming&&(r.content&&r.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated content with clean content: "${r.content.substring(0,50)}..."`),n.content=r.content,n.originalContent=r.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided in conversation_complete event"),r.completeWithTools&&(n.metadata={toolResults:r.completeWithTools}),n.isStreaming=!1,o.debug("[MESSAGE HANDLER] Updated final message using SnowX triple-format")),i&&i.isStreaming&&(r.content&&r.content.trim()?(o.debug(`[MESSAGE HANDLER] Replacing accumulated history content with clean content: "${r.content.substring(0,50)}..."`),i.content=r.content,i.originalContent=r.content):o.debug("[MESSAGE HANDLER] Warning: No clean content provided for history message"),r.completeWithTools&&(i.metadata={toolResults:r.completeWithTools}),i.isStreaming=!1),this.delegate.isLoading=!1,this.delegate.updateCurrentConversation()}})}setDelegate(e){this.delegate=e}async sendMessage(e,t=!0){if(!this.delegate||!e.trim())return;let s=87500,r=e.trim();if(r.length>s){console.log(j.formatError(`Prompt too large (${r.length} characters). Please reduce it to ${s} characters or less.`));return}if(this.delegate.isLoading){let i=he.getInstance();i.addToQueue({content:r,imageUrls:[],attachments:[],model:this.delegate.selectedModel.name})?(console.log(Ct.blue(`\u26A1 Message queued (${i.getQueueCount()} in queue)`)),console.log(Ct.dim(" Your feedback will be sent when AI completes current task"))):console.log(Ct.yellow("\u26A0\uFE0F Queue is full (max 5 messages)"));return}this.delegate.isLoading=!0;let n=null;this.delegate.isVisionEnabled&&(n=await st.getInstance().captureScreen(),n?o.debug(`[MESSAGE HANDLER] Captured screenshot for vision mode: ${n.length} chars`):o.debug("[MESSAGE HANDLER] Failed to capture screenshot, sending message without vision")),this.delegate.currentInput="";try{t?await this.processStreamingMessage(n):await this.processNonStreamingMessage(n)}catch(i){console.error(j.formatError(`Message failed: ${i.message}`)),this.delegate.isLoading=!1,this.emit("BotResponseError",i.message)}}async processStreamingMessage(e){if(this.delegate)try{o.debug("[MESSAGE HANDLER] Using PersonalAgentService (matches SnowX exactly)"),await this.processWithPersonalAgentService(e)}catch(t){throw t}}shouldUsePersonalAgentService(){return!0}async processWithPersonalAgentService(e){if(!this.delegate)return;let t=this.delegate.fullConversationHistory.slice(0,-2).filter(n=>!(n.isStreaming||n.role==="system"||!n.content||typeof n.content=="string"&&n.content.trim().length===0)).map(n=>({role:n.role,content:n.content})),s=this.delegate.fullConversationHistory.filter(n=>n.role==="user"),r=s[s.length-1];if(r)try{let n=e?[e]:void 0,i={conversationId:this.delegate.conversationId||void 0};await this.personalAgentService.sendMessageWithToolCalling(r.content,t,this.delegate.selectedModel,.7,!0,void 0,n,i),o.debug("[MESSAGE HANDLER] PersonalAgentService processing complete")}catch(n){throw o.debug(`[MESSAGE HANDLER] PersonalAgentService error: ${n.message}`),n}}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(r=>r.isStreaming);if(t){if(e=t.content,!t.content.includes("[STOPPED]")&&!t.content.includes("[DONE]")){let n=t.content;n.trim().length>0&&(n+=`
258
+
259
+ `),n+="\u23F9\uFE0F **[STOPPED]** - Operation was cancelled by user request.",t.content=n}t.isStreaming=!1;let r=this.delegate.fullConversationHistory.find(n=>n.isStreaming);r&&(r.content=t.content,r.isStreaming=!1)}this.delegate.isLoading=!1,K.getInstance().stopStreaming().catch(r=>{o.error("[MESSAGE HANDLER] Error in comprehensive stop:",r)}),this.delegate.updateCurrentConversation(),this.emit("BotResponseStopped")}}getMessages(){return this.delegate?.messages||[]}getFullConversationHistory(){return this.delegate?.fullConversationHistory||[]}};ae();gt();Le();Fe();Dt();we();Y();fe();function ws(){let{exit:c}=Tn(),e=q.getInstance(),t=K.getInstance(),s=he.getInstance(),r=V.getInstance(),n=Ie.getInstance();xe(()=>(B.enableCustomUI(),()=>B.disableCustomUI()),[]);let[i,a]=bs({messages:[{role:"system",content:`Welcome to Orion
260
+
261
+ Your autonomous on-device AI agent.
262
+ Type a message to start.`,timestamp:Date.now()}],input:"",isLoading:!1,loadingMessage:"Processing",mode:"prompt",showHelp:!1,showModelMenu:!1,showCommandMenu:!1,tokens:0,cost:0,selectedModel:X.find(p=>p.name===pe.string("selectedAIModel"))||X.find(p=>p.name==="snowx-h4")||X[0],isVisionEnabled:!1,queuedMessages:[],crossDeviceQueue:[],todoList:null,conversationId:null,conversationTitleGenerated:!1}),l=wn(null),[u]=bs(()=>{let p={messages:[],fullConversationHistory:[],isLoading:!1,currentInput:"",selectedModel:X.find(v=>v.name===pe.string("selectedAIModel"))||X.find(v=>v.name==="snowx-h4")||X[0],isVisionEnabled:!1,conversationId:null,usesCustomUI:!0,updateCurrentConversation:()=>{}};return new ot(p)}),g=Nt(async()=>{},[]);xe(()=>{let p=i.messages.map(f=>({role:f.role,content:f.content,timestamp:new Date(f.timestamp||Date.now()),...f.tool&&{tool:f.tool},...f.toolOutput&&{toolOutput:f.toolOutput}})),v={messages:p,fullConversationHistory:p,isLoading:i.isLoading,currentInput:i.input,selectedModel:i.selectedModel,isVisionEnabled:i.isVisionEnabled,conversationId:i.conversationId,usesCustomUI:!0,updateCurrentConversation:g};u.setDelegate(v)},[i.messages,i.selectedModel,i.isVisionEnabled,i.isLoading,i.input,i.conversationId,u,g]);let h=Nt(async p=>{if(p.startsWith("/")){let C=p.toLowerCase().trim();if(C==="/help"||C==="/?"){a(E=>({...E,showCommandMenu:!0,input:""}));return}if(C==="/model"){a(E=>({...E,showModelMenu:!0,input:""}));return}if(C==="/clear"||C==="/new"){a(E=>({...E,messages:[{role:"system",content:`Welcome to Orion
263
+
264
+ Your intelligent AI assistant.
265
+ Type a message to start.`,timestamp:Date.now()}],input:"",todoList:null,conversationId:null,conversationTitleGenerated:!1}));return}if(C==="/vision"){a(E=>({...E,isVisionEnabled:!E.isVisionEnabled,messages:[...E.messages,{role:"system",content:`Vision mode ${E.isVisionEnabled?"disabled":"enabled"}`,timestamp:Date.now()}],input:""}));return}if(C==="/exit"||C==="/quit"){c();return}if(C==="/stop"){i.isLoading?(t.stopStreaming(),a(E=>({...E,isLoading:!1,messages:[...E.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}],input:""}))):a(E=>({...E,messages:[...E.messages,{role:"system",content:"No active task to stop",timestamp:Date.now()}],input:""}));return}if(C==="/signout"){a(E=>({...E,messages:[...E.messages,{role:"system",content:"\u{1F504} Signing out...",timestamp:Date.now()}],input:""}));try{await e.signOut()?(a(_=>({..._,messages:[..._.messages,{role:"system",content:"\u2705 Successfully signed out. Goodbye!",timestamp:Date.now()}]})),setTimeout(()=>c(),1e3)):a(_=>({..._,messages:[..._.messages,{role:"system",content:"\u26A0\uFE0F Sign out failed. Use Ctrl+C to exit.",timestamp:Date.now()}]}))}catch(E){a(_=>({..._,messages:[..._.messages,{role:"system",content:`\u274C Error: ${E.message}`,timestamp:Date.now()}]}))}return}a(E=>({...E,messages:[...E.messages,{role:"system",content:`Unknown command: ${p}
266
+
267
+ Type /help to see available commands.`,timestamp:Date.now()}],input:""}));return}if(i.isLoading){let C=s.addToQueue({content:p,imageUrls:[],attachments:[],model:i.selectedModel.name});a(C?E=>({...E,input:""}):E=>({...E,messages:[...E.messages,{role:"system",content:"\u26A0\uFE0F Queue is full (max 5 messages)",timestamp:Date.now()}]}));return}let v=Date.now(),f={role:"user",content:p,timestamp:v},I={role:"assistant",content:"",timestamp:v+1},P=[...i.messages,f,I];a(C=>({...C,messages:P,input:"",isLoading:!0,loadingMessage:"Processing"}));let D=P.map(C=>({role:C.role,content:C.content,timestamp:new Date(C.timestamp||Date.now()),...C.tool&&{tool:C.tool},...C.toolOutput&&{toolOutput:C.toolOutput}}));u.setDelegate({messages:D,fullConversationHistory:D,isLoading:!1,currentInput:"",selectedModel:i.selectedModel,isVisionEnabled:i.isVisionEnabled,conversationId:i.conversationId,usesCustomUI:!0,updateCurrentConversation:g});try{await u.sendMessage(p)}catch(C){a(E=>({...E,messages:[...E.messages,{role:"system",content:`Error: ${C.message}`,timestamp:Date.now()}],isLoading:!1}))}},[i.isLoading,i.isVisionEnabled,i.selectedModel,s,u,e,c]),m=Nt(()=>{if(!s.hasQueuedMessages())return;let p=s.processNextMessage();p&&(s.startProcessing(),h(p.content))},[s,h]);xe(()=>{let p="",v=N=>{a(A=>({...A,conversationId:N.conversationId,conversationTitleGenerated:!!N.title}))},f=N=>{},I=()=>{a(N=>({...N,loadingMessage:"Processing"}))},P=N=>{p+=N,a(A=>{let k=[...A.messages];for(let T=k.length-1;T>=0;T--)if(k[T].role==="assistant"){k[T].content=p;break}return{...A,messages:k}})},D=N=>{a(A=>{let k=[...A.messages];for(let T=k.length-1;T>=0;T--)if(k[T].role==="assistant"){let y=`
268
+
269
+ \u2022 ${N}`;k[T].content+=y,p+=y;break}return{...A,messages:k,loadingMessage:`Running ${N}`}})},C=N=>{if(N&&N.toolName&&N.result){let A="";typeof N.result=="string"?A=N.result:Array.isArray(N.result)?A=N.result.map(x=>typeof x=="string"?x:x&&typeof x=="object"?x.text||x.content||JSON.stringify(x):"").join(""):N.result.output?A=typeof N.result.output=="string"?N.result.output:JSON.stringify(N.result.output,null,2):N.result.content?A=N.result.content:A=JSON.stringify(N.result,null,2);let k=`<context>
270
+ ${A}
271
+ </context>`;a(x=>{let O=[...x.messages];for(let W=O.length-1;W>=0;W--)if(O[W].role==="assistant"){let Q=O[W];Q.metadata||(Q.metadata={});let J=Q.metadata;J.toolResults?J.toolResults+=`
272
+ `+k:J.toolResults=k;break}return{...x,messages:O}});let T=`${N.toolName} completed`,y="";if(A){let x=A.split(`
273
+ `),O=x.length,W=A.length,Q=A.match(/(?:File|Path|file_path):\s*(.+?)(?:\n|$)/i)||A.match(/(?:Writing|Reading|Editing):\s*(.+?)(?:\n|$)/i),J=Q?Q[1].trim():null,ee=N.toolName.toLowerCase();if(ee.includes("todo")){let G=N.todos;if(G&&Array.isArray(G)&&G.length>0){let H=G.filter(le=>le.status==="completed").length,Se=G.length;T=`Tasks (${H}/${Se})`,y=G.map(le=>{let ct=le.status==="completed"?"\u2713":le.status==="inProgress"||le.status==="in_progress"?"\u22EF":"\u25CB",$t=le.text||le.content||"Unknown task";return` ${ct} ${$t}`}).join(`
274
+ `)}else T="Todo list updated",y=""}else if(ee.includes("read")){T="Read";let G=A.match(/Read (\d+) lines \(from line (\d+) to (\d+)\) out of (\d+) total lines\.\nFile: (.+?)\n\n/);if(G){let[,H,Se,Ps,le,ct]=G;T=`Read ${ct} (${H}/${le} lines)`,y=A.substring(G[0].length)}else A.includes("more lines)")?(T="Read (truncated)",y=A):(T=`Read (${O} lines)`,y=x.slice(0,5).join(`
275
+ `)+(O>5?`
276
+ ...
277
+ (${O-5} more lines)`:""))}else if(ee.includes("write"))if(T="Write completed",A.includes("more lines)")||A.includes("+ ..."))y=A;else{let G=x.filter(H=>H.startsWith("+ ")).slice(0,8);G.length>0?(y=G.join(`
278
+ `),x.filter(H=>H.startsWith("+ ")).length>8&&(y+=`
279
+ + ...
280
+
281
+ (${x.filter(H=>H.startsWith("+ ")).length-8} more lines)`)):(y=x.slice(0,8).map(H=>`+ ${H}`).join(`
282
+ `),O>8&&(y+=`
283
+ + ...
284
+
285
+ (${O-8} more lines)`))}else if(ee.includes("edit"))if(T="Edit completed",J&&(T=`Edited ${J}`),A.match(/(replaced|search|->|→)/gi)){let H=x.filter(Se=>Se.toLowerCase().includes("replaced")||Se.toLowerCase().includes("search")||Se.includes("->")||Se.includes("\u2192"));y=H.slice(0,5).join(`
286
+ `),H.length>5&&(y+=`
287
+ ... (${H.length-5} more changes)`)}else y=x.slice(0,8).join(`
288
+ `),O>8&&(y+=`
289
+ ... (${O-8} more lines)`);else ee.includes("bash")||ee.includes("command")?(T="Command completed",A.includes("showing first")||A.includes("more lines)")?y=A:(y=x.slice(0,15).join(`
290
+ `),O>15&&(y+=`
291
+
292
+ ... (showing first 15 of ${O} lines)`))):(T=`${N.toolName} completed`,y=x.slice(0,8).join(`
293
+ `),O>8&&(y+=`
294
+ ... (${O-8} more lines)`))}let $="";y?$=`
295
+ ${y.split(`
296
+ `).map((W,Q)=>Q===0?` \u2514\u2500 ${T}
297
+ ${W}`:` ${W}`).join(`
298
+ `)}`:$=`
299
+ \u2514\u2500 ${T}`,a(x=>{let O=[...x.messages];for(let W=O.length-1;W>=0;W--)if(O[W].role==="assistant"){if(N.toolName.toLowerCase().includes("todo")){let J=/\n\n• [Tt]odo[Ww]rite\n[\s\S]*?(?=\n\n• |\n\n▶ |$)/g;O[W].content=O[W].content.replace(J,"")}O[W].content+=$,p+=$;break}return{...x,messages:O}})}},E=()=>{p="",a(N=>({...N,isLoading:!1}))},_=N=>{a(A=>({...A,messages:[...A.messages,{role:"system",content:`Error: ${N.message||"Unknown error"}`,timestamp:Date.now()}],isLoading:!1})),p=""};return t.on("conversation_id_received",v),t.on("conversation_title_updated",f),t.on("thinking",I),t.on("data",P),t.on("toolExecuting",D),t.on("tool_completed",C),t.on("done",E),t.on("error",_),()=>{t.off("conversation_id_received",v),t.off("conversation_title_updated",f),t.off("thinking",I),t.off("data",P),t.off("toolExecuting",D),t.off("tool_completed",C),t.off("done",E),t.off("error",_)}},[t,m]),xe(()=>{let p=P=>{a(D=>({...D,queuedMessages:P}))},v=P=>{},f=P=>{l.current=P,a(D=>({...D,todoList:P}))},I=P=>{if(i.isLoading){a(D=>D.crossDeviceQueue.length>=10?{...D,messages:[...D.messages,{role:"system",content:"\u26A0\uFE0F Cross-device queue is full - task rejected",timestamp:Date.now()}]}:{...D,crossDeviceQueue:[...D.crossDeviceQueue,P.prompt]});return}h(P.prompt)};return s.on("queue:updated",p),r.on("feedback:sent",v),t.on("todo_update",f),n.on("CrossDeviceTaskSendMessage",I),()=>{s.off("queue:updated",p),r.off("feedback:sent",v),t.off("todo_update",f),n.off("CrossDeviceTaskSendMessage",I)}},[s,r,t,n,h,i.isLoading,i.selectedModel.name]),xe(()=>{!i.isLoading&&s.hasQueuedMessages()&&m()},[i.isLoading,s,m]),xe(()=>{if(!i.isLoading&&!s.hasQueuedMessages()&&i.crossDeviceQueue.length>0){let p=i.crossDeviceQueue[0];a(v=>({...v,crossDeviceQueue:v.crossDeviceQueue.slice(1)})),h(p)}},[i.isLoading,i.crossDeviceQueue,s,h]),yn((p,v)=>{if(v.escape){if(i.isLoading){t.stopStreaming(),a(f=>({...f,isLoading:!1,messages:[...f.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}));return}if(i.showModelMenu||i.showCommandMenu){a(f=>({...f,showModelMenu:!1,showCommandMenu:!1,input:f.showCommandMenu&&f.input==="/"?"":f.input}));return}if(i.showHelp){a(f=>({...f,showHelp:!1}));return}}if(!i.showModelMenu){if(v.ctrl&&p==="c"){i.isLoading?(t.stopStreaming(),a(f=>({...f,isLoading:!1,messages:[...f.messages,{role:"system",content:"[STOPPED] - Task was stopped by user",timestamp:Date.now()}]}))):c();return}if(p==="?"&&i.input===""){a(f=>({...f,showHelp:!f.showHelp}));return}if(v.return&&!i.showCommandMenu){i.input.trim()&&h(i.input);return}if(v.delete||v.backspace){a(f=>{let I=f.input.slice(0,-1);return f.showCommandMenu&&!I.startsWith("/")?{...f,input:I,showCommandMenu:!1}:{...f,input:I}});return}!v.ctrl&&!v.meta&&p&&a(f=>{let I=f.input+p;return I==="/"&&!f.showCommandMenu?{...f,input:I,showCommandMenu:!0}:{...f,input:I}})}});let w=e.getUserEmail()||"User",S=ue.getDisplayName(ue.getCurrentUserTier());return d.createElement(R,{flexDirection:"column",width:"100%"},d.createElement(R,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:0,width:"100%"},d.createElement(b,{color:"white"},i.selectedModel.displayName),d.createElement(b,{color:"gray",dimColor:!0}," \u2022 "),d.createElement(b,{color:"gray"},w),d.createElement(b,{color:"gray",dimColor:!0}," \u2022 "),d.createElement(b,{color:"white"},S),i.queuedMessages.length>0&&d.createElement(d.Fragment,null,d.createElement(b,{color:"gray",dimColor:!0}," \u2022 "),d.createElement(b,{color:"white",inverse:!0,bold:!0}," ",i.queuedMessages.length," "),d.createElement(b,{color:"gray"}," queued")),i.crossDeviceQueue.length>0&&d.createElement(d.Fragment,null,d.createElement(b,{color:"gray",dimColor:!0}," \u2022 "),d.createElement(b,{color:"blue",inverse:!0,bold:!0}," \u{1F4F1} ",i.crossDeviceQueue.length," "),d.createElement(b,{color:"gray"}," cross-device"))),d.createElement(R,{flexDirection:"column",paddingX:2,paddingY:1,minHeight:15},i.messages.map((p,v)=>d.createElement(En,{key:`${p.role}-${p.timestamp}-${v}`,message:p}))),i.todoList&&i.todoList.todos.length>0&&i.todoList.todos.some(p=>p.status!=="completed")&&d.createElement(R,{paddingX:2,marginBottom:1},d.createElement(R,{borderStyle:"round",borderColor:"gray",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(R,{marginBottom:1},d.createElement(b,{color:"white",bold:!0},"Tasks"),d.createElement(b,{color:"gray"}," \u2022 "),d.createElement(b,{color:"gray"},i.todoList.todos.filter(p=>p.status==="completed").length,"/",i.todoList.todos.length)),i.todoList.todos.map((p,v)=>{let f=p.status==="completed"?"\u2713":p.status==="in_progress"?"\u22EF":"\u25CB",I=p.status==="completed"?"green":p.status==="in_progress"?"blue":"gray";return d.createElement(R,{key:p.id||v},d.createElement(b,{color:I},f),d.createElement(b,{color:"gray"}," "),d.createElement(b,{color:p.status==="completed"?"gray":"white",dimColor:p.status==="completed"},p.status==="in_progress"&&p.activeForm?p.activeForm:p.text))}))),i.isLoading&&d.createElement(R,{paddingX:0,marginBottom:1},d.createElement(b,{color:"magenta"},d.createElement(Cn,{type:"dots"})),d.createElement(b,{color:"white"}," ",i.loadingMessage,"\u2026 "),d.createElement(b,{color:"white"},"(esc to interrupt)")),i.showHelp&&d.createElement(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Keyboard Shortcuts"),d.createElement(R,{marginTop:1,flexDirection:"column"},d.createElement(b,{color:"white"},"\u2022 ",d.createElement(b,{color:"white",bold:!0},"Enter")," ",d.createElement(b,{color:"white"},"Submit message")),d.createElement(b,{color:"white"},"\u2022 ",d.createElement(b,{color:"white",bold:!0},"?")," ",d.createElement(b,{color:"white"},"Toggle this help")),d.createElement(b,{color:"white"},"\u2022 ",d.createElement(b,{color:"white",bold:!0},"Esc")," ",d.createElement(b,{color:"white"},"Stop generation / Close menus")),d.createElement(b,{color:"white"},"\u2022 ",d.createElement(b,{color:"white",bold:!0},"Ctrl+C")," ",d.createElement(b,{color:"white"},"Stop generation / Exit"))),d.createElement(R,{marginTop:1},d.createElement(b,{color:"white"},"Press Esc to close"))),i.showModelMenu&&d.createElement(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Select Model"),d.createElement(R,{marginTop:1},d.createElement(Ss,{items:X.map(p=>({label:`${p.displayName}`,value:p.name})),onSelect:p=>{let v=X.find(f=>f.name===p.value);v&&(pe.set("selectedAIModel",v.name),a(f=>({...f,selectedModel:v,showModelMenu:!1,messages:[...f.messages,{role:"system",content:`Switched to ${v.displayName}`,timestamp:Date.now()}]})))}})),d.createElement(R,{marginTop:1},d.createElement(b,{color:"white"},"Esc to cancel"))),i.showCommandMenu&&(()=>{let p=[{label:"/model \u2014 Change AI model",value:"model"},{label:"/new \u2014 Start new conversation",value:"new"},{label:"/clear \u2014 Clear conversation",value:"clear"},{label:"/stop \u2014 Stop current generation",value:"stop"},{label:"/vision \u2014 Toggle vision mode",value:"vision"},{label:"/signout \u2014 Sign out and exit",value:"signout"},{label:"/exit \u2014 Exit Orion",value:"exit"},{label:"/help \u2014 Show this menu",value:"help"}],v=i.input.startsWith("/")?i.input.substring(1).toLowerCase():"",f=v?p.filter(I=>I.value.toLowerCase().includes(v)):p;return d.createElement(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,flexDirection:"column"},d.createElement(b,{bold:!0,color:"white"},"Available Commands ",v&&`(filtered: "${v}")`),d.createElement(R,{marginTop:1},d.createElement(Ss,{items:f.length>0?f:[{label:"No matching commands",value:""}],onSelect:I=>{I.value&&(a(P=>({...P,showCommandMenu:!1,input:""})),h(`/${I.value}`))}})),d.createElement(R,{marginTop:1},d.createElement(b,{color:"white"},"Esc to cancel")))})(),i.queuedMessages.length>0&&d.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},i.queuedMessages.map((p,v)=>d.createElement(R,{key:p.id,borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,marginBottom:1},d.createElement(R,null,d.createElement(b,{color:"white",bold:!0},v+1),d.createElement(b,{color:"white"}," \u2022 "),d.createElement(b,{color:"white"},p.content.length>60?p.content.substring(0,60)+"...":p.content)))),d.createElement(R,null,d.createElement(b,{color:"white"},i.queuedMessages.length," message",i.queuedMessages.length>1?"s":""," queued"))),i.crossDeviceQueue.length>0&&d.createElement(R,{flexDirection:"column",paddingX:2,marginBottom:1},i.crossDeviceQueue.map((p,v)=>d.createElement(R,{key:`cross-${v}`,borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:0,marginBottom:1},d.createElement(R,null,d.createElement(b,{color:"blue",bold:!0},"\u{1F4F1} ",v+1),d.createElement(b,{color:"white"}," \u2022 "),d.createElement(b,{color:"white"},p.length>60?p.substring(0,60)+"...":p)))),d.createElement(R,null,d.createElement(b,{color:"blue"},i.crossDeviceQueue.length," cross-device task",i.crossDeviceQueue.length>1?"s":""," waiting"))),d.createElement(R,{borderStyle:"round",borderColor:"white",paddingX:2,paddingY:0,flexDirection:"column",width:"100%"},d.createElement(R,null,d.createElement(b,{color:"white"},"\u25B6 "),d.createElement(b,{color:"white"},i.input,!i.isLoading&&d.createElement(b,{color:"white",inverse:!0}," "))),d.createElement(R,{marginTop:0},d.createElement(b,{color:"white"},i.isLoading?"Send feedback or press Enter to queue \xB7 esc to stop":"/help \xB7 ? \xB7 enter to submit"))),d.createElement(R,{paddingX:2,paddingY:0},d.createElement(b,{color:"white"},"? help \xB7 Ctrl+C exit")))}function At(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=e.replace(/\[(.+?)\]\(.+?\)/g,"$1"),e}function En({message:c}){let{role:e,content:t,tool:s}=c;if(e==="system"){let r=t.split(`
300
+ `);return d.createElement(R,{marginBottom:1,justifyContent:"flex-start"},d.createElement(R,{paddingX:2,paddingY:1,flexDirection:"column",borderStyle:"round",borderColor:"white"},r.map((n,i)=>i===0?d.createElement(b,{key:`system-${i}-${n.substring(0,10)}`,color:"white",bold:!0},n):d.createElement(b,{key:`system-${i}-${n.substring(0,10)}`,color:"white"},n))))}if(e==="user")return d.createElement(R,{marginBottom:1},d.createElement(b,{color:"blue"}," \u25B6 "),d.createElement(b,{color:"white",bold:!0},t));if(e==="assistant"){let r=t.split(`
301
+ `);return d.createElement(R,{marginBottom:1,flexDirection:"column"},d.createElement(R,null,d.createElement(b,{color:"white"}," Orion ")),r.map((n,i)=>{if(n.match(/^• /)){let u=!1;for(let g=i-1;g>=0;g--){if(r[g].match(/^ └─ /)){u=!0;break}if(r[g].match(/^• /))break}return u?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(b,null," "),d.createElement(R,null,d.createElement(b,{color:"gray"},"\u25CF"),d.createElement(b,{color:"white",bold:!0},n.substring(1)))):d.createElement(R,{key:i},d.createElement(b,{color:"gray"},"\u25CF"),d.createElement(b,{color:"white",bold:!0},n.substring(1)))}if(n.match(/^ └─ /)){let u=n.substring(4);return d.createElement(R,{key:i},d.createElement(b,{color:"green"}," \u2514\u2500 "),d.createElement(b,{color:"white"},u))}if(n.match(/^ [✓⋯○] /)){let u=n.substring(5,6),g=n.substring(7),h=u==="\u2713"?"green":u==="\u22EF"?"blue":"gray",m=r[i+1];return m&&(m.match(/^• /)||m.trim()!==""&&!m.match(/^ /))?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(R,null,d.createElement(b,{color:h}," ",u," "),d.createElement(b,{color:u==="\u2713"?"gray":"white"},g)),d.createElement(b,null," ")):d.createElement(R,{key:i},d.createElement(b,{color:h}," ",u," "),d.createElement(b,{color:u==="\u2713"?"gray":"white"},g))}if(n.match(/^ \+ /)){let u=r[i+1];return u&&(u.match(/^• /)||u.trim()!==""&&!u.match(/^ /))?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(R,null,d.createElement(b,{color:"green"}," + "),d.createElement(b,{color:"white"},n.substring(7))),d.createElement(b,null," ")):d.createElement(R,{key:i},d.createElement(b,{color:"green"}," + "),d.createElement(b,{color:"white"},n.substring(7)))}if(n.match(/^ \d+→/)){let u=n.match(/^( \d+→)(.*)$/);if(u){let g=r[i+1];return g&&(g.match(/^• /)||g.trim()!==""&&!g.match(/^ /))?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(R,null,d.createElement(b,{color:"gray"},u[1]),d.createElement(b,{color:"white"},u[2])),d.createElement(b,null," ")):d.createElement(R,{key:i},d.createElement(b,{color:"gray"},u[1]),d.createElement(b,{color:"white"},u[2]))}}if(n.match(/^ /)){let u=At(n),g=r[i+1];return g&&(g.match(/^• /)||g.trim()!==""&&!g.match(/^ /))?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(b,{color:"white"},u),d.createElement(b,null," ")):d.createElement(b,{key:i,color:"white"},u)}if(n.trim()==="")return d.createElement(b,{key:i}," ");let a=i>0?r[i-1]:null;return a&&a.match(/^ /)?d.createElement(R,{key:i,flexDirection:"column"},d.createElement(b,null," "),d.createElement(b,{color:"white"},At(n))):d.createElement(b,{key:i,color:"white"},At(n))}))}return null}Pt();se();se();import M from"chalk";import $n from"inquirer";import _n from"open";var ce=class{authService;constructor(){this.authService=q.getInstance()}async login(){console.log(M.blue(`
302
+ \u{1F510} Orion Authentication`)),console.log(M.gray("\u2500".repeat(50)));let e="https://meetorion.app/auth?backUrl=/auth/token&platform=cli";console.log(M.yellow(`
303
+ Please visit the following URL to authenticate:`)),console.log(M.cyan.underline(e));try{await _n(e),console.log(M.gray(`
304
+ (Browser opened automatically)`))}catch{console.log(M.gray(`
305
+ (Please open the URL manually in your browser)`))}console.log(M.yellow(`
306
+ After logging in, copy the access token and paste it here:`));let{accessToken:t}=await $n.prompt([{type:"password",name:"accessToken",message:"Access Token:",mask:"*",validate:s=>!s||s.trim().length===0?"Access token is required":!0}]);console.log(M.gray(`
307
+ Verifying access token...`));try{if(await this.authService.authenticateWithAccessToken(t.trim())){let r=await this.authService.getUserInfo();console.log(M.green(`
308
+ \u2705 Authentication successful!`)),r&&(console.log(M.gray(`Logged in as: ${r.email||r.username||"User"}`)),console.log(M.gray(`Subscription: ${this.getSubscriptionDisplay(r.subscription?.tier)}`)))}else console.log(M.red(`
309
+ \u274C Authentication failed. Please try again.`))}catch(s){console.log(M.red(`
310
+ \u274C Authentication error: ${s.message}`))}}async logout(){console.log(M.yellow(`
311
+ \u{1F504} Signing out...`)),console.log(M.gray("This will clear all stored data and device registrations.")),await this.authService.signOut()?(console.log(M.green(`
312
+ \u2705 Successfully signed out`)),console.log(M.gray("All authentication data and settings have been cleared.")),console.log(M.gray('Run "orion auth login" to sign in again.'))):(console.log(M.red(`
313
+ \u274C Logout failed`)),console.log(M.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(M.green(`
314
+ \u2705 Authenticated`)),t){console.log(M.gray("\u2500".repeat(50))),console.log(M.white("User:",t.name||t.username||"N/A")),console.log(M.white("Email:",t.email||"N/A"));let s=this.getSubscriptionDisplay(t.subscription?.tier);console.log(M.white("Subscription:",s)),t.usage&&(console.log(M.gray(`
315
+ Usage:`)),console.log(M.white(` Standard prompts: ${t.usage.prompt||0}`)),console.log(M.white(` Enhanced prompts: ${t.usage.enhancedPrompt||0}`)),console.log(M.white(` Deep prompts: ${t.usage.deepPrompt||0}`)))}}else console.log(M.yellow(`
316
+ \u26A0\uFE0F Not authenticated`)),console.log(M.gray('Run "orion auth login" to authenticate'))}getSubscriptionDisplay(e){switch(e){case 0:return"Free";case 1:return"Plus";case 2:return"Pro";default:return"Free"}}};fe();var Ns=!1;async function Ot(){if(Ns){console.log("Already running...");return}Ns=!0,B.enableCustomUI();let c=We.getInstance(),e=q.getInstance();if(await e.autoAuthenticate(),e.isAuthenticated()||(console.log(`\u{1F510} Authentication required to use Orion CLI
317
+ `),await new ce().login(),e.isAuthenticated()||(console.error(`
318
+ \u274C Authentication failed. Please try again.`),process.exit(1)),console.log(`
319
+ \u2728 Starting Orion CLI...
320
+ `)),!c.isInitialized()){console.log("\u{1F527} Initializing Orion services...");try{await c.initialize({enableFirebase:!0,enableWebSocket:!0,enableCrossDevice:!0,enableToolCalling:!0})}catch(s){console.error(`
321
+ \u274C Failed to initialize services:`,s.message),console.error(`
322
+ \u{1F4A1} Tip: Check your internet connection and Firebase configuration.
323
+ `),process.exit(1)}}await e.autoAuthenticate(),e.isFirebaseAuthenticated()||(console.log(`
324
+ \u26A0\uFE0F Firebase authentication failed. Re-authenticating...
325
+ `),await e.signOut(),await new ce().login(),e.isAuthenticated()||(console.error(`
326
+ \u274C Authentication failed. Cannot start Orion CLI.
327
+ `),process.exit(1)),await e.autoAuthenticate(),e.isFirebaseAuthenticated()||(console.error(`
328
+ \u274C Firebase authentication still failed. Please check your connection and try again.
329
+ `),process.exit(1))),await e.getFirebaseIdToken()||(console.log(`
330
+ \u26A0\uFE0F Session expired. Please log in again.
331
+ `),await e.signOut(),await new ce().login(),e.isAuthenticated()||(console.error(`
332
+ \u274C Authentication failed. Cannot start Orion CLI.
333
+ `),process.exit(1)),await e.autoAuthenticate(),await e.getFirebaseIdToken()||(console.error(`
334
+ \u274C Failed to obtain authentication token. Please try again.
335
+ `),process.exit(1))),console.log("\u2705 Authentication verified"),console.clear(),process.stdout.write("\x1Bc"),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),Wn(Mn.createElement(ws))}we();U();import{EventEmitter as Un}from"events";import Ln from"axios";import{execSync as Bn}from"child_process";import As from"chalk";var at=class c extends Un{static instance;packageName="@zinley/orion";currentVersion;isChecking=!1;constructor(e){super(),this.currentVersion=e}static getInstance(e){return c.instance||(c.instance=new c(e)),c.instance}async checkAndUpdate(){if(!this.isChecking){this.isChecking=!0;try{let e=await this.fetchLatestVersion();this.isNewerVersion(e,this.currentVersion)?await this.performUpdate(e):o.debug(`Already on latest version: ${this.currentVersion}`)}catch(e){o.debug("Update check failed:",e)}finally{this.isChecking=!1}}}async fetchLatestVersion(){let e=`https://registry.npmjs.org/${this.packageName}`;return(await Ln.get(e,{timeout:5e3,headers:{Accept:"application/json"}})).data["dist-tags"].latest}isNewerVersion(e,t){let s=e.split(".").map(Number),r=t.split(".").map(Number);for(let n=0;n<3;n++){let i=s[n]||0,a=r[n]||0;if(i>a)return!0;if(i<a)return!1}return!1}async performUpdate(e){try{let t=`npm install -g ${this.packageName}@latest`;o.debug(`Auto-updating from ${this.currentVersion} to ${e}`),Bn(t,{stdio:"pipe",encoding:"utf8"}),console.log(As.green(`\u2713 Updated to v${e}`)+As.gray(` - restarting...
336
+ `)),process.exit(0)}catch(t){o.debug("Auto-update failed:",t)}}async checkForUpdates(){try{let e=await this.fetchLatestVersion();return{hasUpdate:this.isNewerVersion(e,this.currentVersion),latestVersion:e}}catch(e){return o.debug("Update check failed:",e),{hasUpdate:!1}}}};import qn from"dotenv";import{fileURLToPath as Xn}from"url";import{dirname as Hn,join as Vn}from"path";import{readFileSync as zn}from"fs";qn.config();var jn=Xn(import.meta.url),Qn=Hn(jn),Rs=JSON.parse(zn(Vn(Qn,"..","package.json"),"utf8")),Kn=at.getInstance(Rs.version);Kn.checkAndUpdate().catch(()=>{});var De=new Gn;De.name("orion").description("Orion CLI - AI Assistant powered by multiple models").version(Rs.version);De.command("chat").description("Start Orion chat interface (Ink UI)").action(async()=>{try{await Ot()}catch(c){console.error(j.formatError(c.message)),process.exit(1)}});De.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(()=>(Pt(),Ds)),s=t.getInstance();console.log("\u{1F527} Initializing Orion services..."),await s.initialize(),await s.waitForDeviceRegistration();let r=X.find(i=>i.name===e.model)||X[0];console.log("\u{1F4AD} Sending message...");let n=await s.sendMessage(c,r,{usePersonalAgent:!0,enableToolCalling:!0,temperature:.7,stream:e.stream});console.log(n)}catch(t){j.stopSpinner(!1),console.error(j.formatError(t.message)),process.exit(1)}});var Ft=De.command("auth").description("Authentication commands");Ft.command("login").description("Login to Orion").action(async()=>{try{await new ce().login()}catch(c){console.error(j.formatError(c.message)),process.exit(1)}});Ft.command("logout").description("Logout from Orion").action(async()=>{try{await new ce().logout()}catch(c){console.error(j.formatError(c.message)),process.exit(1)}});Ft.command("status").description("Check authentication status").action(async()=>{try{await new ce().status()}catch(c){console.error(j.formatError(c.message)),process.exit(1)}});De.command("models").description("List available AI models").action(()=>{j.printHeader("Available Models");for(let c of X)console.log(`${j.formatModelName(c.name)} - ${c.displayName}`)});process.argv.length===2?Ot().catch(c=>{console.error(j.formatError(c.message)),process.exit(1)}):De.parse(process.argv);
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@zinley/orion",
3
+ "version": "1.1.8",
4
+ "description": "A fully autonomous on-device agent that lives in your terminal.",
5
+ "main": "dist/index.js",
6
+ "type": "module",
7
+ "bin": {
8
+ "orion": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "scripts": {
15
+ "build": "node build.js",
16
+ "dev": "tsx watch src/index.ts",
17
+ "start": "node dist/index.js",
18
+ "demo": "tsx src/ink-ui/index.tsx",
19
+ "clean": "rm -rf dist",
20
+ "prepublishOnly": "npm run clean && npm run build",
21
+ "test": "npm run build && node test-task-validation.js",
22
+ "test:security": "npm run build && node test-security-integration.js",
23
+ "test:all": "npm run test && npm run test:security"
24
+ },
25
+ "keywords": [],
26
+ "author": "",
27
+ "license": "ISC",
28
+ "packageManager": "pnpm@10.6.2",
29
+ "devDependencies": {
30
+ "@types/figlet": "^1.7.0",
31
+ "@types/marked-terminal": "^6.1.1",
32
+ "@types/node": "^24.3.1",
33
+ "nodemon": "^3.1.10",
34
+ "tsx": "^4.20.5",
35
+ "typescript": "^5.9.2"
36
+ },
37
+ "dependencies": {
38
+ "@firebase/firestore": "^4.9.1",
39
+ "@inquirer/checkbox": "^4.2.2",
40
+ "@inquirer/prompts": "^7.8.4",
41
+ "@sentry/node": "^10.17.0",
42
+ "@types/inquirer": "^9.0.9",
43
+ "@types/react": "^19.2.2",
44
+ "@types/uuid": "^10.0.0",
45
+ "@types/ws": "^8.18.1",
46
+ "axios": "^1.12.0",
47
+ "boxen": "^8.0.1",
48
+ "chalk": "^5.6.2",
49
+ "cli-spinners": "^3.2.0",
50
+ "commander": "^14.0.0",
51
+ "dotenv": "^17.2.2",
52
+ "esbuild": "^0.25.10",
53
+ "eventsource": "^4.0.0",
54
+ "figlet": "^1.9.3",
55
+ "firebase": "^10.14.1",
56
+ "form-data": "^4.0.4",
57
+ "gradient-string": "^3.0.0",
58
+ "ink": "^6.3.1",
59
+ "ink-select-input": "^6.2.0",
60
+ "ink-spinner": "^5.0.0",
61
+ "inquirer": "^12.9.4",
62
+ "marked": "^15.0.12",
63
+ "marked-terminal": "^7.3.0",
64
+ "open": "^10.2.0",
65
+ "ora": "^8.2.0",
66
+ "react": "^19.2.0",
67
+ "socket.io-client": "^4.8.1",
68
+ "uuid": "^13.0.0",
69
+ "ws": "^8.18.3"
70
+ }
71
+ }